forked from mtusi2026/mtusi2026lab5
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d40313318 | ||
|
|
2639c08944 | ||
|
|
9899ee4676 | ||
|
|
7cd02da51d |
+5
-5
@@ -1,8 +1,8 @@
|
||||
# Скопируйте в .env для локального окружения; .env не коммитится.
|
||||
# Настройки приложения, Compose и очереди lab5.
|
||||
# Настройки приложения, Compose и очереди.
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
APP_ENV=development
|
||||
LOG_LEVEL=INFO
|
||||
|
||||
MAX_MESSAGES=100000
|
||||
@@ -35,7 +35,7 @@ DB_STATEMENT_TIMEOUT_MS=5000
|
||||
|
||||
# --- Балансировка и идемпотентность ---
|
||||
API_REPLICAS=2
|
||||
API_IMAGE=mtusi-messenger:lab5
|
||||
API_IMAGE=messenger:local
|
||||
API_BUILD_REVISION=development
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
SHUTDOWN_DRAIN_SECONDS=1
|
||||
@@ -48,7 +48,7 @@ LB_HOST_PORT=18081
|
||||
DB_HOST_PORT=25432
|
||||
REDIS_HOST_PORT=26379
|
||||
|
||||
# --- Lab4: MinIO, ограниченный upload и очистка журнала ---
|
||||
# --- MinIO, ограниченный upload и очистка журнала ---
|
||||
S3_ENDPOINT=http://minio:9000
|
||||
S3_REGION=us-east-1
|
||||
S3_BUCKET=messenger-attachments
|
||||
@@ -72,7 +72,7 @@ MINIO_ROOT_USER_FILE=/run/secrets/minio_root_user
|
||||
MINIO_ROOT_PASSWORD_FILE=/run/secrets/minio_root_password
|
||||
MINIO_BROWSER=off
|
||||
|
||||
# Lab5: отдельный RabbitMQ broker и ограниченный worker.
|
||||
# Отдельный RabbitMQ broker и ограниченный worker.
|
||||
WORKER_CONCURRENCY=2
|
||||
JOB_MAX_ATTEMPTS=5
|
||||
JOB_TIMEOUT_SECONDS=60
|
||||
|
||||
+1
-3
@@ -1,7 +1,5 @@
|
||||
FROM python:3.12.15-slim-bookworm
|
||||
|
||||
LABEL io.mtusi.messenger.secrets="file-v1"
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PIP_NO_CACHE_DIR=1 \
|
||||
@@ -19,7 +17,7 @@ COPY migrations ./migrations
|
||||
COPY app ./app
|
||||
|
||||
ARG API_BUILD_REVISION
|
||||
LABEL io.mtusi.messenger.revision=$API_BUILD_REVISION
|
||||
LABEL org.opencontainers.image.revision=$API_BUILD_REVISION
|
||||
|
||||
USER appuser
|
||||
|
||||
|
||||
@@ -4,14 +4,12 @@ PYTHON ?= $(if $(wildcard .venv/bin/python),.venv/bin/python,$(if $(wildcard ven
|
||||
PYTEST_ARGS ?=
|
||||
BASE_URL ?= http://localhost:$(or $(LB_HOST_PORT),8080)
|
||||
CA_FILE ?=
|
||||
SERVICE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
COMPOSE = docker compose --env-file .env
|
||||
|
||||
# Отдельный тестовый стенд: свой compose-проект, свои порты, открытые БД/Redis
|
||||
# (compose.test.yaml). COMPOSE_FILE подхватывают и scripts/*.sh.
|
||||
TEST_PROJECT ?= mtusi-messenger-lab5-test
|
||||
TEST_PROJECT ?= messenger-test
|
||||
TEST_LB_PORT ?= 28080
|
||||
TEST_DB_PORT ?= $(DB_HOST_PORT)
|
||||
TEST_REDIS_PORT ?= $(REDIS_HOST_PORT)
|
||||
@@ -27,58 +25,49 @@ TEST_REDIS_PASSWORD ?= $(if $(wildcard secrets/redis_password),$(file <secrets/r
|
||||
TEST_REDIS_DB ?= 15
|
||||
export TEST_DATABASE_URL TEST_REDIS_HOST TEST_REDIS_PORT TEST_REDIS_PASSWORD TEST_REDIS_DB
|
||||
|
||||
define wait_ready
|
||||
@for i in $$(seq 1 90); do \
|
||||
curl -sf "$(1)/health/ready" >/dev/null && exit 0; sleep 1; \
|
||||
done; echo "API $(1) не готов за 90 секунд" >&2; exit 1
|
||||
endef
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover \
|
||||
init test-grade4 test-s3 load-uploads cleanup-dry-run cleanup-apply \
|
||||
up down restart restore ps logs migrate migration instances \
|
||||
test-stand-up test-stand-down test-stand-destroy test-stand-ps \
|
||||
test-stand-smoke test-stand-persistence test-stand-failover \
|
||||
test-own test-docker test-limits test-concurrency test-migrations test-all \
|
||||
explain expiry-demo failure-demo test-nginx test-lab3-grade3 test-stand-idempotency \
|
||||
rolling-update failover-all test-lab3-grade4
|
||||
.PHONY: help init up down restart ps logs migrate migration worker-stop worker-start \
|
||||
cleanup-dry-run cleanup-apply check validate test test-unit test-pipeline \
|
||||
test-nginx test-storage test-outbox test-jobs test-persistence test-failover \
|
||||
test-suite test-stand-up test-stand-destroy
|
||||
|
||||
help:
|
||||
@echo "Lab5: init | worker-stop | worker-start | jobs-logs | cleanup-dry-run | cleanup-apply"
|
||||
@echo "Lab5: test-grade4 | test-jobs; legacy lab4: test-s3 | load-uploads"
|
||||
@echo "Проверки: check | validate | test | load | test-persistence ACTION_SCRIPT=scripts/restart.sh"
|
||||
@echo " test-failover ACTION_SCRIPT=scripts/stop-one.sh"
|
||||
@echo "Основной: up | down | restart | restore | ps | logs | migrate | instances"
|
||||
@echo "Тестовый: test-stand-up | test-stand-down | test-stand-destroy | test-stand-ps"
|
||||
@echo " test-stand-smoke | test-stand-persistence | test-stand-failover"
|
||||
@echo "Тесты: test-own | test-docker | test-limits | test-concurrency | test-migrations | test-all"
|
||||
@echo "Демо: explain | expiry-demo | failure-demo (на тестовом стенде)"
|
||||
@echo "Nginx: test-nginx (отдельный временный стенд без БД и приложения)"
|
||||
@echo "База lab3: test-lab3-grade3 (все проверки уровня 3 с удалением тестовых volumes)"
|
||||
@echo "База lab3: rolling-update | failover-all"
|
||||
@echo " test-lab3-grade4 (проверки lab3 на отдельном стенде с очисткой)"
|
||||
@echo "Миграции: migration m='описание' (нужен поднятый тестовый стенд)"
|
||||
|
||||
# --- Проверки API и сценариев отказа (tests/) ---
|
||||
@echo "Запуск: init | up | down | restart | ps | logs SERVICE=worker"
|
||||
@echo "Обслуживание: migrate | migration m='описание' | worker-stop | worker-start"
|
||||
@echo "Очистка объектов: cleanup-dry-run | cleanup-apply"
|
||||
@echo "Проверки: check | validate | test | test-pipeline | test-unit PYTEST_ARGS=..."
|
||||
@echo "Сервисы: test-nginx | test-storage | test-outbox | test-jobs"
|
||||
@echo "Отказы API (по запросу): test-persistence | test-failover"
|
||||
@echo "Автономный прогон с удалением тестового стенда: test-suite"
|
||||
|
||||
init:
|
||||
$(PYTHON) scripts/init_local.py
|
||||
|
||||
test-grade4:
|
||||
$(MAKE) check validate
|
||||
$(MAKE) test-stand-up
|
||||
$(MAKE) test-docker
|
||||
$(MAKE) test-stand-smoke
|
||||
$(MAKE) test-stand-idempotency
|
||||
$(MAKE) test-stand-persistence
|
||||
$(MAKE) test-stand-failover
|
||||
$(TEST_ENV) $(PYTHON) -m scripts.check_outbox_recovery --base-url "$(TEST_BASE_URL)"
|
||||
$(TEST_ENV) $(PYTHON) -m scripts.check_lab5_jobs --base-url "$(TEST_BASE_URL)"
|
||||
up:
|
||||
$(COMPOSE) up -d --build --wait --wait-timeout 120
|
||||
|
||||
test-s3:
|
||||
$(PYTHON) -m scripts.check_s3 --base-url "$(BASE_URL)" --with-outage --with-faults
|
||||
down:
|
||||
$(COMPOSE) down
|
||||
|
||||
load-uploads:
|
||||
$(PYTHON) -m scripts.upload_load --base-url "$(BASE_URL)" --concurrency 10
|
||||
restart:
|
||||
scripts/restart.sh
|
||||
|
||||
ps:
|
||||
$(COMPOSE) ps $(SERVICE)
|
||||
|
||||
logs:
|
||||
$(COMPOSE) logs -f $(SERVICE)
|
||||
|
||||
migrate:
|
||||
$(COMPOSE) run --rm --build migrate
|
||||
|
||||
migration:
|
||||
DB_HOST=localhost DB_PORT=$(TEST_DB_PORT) $(PYTHON) -m alembic revision --autogenerate -m "$(m)"
|
||||
|
||||
worker-stop:
|
||||
$(COMPOSE) stop worker
|
||||
|
||||
worker-start:
|
||||
$(COMPOSE) start worker
|
||||
|
||||
cleanup-dry-run:
|
||||
$(COMPOSE) run --rm --no-deps cleanup python -m app.core.cleanup --once
|
||||
@@ -92,161 +81,49 @@ check:
|
||||
validate:
|
||||
$(PYTHON) scripts/validate_openapi.py
|
||||
|
||||
test:
|
||||
$(PYTHON) tests/smoke.py --base-url "$(TEST_BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
# Все сохранённые регрессионные тесты запускаются явно; PYTEST_ARGS выбирает подмножество.
|
||||
test-unit:
|
||||
$(TEST_ENV) $(PYTHON) -m pytest -q $(PYTEST_ARGS)
|
||||
|
||||
test-pipeline:
|
||||
$(TEST_ENV) $(PYTHON) -m pytest -q student-tests/test_attachments.py student-tests/test_jobs.py student-tests/test_image_pipeline.py $(PYTEST_ARGS)
|
||||
|
||||
test-nginx:
|
||||
$(PYTHON) scripts/check_nginx.py
|
||||
|
||||
test-lab3-grade3:
|
||||
@set -eu; trap '$(TEST_COMPOSE) down --volumes --remove-orphans' EXIT; \
|
||||
$(MAKE) check validate; \
|
||||
$(MAKE) test-stand-up; \
|
||||
$(MAKE) test-docker test-stand-smoke test-stand-idempotency test-stand-persistence test-stand-failover
|
||||
test-storage:
|
||||
$(PYTHON) -m scripts.check_s3 --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-lab3-grade4:
|
||||
@set -eu; trap '$(TEST_COMPOSE) down --volumes --remove-orphans' EXIT; \
|
||||
$(MAKE) check validate; \
|
||||
$(MAKE) test-stand-up; \
|
||||
$(MAKE) test-docker test-stand-smoke test-stand-idempotency test-stand-persistence test-stand-failover; \
|
||||
$(TEST_ENV) $(PYTHON) -m scripts.check_grade4 --base-url "$(TEST_BASE_URL)"
|
||||
|
||||
test:
|
||||
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
load:
|
||||
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(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)
|
||||
|
||||
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)
|
||||
|
||||
# --- Основной стенд ---
|
||||
|
||||
rolling-update:
|
||||
$(PYTHON) -m scripts.rolling_update --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
failover-all:
|
||||
$(PYTHON) -m scripts.failover_all --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
up:
|
||||
$(COMPOSE) up -d --build
|
||||
$(call wait_ready,$(BASE_URL))
|
||||
|
||||
down:
|
||||
$(COMPOSE) down
|
||||
|
||||
restart:
|
||||
scripts/restart.sh
|
||||
$(call wait_ready,$(BASE_URL))
|
||||
|
||||
# Вернуть остановленную stop-one.sh реплику (compose up стартует остановленные контейнеры).
|
||||
restore:
|
||||
$(COMPOSE) up -d --wait api
|
||||
|
||||
ps:
|
||||
$(COMPOSE) ps
|
||||
|
||||
logs:
|
||||
$(COMPOSE) logs -f api nginx
|
||||
|
||||
migrate:
|
||||
$(COMPOSE) run --rm --build migrate
|
||||
|
||||
# Показать, какие реплики отвечают через LB (по заголовку X-Instance-Id).
|
||||
instances:
|
||||
@for i in $$(seq 1 10); do \
|
||||
curl -s -o /dev/null -D - "$(BASE_URL)/health/live" | grep -i '^x-instance-id' || echo "нет X-Instance-Id"; \
|
||||
done
|
||||
|
||||
# Генерация миграции против БД тестового стенда (основной стенд БД не публикует).
|
||||
migration:
|
||||
DB_HOST=localhost DB_PORT=$(TEST_DB_PORT) $(PYTHON) -m alembic revision --autogenerate -m "$(m)"
|
||||
|
||||
# --- Тестовый стенд ---
|
||||
|
||||
test-stand-up:
|
||||
$(TEST_COMPOSE) up -d --build
|
||||
$(call wait_ready,$(TEST_BASE_URL))
|
||||
$(TEST_COMPOSE) exec -T postgres sh -c 'createdb -U "$$POSTGRES_USER" "$$POSTGRES_DB"_test 2>&1 | grep -v "already exists"; true'
|
||||
|
||||
test-stand-down:
|
||||
$(TEST_COMPOSE) down
|
||||
|
||||
test-stand-destroy:
|
||||
$(TEST_COMPOSE) down -v
|
||||
|
||||
test-stand-ps:
|
||||
$(TEST_COMPOSE) ps
|
||||
|
||||
test-stand-smoke:
|
||||
$(PYTHON) tests/smoke.py --base-url "$(TEST_BASE_URL)"
|
||||
|
||||
test-stand-idempotency:
|
||||
$(PYTHON) -m scripts.check_idempotency --base-url "$(TEST_BASE_URL)"
|
||||
|
||||
test-stand-persistence:
|
||||
$(TEST_COMPOSE) ps
|
||||
$(TEST_ENV) $(PYTHON) tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url "$(TEST_BASE_URL)"
|
||||
$(TEST_COMPOSE) ps
|
||||
|
||||
test-stand-failover:
|
||||
$(TEST_COMPOSE) ps
|
||||
$(TEST_ENV) $(PYTHON) tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url "$(TEST_BASE_URL)"
|
||||
$(TEST_COMPOSE) ps -a api
|
||||
$(TEST_COMPOSE) up -d --wait api
|
||||
|
||||
# --- Собственные тесты (student-tests/) ---
|
||||
|
||||
test-own:
|
||||
$(PYTHON) -m pytest -q $(PYTEST_ARGS)
|
||||
|
||||
test-docker:
|
||||
$(TEST_ENV) DOCKER_TESTS=1 $(PYTHON) -m pytest -q $(PYTEST_ARGS)
|
||||
|
||||
test-limits:
|
||||
$(PYTHON) -m pytest student-tests/test_limits.py -q
|
||||
|
||||
test-concurrency:
|
||||
$(PYTHON) -m pytest student-tests/test_concurrency.py -q
|
||||
|
||||
test-migrations:
|
||||
$(PYTHON) -m pytest student-tests/test_migrations.py -q
|
||||
|
||||
test-all: test-stand-up test-docker test-stand-smoke test-stand-persistence
|
||||
|
||||
# --- Демо (на тестовом стенде) ---
|
||||
|
||||
explain:
|
||||
$(TEST_ENV) DB_HOST=localhost DB_PORT=$(TEST_DB_PORT) PYTHONPATH=. $(PYTHON) scripts/explain_history.py
|
||||
|
||||
expiry-demo: test-stand-up
|
||||
$(TEST_ENV) SESSION_TTL_SECONDS=3 $(COMPOSE) up -d api
|
||||
$(call wait_ready,$(TEST_BASE_URL))
|
||||
BASE_URL=$(TEST_BASE_URL) TTL=3 scripts/expiry_demo.sh
|
||||
$(TEST_COMPOSE) up -d api
|
||||
$(call wait_ready,$(TEST_BASE_URL))
|
||||
|
||||
failure-demo: test-stand-up
|
||||
$(TEST_ENV) BASE_URL=$(TEST_BASE_URL) scripts/failure_demo.sh
|
||||
|
||||
# --- Очередь lab5 ---
|
||||
.PHONY: worker-stop worker-start jobs-logs
|
||||
worker-stop:
|
||||
$(COMPOSE) stop worker
|
||||
|
||||
worker-start:
|
||||
$(COMPOSE) start worker
|
||||
|
||||
jobs-logs:
|
||||
$(COMPOSE) logs -f publisher worker broker
|
||||
|
||||
# Уже работающий изолированный стенд; сам цель его не поднимает.
|
||||
.PHONY: test-outbox-recovery
|
||||
test-outbox-recovery:
|
||||
test-outbox:
|
||||
$(PYTHON) -m scripts.check_outbox_recovery --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
.PHONY: test-jobs
|
||||
test-jobs:
|
||||
$(PYTHON) -m scripts.check_lab5_jobs --base-url "$(BASE_URL)"
|
||||
$(PYTHON) -m scripts.check_jobs --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-persistence:
|
||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(or $(ACTION_SCRIPT),scripts/restart.sh)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-failover:
|
||||
$(PYTHON) tests/resilience.py --mode failover --action-script "$(or $(ACTION_SCRIPT),scripts/stop-one.sh)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
# Отдельные PostgreSQL/Redis нужны для локальных тестов; тестовая БД создаётся явно.
|
||||
test-stand-up:
|
||||
$(TEST_COMPOSE) up -d --build --wait --wait-timeout 120
|
||||
$(TEST_COMPOSE) exec -T postgres sh -c 'psql -U "$$POSTGRES_USER" -d postgres -tAc "SELECT 1 FROM pg_database WHERE datname = '\''$${POSTGRES_DB}_test'\''" | grep -q 1 || createdb -U "$$POSTGRES_USER" "$${POSTGRES_DB}_test"'
|
||||
|
||||
test-stand-destroy:
|
||||
$(TEST_COMPOSE) down --volumes --remove-orphans
|
||||
|
||||
# Проверки текущего pipeline; полный регрессионный набор и отказы API — отдельные цели.
|
||||
test-suite:
|
||||
@set -eu; trap '$(TEST_COMPOSE) down --volumes --remove-orphans' EXIT; \
|
||||
$(MAKE) check validate; \
|
||||
$(MAKE) test-stand-up; \
|
||||
$(TEST_ENV) $(MAKE) test-pipeline; \
|
||||
$(TEST_ENV) $(MAKE) test BASE_URL="$(TEST_BASE_URL)"; \
|
||||
$(TEST_ENV) $(MAKE) test-storage BASE_URL="$(TEST_BASE_URL)"; \
|
||||
$(TEST_ENV) $(MAKE) test-outbox BASE_URL="$(TEST_BASE_URL)"; \
|
||||
$(TEST_ENV) $(MAKE) test-jobs BASE_URL="$(TEST_BASE_URL)";
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
# Отчёт — лабораторная 5
|
||||
|
||||
Автор: Григорян Илья Мурадович, БПИ2303.
|
||||
Целевая оценка текущего этапа: **4**. Обновлено 10.11.2026.
|
||||
Дальнейшая цель — 5; исследовательский трек ещё не выбран.
|
||||
Использована помощь Codex при реализации, проверках и исправлениях.
|
||||
Commit/PR: заполнить после публикации.
|
||||
- Автор, группа: Григорян Илья Мурадович, БПИ2303.
|
||||
- Целевая оценка: **4**. Все пункты уровней **3 и 4** реализованы и проверены.
|
||||
- Commit/PR: TODO после публикации.
|
||||
- Использованные источники, библиотеки и помощь ИИ: Python 3.12, FastAPI, SQLAlchemy, Pillow, aio-pika; [RabbitMQ](https://www.rabbitmq.com/docs/reliability), [Pillow](https://pillow.readthedocs.io/en/stable/); помощь Codex при реализации и проверках.
|
||||
|
||||
## Запуск
|
||||
## Запуск из чистого clone
|
||||
|
||||
Нужны Python 3.12, pip, Docker с Compose. Зависимости закреплены в requirements.txt.
|
||||
Нужны Python 3.12, pip и Docker Compose. Версии зависимостей закреплены в requirements.txt;
|
||||
основные образы — PostgreSQL 16.10, Redis 7.4.2, RabbitMQ 4.4.0 и nginx 1.28.0.
|
||||
|
||||
```sh
|
||||
python3 -m venv .venv
|
||||
@@ -16,210 +16,80 @@ python3 -m venv .venv
|
||||
make init
|
||||
make up
|
||||
make test
|
||||
make down
|
||||
```
|
||||
|
||||
`make init` создаёт отсутствующие .env и файлы secrets/, сохраняя существующие.
|
||||
Все environment-параметры Compose подставляются из .env; образец — .env.example.
|
||||
Пароли и S3 credentials читаются из файлов secrets, не включаются в задания.
|
||||
API не получает credentials брокера. По умолчанию HTTP доступен на
|
||||
http://localhost:18081. Broker, MinIO и основные PostgreSQL/Redis наружу не открыты.
|
||||
`make init` создаёт отсутствующие .env и secrets/, миграции и bootstrap выполняются
|
||||
при запуске. Все настройки берутся из .env; образец — .env.example.
|
||||
HTTP: http://localhost:18081. Внутренние хранилища и брокер наружу не открыты.
|
||||
`make down` сохраняет данные; `docker compose down --volumes` намеренно удаляет их.
|
||||
При обновлении схемы сначала остановить старые процессы, сохранив volumes.
|
||||
|
||||
При обновлении ранее запущенного стенда сначала остановить старые процессы
|
||||
через `make down` без удаления volumes, затем выполнить `make up`.
|
||||
Migrate применяет ревизии до a62c950e18b3 перед стартом приложения.
|
||||
Миграции добавляют jobs, варианты, бюджет попыток и аудит replay. Готовые
|
||||
вложения раннего варианта lab5 переобрабатываются для заполнения crop/WebP.
|
||||
При переходе Redis Streams → RabbitMQ миграция повторно публикует queued jobs
|
||||
из PostgreSQL; processing восстанавливаются по истечении lease. Старые процессы
|
||||
обоих брокеров во время перехода должны быть остановлены.
|
||||
## Архитектура и решения
|
||||
|
||||
## Инфраструктура и устойчивый приём
|
||||
API → приватный MinIO staging + PostgreSQL job/outbox → RabbitMQ → worker →
|
||||
конечные объекты MinIO + PostgreSQL metadata. Redis хранит сессии.
|
||||
Сохранены аутентификация, чаты, сообщения, пагинация и идемпотентность предыдущих работ.
|
||||
Загрузка возвращает **202 queued** после устойчивого приёма. Состояния:
|
||||
queued / processing / ready / failed; скачивание до ready возвращает 409.
|
||||
|
||||
| Компонент | Реализация | Данные |
|
||||
| --- | --- | --- |
|
||||
| API | две реплики FastAPI, Python 3.12.15 | PostgreSQL и Redis сессий |
|
||||
| Балансировка | nginx 1.28.0 | единая HTTP-точка входа |
|
||||
| База | PostgreSQL 16.10 | сообщения, metadata, jobs, outbox, audit |
|
||||
| Сессии | Redis 7.4.2, AOF always | redisdata |
|
||||
| Объекты | приватный MinIO | staging, originals, variants |
|
||||
| Брокер | RabbitMQ 4.4.0 | durable очередь, rabbitmqdata |
|
||||
| Publisher | отдельный процесс приложения, aio-pika 10.2.2 | PostgreSQL → RabbitMQ |
|
||||
| Worker | отдельный процесс приложения | RabbitMQ → MinIO + PostgreSQL |
|
||||
| Cleanup | отдельный процесс | незавершённые upload и terminal staging |
|
||||
RabbitMQ использует устойчивую очередь, сохранение сообщений на диск и подтверждения.
|
||||
Publisher отмечает публикацию после подтверждения брокера; worker подтверждает доставку
|
||||
после фиксации результата. Outbox восстанавливает разрыв COMMIT → publish.
|
||||
Фиксированные ключи объектов, блокировка job и lease защищают от повторов и устаревшего worker.
|
||||
|
||||
Redis используется для сессий. Очередь заданий использует RabbitMQ через AMQP.
|
||||
Очередь durable, сообщения persistent. Publisher ожидает подтверждение брокером
|
||||
приёма сообщения (publisher confirm) и только затем фиксирует published_attempt.
|
||||
При неизвестном результате публикации возможен дубль; намерение остаётся в БД.
|
||||
Подтверждение worker (consumer ack) следует после устойчивого результата или
|
||||
устойчиво сохранённого перехода retry/failed. При разрыве соединения RabbitMQ
|
||||
возвращает неподтверждённые доставки в очередь.
|
||||
Original не перекодируется. Варианты: JPEG thumbnail ≤256×256, центральный JPEG crop
|
||||
128×128 и WebP ≤1280×1280. JPEG quality=85, WebP quality=80/method=4; EXIF orientation
|
||||
учитывается, EXIF/ICC/XMP удаляются. Для JPEG alpha заменяется белой подложкой,
|
||||
WebP сохраняет прозрачность. Лимиты: 10 MiB, 40 млн пикселей, timeout 60 секунд,
|
||||
768 MiB и 20 секунд CPU на дочерний процесс; concurrency=2, prefetch=1, lease=90 секунд.
|
||||
|
||||
До ответа `202 queued` API полностью принимает и проверяет оригинал, сохраняет
|
||||
его в приватный staging и фиксирует attachment/job одной транзакцией PostgreSQL.
|
||||
Job одновременно служит transactional outbox — устойчивым намерением публикации.
|
||||
Worker и broker не входят в синхронный путь upload и readiness API. Остановка
|
||||
worker не заставляет API выполнять resize. При компенсации неоднозначного COMMIT
|
||||
API проверяет БД, чтобы не удалить оригинал уже принятого задания.
|
||||
Повторы ограничены пятью попытками. Задержка со случайным разбросом:
|
||||
c=min(120, 5×2^(n−1)), delay∈[c/2,c]. Постоянные ошибки завершаются сразу.
|
||||
Реестр failed и аудит находятся в PostgreSQL; явный replay проверяет исходник,
|
||||
выделяет новый бюджет и не запускает уже готовую job. Staging активных jobs сохраняется;
|
||||
ready очищается через сутки, failed — через семь суток.
|
||||
|
||||
Envelope соответствует contracts/jobs.schema.json: job_id, attachment_id,
|
||||
pipeline_version=1, attempt, created_at, schema_version, type и необязательный
|
||||
trace context. Bytes, имена объектов S3, URL и credentials туда не помещаются.
|
||||
Доступ к вложениям проверяется по участию в чате; content до ready возвращает 409.
|
||||
Аутентификация, пагинация, идемпотентность сообщений и ограничения lab4 сохранены.
|
||||
|
||||
## Изображения и ограничения
|
||||
|
||||
Worker повторно сверяет размер и SHA-256 исходника. Original сохраняется без
|
||||
перекодирования. Все варианты создаются в отдельном ограниченном процессе:
|
||||
|
||||
| Вариант | Формат и размеры | Параметры |
|
||||
| --- | --- | --- |
|
||||
| thumbnail | JPEG, вписан в 256×256 без увеличения | quality=85, белая подложка alpha |
|
||||
| crop | JPEG, центральный crop 128×128 | quality=85; маленькое изображение увеличивается |
|
||||
| optimized | WebP, вписан в 1280×1280 без увеличения | quality=80, method=4, alpha сохраняется |
|
||||
|
||||
Применяется EXIF orientation; EXIF/ICC/XMP и текстовые metadata не переносятся
|
||||
в варианты. JPEG создаётся из RGB с белой подложкой, WebP — из чистого RGBA.
|
||||
Алгоритмы используют Pillow 13.0.0. Metadata содержит реальные размеры, bytes и SHA-256.
|
||||
|
||||
Лимиты: PNG/JPEG, 10 MiB, 40 млн пикселей; JOB_TIMEOUT_SECONDS=60;
|
||||
IMAGE_MEMORY_MIB=768 адресного пространства и IMAGE_CPU_SECONDS=20 CPU на процесс.
|
||||
Контейнер worker: 2 GiB, 2 CPU, tmpfs 128 MiB. Отмена завершает дочерний процесс;
|
||||
S3 adapter дожидается SDK-потока перед освобождением блокировки/компенсацией.
|
||||
|
||||
## Повторы, идемпотентность и очистка
|
||||
|
||||
Состояния: queued → processing → ready; временный отказ возвращает queued,
|
||||
постоянный отказ или исчерпание бюджета переводит failed с безопасным error_code.
|
||||
JOB_MAX_ATTEMPTS=5 на цикл. Номер attempt монотонен, бюджет закреплён в attempt_limit.
|
||||
Для попытки n текущего цикла ceiling=min(JOB_RETRY_MAX_SECONDS,
|
||||
JOB_RETRY_SECONDS × 2^(n−1)); delay равномерно выбирается в [ceiling/2, ceiling].
|
||||
База — 5 секунд, максимум — 120 секунд. next_attempt_at сохраняется в БД;
|
||||
дубликат не пересчитывает задержку. Последняя причина остаётся в job даже при
|
||||
публичном retry_exhausted. Ошибки изображения/исходника/конфигурации постоянные;
|
||||
timeout, временные ошибки S3/сети и файловой системы повторяются.
|
||||
|
||||
Job захватывается с lease_token и JOB_LEASE_SECONDS=90. Publisher восстанавливает
|
||||
истёкший processing в пределах бюджета. Перед PUT worker блокирует строку job,
|
||||
проверяет актуальность token и lease, держит блокировку до записи original,
|
||||
трёх вариантов и COMMIT ready. Reaper пропускает заблокированные строки.
|
||||
Устаревшая попытка не может начать запись. Фиксированные ключи по
|
||||
(attachment_id, pipeline_version, variant) исключают второй набор объектов.
|
||||
Дубль ready подтверждается без обработки и PUT. Это доставка как минимум один
|
||||
раз с идемпотентным эффектом, не exactly-once выполнение.
|
||||
|
||||
WORKER_CONCURRENCY=2, отдельный канал каждого consumer, prefetch=1 на канал.
|
||||
Publisher и worker используют init:true: Python не является PID 1, поэтому
|
||||
fault hooks с SIGKILL действительно завершают процесс. SIGTERM отменяет работу
|
||||
без преждевременного ack. Некорректные envelopes отклоняются без сохранения payload.
|
||||
|
||||
Queued/processing staging не удаляется. Для ready retention — 86400 секунд;
|
||||
для failed — FAILED_STAGING_RETENTION_SECONDS=604800 (семь суток).
|
||||
Cleanup и replay блокируют одну строку job. Если staging совпадает с готовым
|
||||
original, объект сохраняется. Частичные конечные объекты failed автоматически
|
||||
не удаляются; после replay используются те же ключи.
|
||||
|
||||
## Реестр failed и операторский replay
|
||||
|
||||
Failed registry находится в PostgreSQL. Команды требуют операторского доступа
|
||||
к Docker/credentials стенда; публичного endpoint для replay нет:
|
||||
Операторские команды:
|
||||
|
||||
```sh
|
||||
docker compose run --rm --no-deps worker python -m app.core.job_admin list-failed
|
||||
docker compose run --rm --no-deps worker python -m app.core.job_admin show JOB_ID
|
||||
docker compose run --rm --no-deps worker python -m app.core.job_admin replay JOB_ID --request-id REQUEST_UUID --actor operator --reason dependency_restored
|
||||
docker compose run --rm --no-deps worker python -m app.core.job_admin history JOB_ID
|
||||
```
|
||||
|
||||
JOB_ID/REQUEST_UUID заменить настоящими UUID. Reasons: dependency_restored,
|
||||
configuration_fixed, manual_review. Actor — аудиторская метка, не система входа.
|
||||
Replay принимает только failed, сверяет сохранённый исходник по bytes/SHA-256,
|
||||
атомарно записывает аудит и новый ограниченный бюджет. Счётчик attempt не
|
||||
сбрасывается, старые envelopes не запускают новый цикл. Повтор того же request-id
|
||||
с теми же параметрами возвращает already_applied даже после ready; конфликт
|
||||
параметров отклоняется. После неоднозначного ответа повторяют тот же request-id.
|
||||
Готовую job с новым request-id повторить нельзя. После удаления staging replay
|
||||
отклоняется с source_expired; отсутствующий объект даёт source_missing.
|
||||
JOB_ID и REQUEST_UUID заменить UUID. Повтор команды с тем же request-id безопасен.
|
||||
|
||||
## Проверки уровня 3 и 4
|
||||
## Доказательства критериев
|
||||
|
||||
Полный воспроизводимый прогон на отдельном стенде:
|
||||
`make test-suite` поднимает отдельный стенд, проверяет pipeline и удаляет контейнеры,
|
||||
сети и volumes при завершении, включая ошибку. Полная сохранённая регрессия запускается
|
||||
отдельно через `make test-unit`; отдельные сервисы — `test-nginx` и `test-storage`.
|
||||
Проверки pipeline: 42 теста. Полная сохранённая регрессия: 201 тест.
|
||||
Публичные smoke/persistence/failover прошли. Для отдельных pytest-прогонов нужен
|
||||
`make test-stand-up`; после проверки — `make test-stand-destroy`.
|
||||
|
||||
```sh
|
||||
make test-grade4 PYTHON=.venv/bin/python
|
||||
```
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | 202 → ready, неизменный original, JPEG thumbnail | evidence/verification.json |
|
||||
| Устойчивый приём и сохранение возможностей lab4 | DOCKER_TESTS=1 make test-unit; make test-persistence | Данные и сессия сохранены, загрузка асинхронная | evidence/verification.json |
|
||||
| Отдельные broker/worker, поздний ack | make test-jobs | Сообщения сохранены, очередь подтверждена | evidence/jobs.json |
|
||||
| Состояния, ограниченные повторы, идемпотентность | make test-pipeline; make test-jobs | failed после бюджета, дубли не создают новые объекты | evidence/verification.json |
|
||||
| Остановка worker и рестарт API/брокера | make test-jobs | То же вложение стало ready, сообщение пережило рестарт | evidence/jobs.json |
|
||||
| Crop/WebP и ограничения worker | make test-pipeline; make test-jobs | Форматы/размеры, metadata и лимиты проверены | evidence/verification.json |
|
||||
| Разрыв COMMIT → publish | make test-outbox | SIGKILL publisher, затем ready без нового upload | evidence/verification.json |
|
||||
| Backoff/jitter, failed registry, replay | make test-jobs | Постоянные/временные ошибки различаются, replay безопасен | evidence/jobs.json |
|
||||
| Crash после PUT до ack, lease и cleanup | make test-jobs; make test-pipeline | Тот же результат, prefetch=1; активный staging сохранён | evidence/jobs.json; evidence/verification.json |
|
||||
|
||||
Цель последовательно запускает контракт/OpenAPI, тестовый стенд, собственные
|
||||
тесты с реальными PostgreSQL/Redis, публичный smoke, идемпотентность через две
|
||||
реплики, persistence/failover, outbox и сценарии worker/replay. Подготовка БД
|
||||
для pytest выполняется только в выделенной базе *_test, Redis — DB15.
|
||||
Публичные tests/ и обязательные contracts/ не изменены.
|
||||
## Эксперименты и отказы
|
||||
|
||||
Отдельные сценарии на уже работающем изолированном стенде:
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| Crash после PUT до COMMIT | Повтор той же job | ready на второй попытке, те же четыре объекта и SHA-256 | После lease/retry; потерь нет |
|
||||
| Crash после COMMIT до ack | Готовый дубль без обработки | Metadata и Last-Modified не изменились | После доставки; потерь нет |
|
||||
| Временная / постоянная ошибка | Ограниченный retry / немедленный failed | Пять / одна попытка; явный replay завершился ready | В пределах бюджета; потерь нет |
|
||||
|
||||
```sh
|
||||
make test-outbox-recovery BASE_URL=http://localhost:28080
|
||||
make test-jobs BASE_URL=http://localhost:28080
|
||||
```
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
При выборе своего проекта задать COMPOSE_PROJECT_NAME и соответствующие порты
|
||||
в окружении. Сценарии сверяют BASE_URL с API выбранного Compose-проекта,
|
||||
создают синтетические данные и возвращают штатные worker/publisher в finally.
|
||||
Перезапуски сохраняют volumes. Сброса пользовательских данных нет.
|
||||
|
||||
Результаты и сопоставление каждому пункту приведены в evidence/lab5-verification.json;
|
||||
подробные снимки состояний/объектов/retry — в evidence/lab5-jobs.json.
|
||||
Секреты, tokens и исходные broker payload в evidence не записываются.
|
||||
|
||||
## Фактический результат проверок
|
||||
|
||||
Все перечисленные проверки завершились успешно на отдельном проекте
|
||||
`mtusi-lab5-verification`, HTTP http://localhost:28080, без удаления volumes:
|
||||
|
||||
| Проверка | Результат |
|
||||
| --- | --- |
|
||||
| Собственные тесты PostgreSQL/Redis/API/миграций/изображений/OS-лимитов | 199 passed, без пропусков |
|
||||
| Дополнительные timeout и failed retention/SHA-256 | 2 passed |
|
||||
| Контракт, OpenAPI и Compose config | PASS |
|
||||
| Публичный smoke | PASS |
|
||||
| 24 конкурентных повтора сообщения через две API-реплики | PASS |
|
||||
| Публичные persistence и failover | PASS |
|
||||
| SIGKILL publisher после COMMIT до publish | 137 → queued → ready; без повторного upload |
|
||||
| Остановленный worker, рестарт API/брокера/хранилищ | ready того же ID; сообщение RabbitMQ сохранилось с volume |
|
||||
| SIGKILL после четырёх PUT до COMMIT | processing → ready на попытке 2; тот же набор/checksums объектов |
|
||||
| SIGKILL после COMMIT до ack | ready-дубль подтверждён без изменения metadata/Last-Modified |
|
||||
| Временная ошибка и replay | failed после 5 попыток, затем ready; повтор request-id безопасен |
|
||||
| Постоянная ошибка и replay | failed после 1 попытки, затем ready; новый replay ready отклонён |
|
||||
| Конкуренция/подтверждения RabbitMQ после сценариев | 2 consumer, prefetch=1; ready=0, unacknowledged=0 |
|
||||
| Неизменность публичных tests/contracts/README и whitespace | PASS |
|
||||
|
||||
Суммарно выполнен 201 собственный тест двумя прогонами; новые тесты включены
|
||||
в последующие полные запуски make test-grade4. Тесты намеренно меняют только
|
||||
выделенную БД *_test и Redis DB15. API и worker в интеграционных сценариях
|
||||
используют собственную БД тестового Compose-проекта.
|
||||
|
||||
Измеренные задержки пяти неудачных попыток: 4.613, 6.837, 17.323, 30.885,
|
||||
42.633 секунды; все попали в соответствующие интервалы jitter. Задержка
|
||||
последней failed-попытки сохраняется для диагностики, автоматический retry
|
||||
после исчерпания бюджета не выполняется. Ограничение максимума проверено отдельно.
|
||||
|
||||
Во время проверки исправлена проблема fault hooks с PID 1 через init:true.
|
||||
Старые собственные проверки lab4 адаптированы к обязательному переходу
|
||||
202 queued → ready; публичные проверки не изменены. Цель make test-grade4
|
||||
переведена на lab5 и последовательные сценарии, чтобы рестарты инфраструктуры
|
||||
не пересекались с регрессией БД. RabbitMQ используется как брокер, Redis — для сессий.
|
||||
|
||||
## Границы результата
|
||||
|
||||
Проверки относятся к одному Docker-хосту и рестартам с сохранением volumes.
|
||||
PostgreSQL, RabbitMQ и MinIO не реплицированы; потеря диска/хоста не покрыта.
|
||||
Ожидание в очереди не ограничено; admission control и исследование перегрузки
|
||||
относятся к будущему уровню 5. Pipeline фиксирован на версии 1; изменение
|
||||
алгоритмов требует решения о новой версии/миграции результатов.
|
||||
|
||||
Официальные источники: [RabbitMQ reliability](https://www.rabbitmq.com/docs/reliability),
|
||||
[publisher confirms и consumer acknowledgements](https://www.rabbitmq.com/docs/confirms),
|
||||
[aio-pika](https://docs.aio-pika.com/quick-start.html),
|
||||
[Pillow ImageOps](https://pillow.readthedocs.io/en/stable/reference/ImageOps.html),
|
||||
[Pillow WebP](https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#webp).
|
||||
Один Docker-хост, без репликации хранилищ и защиты от потери диска. Очередь не имеет
|
||||
admission control; pipeline фиксирован на версии 1. Доставка как минимум один раз,
|
||||
с идемпотентным результатом.
|
||||
|
||||
@@ -8,7 +8,14 @@ from aio_pika.exceptions import AMQPException, ChannelInvalidStateError
|
||||
from sqlalchemy.exc import InterfaceError, OperationalError
|
||||
from sqlalchemy.exc import TimeoutError as PoolTimeoutError
|
||||
|
||||
TRANSIENT_JOB_ERRORS = (AMQPException, ChannelInvalidStateError, InterfaceError, OperationalError, PoolTimeoutError, OSError)
|
||||
TRANSIENT_JOB_ERRORS = (
|
||||
AMQPException,
|
||||
ChannelInvalidStateError,
|
||||
InterfaceError,
|
||||
OperationalError,
|
||||
PoolTimeoutError,
|
||||
OSError,
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
|
||||
+3
-1
@@ -21,7 +21,9 @@ async def cleanup_once(factory, storage, apply: bool, jobs: JobSettings) -> bool
|
||||
async with factory() as session:
|
||||
result = await reconcile_attachments(session, storage, dry_run=not apply)
|
||||
staging = await cleanup_staging(session, storage, jobs, apply=apply)
|
||||
print(json.dumps({**asdict(result), "terminal_staging": staging}), flush=True)
|
||||
print(
|
||||
json.dumps({**asdict(result), "terminal_staging": staging}), flush=True
|
||||
)
|
||||
except RECOVERABLE_STORAGE_ERRORS as error:
|
||||
log_recoverable_error("Reconciliation", error)
|
||||
completed = False
|
||||
|
||||
@@ -5,7 +5,9 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class ImageSettings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_prefix="IMAGE_", env_file=".env", extra="ignore")
|
||||
model_config = SettingsConfigDict(
|
||||
env_prefix="IMAGE_", env_file=".env", extra="ignore"
|
||||
)
|
||||
|
||||
jpeg_quality: int = Field(default=85, ge=1, le=95)
|
||||
webp_quality: int = Field(default=80, ge=1, le=100)
|
||||
|
||||
+22
-5
@@ -9,7 +9,13 @@ from app.core.background import log_background_error
|
||||
from app.core.config import Settings
|
||||
from app.core.database import create_db_engine, create_session_factory
|
||||
from app.core.jobs import JobSettings
|
||||
from app.domain.job_admin import REPLAY_REASONS, history, list_failed, replay_failed_job, show_job
|
||||
from app.domain.job_admin import (
|
||||
REPLAY_REASONS,
|
||||
history,
|
||||
list_failed,
|
||||
replay_failed_job,
|
||||
show_job,
|
||||
)
|
||||
from app.errors.exceptions import JobOperationError
|
||||
from app.storage.s3 import create_s3_storage
|
||||
|
||||
@@ -29,8 +35,15 @@ async def execute(args):
|
||||
result = await history(session, args.job_id)
|
||||
else:
|
||||
storage = create_s3_storage(settings.s3)
|
||||
result = await replay_failed_job(session, storage, JobSettings(), args.job_id,
|
||||
request_id=args.request_id, actor=args.actor, reason=args.reason)
|
||||
result = await replay_failed_job(
|
||||
session,
|
||||
storage,
|
||||
JobSettings(),
|
||||
args.job_id,
|
||||
request_id=args.request_id,
|
||||
actor=args.actor,
|
||||
reason=args.reason,
|
||||
)
|
||||
print(json.dumps(result, default=str), flush=True)
|
||||
finally:
|
||||
if storage is not None:
|
||||
@@ -39,10 +52,14 @@ async def execute(args):
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Реестр failed и явный replay с аудитом")
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Реестр failed и явный replay с аудитом"
|
||||
)
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
listing = commands.add_parser("list-failed")
|
||||
listing.add_argument("--limit", type=int, choices=range(1, 501), default=50, metavar="1..500")
|
||||
listing.add_argument(
|
||||
"--limit", type=int, choices=range(1, 501), default=50, metavar="1..500"
|
||||
)
|
||||
for name in ("show", "history", "replay"):
|
||||
command = commands.add_parser(name)
|
||||
command.add_argument("job_id", type=UUID)
|
||||
|
||||
+42
-9
@@ -12,7 +12,12 @@ from uuid import UUID, uuid4
|
||||
from PIL import features
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.core.background import TRANSIENT_JOB_ERRORS, log_background_error, shutdown_event, wait_or_stop
|
||||
from app.core.background import (
|
||||
TRANSIENT_JOB_ERRORS,
|
||||
log_background_error,
|
||||
shutdown_event,
|
||||
wait_or_stop,
|
||||
)
|
||||
from app.core.config import Settings
|
||||
from app.core.database import create_db_engine, create_session_factory
|
||||
from app.core.jobs import JobSettings
|
||||
@@ -34,7 +39,10 @@ class Faults:
|
||||
object_name: str = "optimized"
|
||||
|
||||
def kill(self, attachment_id: UUID, phase: str) -> None:
|
||||
print(json.dumps({"fault": phase, "attachment_id": str(attachment_id)}), flush=True)
|
||||
print(
|
||||
json.dumps({"fault": phase, "attachment_id": str(attachment_id)}),
|
||||
flush=True,
|
||||
)
|
||||
os.kill(os.getpid(), signal.SIGKILL)
|
||||
|
||||
def after_object(self, attachment_id: UUID, name: str) -> None:
|
||||
@@ -52,7 +60,14 @@ class Faults:
|
||||
raise ProcessingError("injected_permanent")
|
||||
|
||||
|
||||
async def consume_connected(factory, storage, broker: JobBroker, settings: JobSettings, stop: asyncio.Event, faults: Faults) -> None:
|
||||
async def consume_connected(
|
||||
factory,
|
||||
storage,
|
||||
broker: JobBroker,
|
||||
settings: JobSettings,
|
||||
stop: asyncio.Event,
|
||||
faults: Faults,
|
||||
) -> None:
|
||||
consumer = uuid4().hex
|
||||
while not stop.is_set():
|
||||
try:
|
||||
@@ -68,8 +83,12 @@ async def consume_connected(factory, storage, broker: JobBroker, settings: JobSe
|
||||
try:
|
||||
async with factory() as session:
|
||||
acknowledge = await process_attachment_job(
|
||||
session, storage, message, settings,
|
||||
after_object=faults.after_object, before_processing=faults.before_processing,
|
||||
session,
|
||||
storage,
|
||||
message,
|
||||
settings,
|
||||
after_object=faults.after_object,
|
||||
before_processing=faults.before_processing,
|
||||
)
|
||||
except ProcessingError:
|
||||
await broker.reject_invalid(delivery.id)
|
||||
@@ -107,7 +126,10 @@ async def run_worker(faults: Faults) -> None:
|
||||
storage = create_s3_storage(settings.s3)
|
||||
factory = create_session_factory(engine)
|
||||
async with asyncio.TaskGroup() as group:
|
||||
tasks = [group.create_task(consume(factory, storage, jobs, stop, faults)) for _ in range(jobs.worker_concurrency)]
|
||||
tasks = [
|
||||
group.create_task(consume(factory, storage, jobs, stop, faults))
|
||||
for _ in range(jobs.worker_concurrency)
|
||||
]
|
||||
await stop.wait()
|
||||
# Отмена убивает resize-процесс, дожидается SDK и не отправляет ack.
|
||||
for task in tasks:
|
||||
@@ -119,11 +141,22 @@ async def run_worker(faults: Faults) -> None:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Image worker с явными fault-injection hooks")
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Image worker с явными fault-injection hooks"
|
||||
)
|
||||
modes = parser.add_mutually_exclusive_group()
|
||||
for flag in ("crash-after-object", "crash-before-ack", "fail-transient", "fail-permanent"):
|
||||
for flag in (
|
||||
"crash-after-object",
|
||||
"crash-before-ack",
|
||||
"fail-transient",
|
||||
"fail-permanent",
|
||||
):
|
||||
modes.add_argument("--" + flag, type=UUID, metavar="ATTACHMENT_ID")
|
||||
parser.add_argument("--object-name", choices=("original", "thumbnail", "crop", "optimized"), default="optimized")
|
||||
parser.add_argument(
|
||||
"--object-name",
|
||||
choices=("original", "thumbnail", "crop", "optimized"),
|
||||
default="optimized",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
faults = Faults(**vars(args))
|
||||
try:
|
||||
|
||||
+3
-1
@@ -29,7 +29,9 @@ class JobSettings(BaseSettings):
|
||||
@model_validator(mode="after")
|
||||
def validate_lease(self) -> Self:
|
||||
if self.job_lease_seconds < self.job_timeout_seconds + 30:
|
||||
raise ValueError("Lease должен превышать timeout задания минимум на 30 секунд")
|
||||
raise ValueError(
|
||||
"Lease должен превышать timeout задания минимум на 30 секунд"
|
||||
)
|
||||
if self.job_retry_max_seconds < self.job_retry_seconds:
|
||||
raise ValueError("Retry maximum must be at least the base delay")
|
||||
return self
|
||||
|
||||
@@ -8,7 +8,12 @@ import os
|
||||
import signal
|
||||
from uuid import UUID
|
||||
|
||||
from app.core.background import TRANSIENT_JOB_ERRORS, log_background_error, shutdown_event, wait_or_stop
|
||||
from app.core.background import (
|
||||
TRANSIENT_JOB_ERRORS,
|
||||
log_background_error,
|
||||
shutdown_event,
|
||||
wait_or_stop,
|
||||
)
|
||||
from app.core.config import Settings
|
||||
from app.core.database import create_db_engine, create_session_factory
|
||||
from app.core.jobs import JobSettings
|
||||
@@ -18,7 +23,10 @@ from app.storage.broker import JobBroker
|
||||
|
||||
def crash_before_publish(attachment_id: UUID) -> None:
|
||||
"""Реальный SIGKILL после чтения принятой job, до publisher confirm и отметки publish."""
|
||||
print(json.dumps({"fault": "before_publish", "attachment_id": str(attachment_id)}), flush=True)
|
||||
print(
|
||||
json.dumps({"fault": "before_publish", "attachment_id": str(attachment_id)}),
|
||||
flush=True,
|
||||
)
|
||||
os.kill(os.getpid(), signal.SIGKILL)
|
||||
|
||||
|
||||
@@ -39,8 +47,14 @@ async def run_publisher(crash_attachment_id: UUID | None = None) -> None:
|
||||
async with factory() as session:
|
||||
await recover_expired_jobs(session, jobs)
|
||||
published = await publish_next_job(
|
||||
session, broker, attachment_id=crash_attachment_id,
|
||||
before_publish=crash_before_publish if crash_attachment_id is not None else None,
|
||||
session,
|
||||
broker,
|
||||
attachment_id=crash_attachment_id,
|
||||
before_publish=(
|
||||
crash_before_publish
|
||||
if crash_attachment_id is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
except TRANSIENT_JOB_ERRORS as error:
|
||||
log_background_error("Publisher deferred", error)
|
||||
@@ -53,9 +67,13 @@ async def run_publisher(crash_attachment_id: UUID | None = None) -> None:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Публикация устойчивых jobs в RabbitMQ")
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Публикация устойчивых jobs в RabbitMQ"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--crash-before-publish", type=UUID, metavar="ATTACHMENT_ID",
|
||||
"--crash-before-publish",
|
||||
type=UUID,
|
||||
metavar="ATTACHMENT_ID",
|
||||
help="аварийно завершить этот процесс перед публикацией только указанного вложения",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
+1
-2
@@ -4,6 +4,7 @@ from redis.backoff import NoBackoff
|
||||
|
||||
from app.core.config import Settings
|
||||
|
||||
|
||||
def create_redis_client(settings: Settings) -> Redis:
|
||||
password = (
|
||||
settings.redis_password.get_secret_value() if settings.redis_password else None
|
||||
@@ -21,5 +22,3 @@ def create_redis_client(settings: Settings) -> Redis:
|
||||
decode_responses=True,
|
||||
)
|
||||
return Redis.from_pool(pool)
|
||||
|
||||
|
||||
|
||||
+16
-4
@@ -6,6 +6,7 @@ from urllib.parse import urlsplit
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class S3Settings(BaseSettings):
|
||||
endpoint: str = "http://minio:9000"
|
||||
region: str = "us-east-1"
|
||||
@@ -24,12 +25,23 @@ class S3Settings(BaseSettings):
|
||||
cleanup_grace_seconds: int = Field(default=86_400, ge=300)
|
||||
cleanup_interval_seconds: int = Field(default=300, ge=1)
|
||||
|
||||
model_config = SettingsConfigDict(env_prefix="S3_", env_file=".env", extra="ignore", frozen=True)
|
||||
model_config = SettingsConfigDict(
|
||||
env_prefix="S3_", env_file=".env", extra="ignore", frozen=True
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_endpoint(self):
|
||||
url = urlsplit(self.endpoint)
|
||||
if (url.scheme not in {"http", "https"} or not url.hostname or url.username
|
||||
or url.password or url.path not in {"", "/"} or url.query or url.fragment):
|
||||
raise ValueError("S3_ENDPOINT должен быть http(s) адресом без credentials/пути")
|
||||
if (
|
||||
url.scheme not in {"http", "https"}
|
||||
or not url.hostname
|
||||
or url.username
|
||||
or url.password
|
||||
or url.path not in {"", "/"}
|
||||
or url.query
|
||||
or url.fragment
|
||||
):
|
||||
raise ValueError(
|
||||
"S3_ENDPOINT должен быть http(s) адресом без credentials/пути"
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -13,11 +13,15 @@ def main() -> int:
|
||||
settings = ImageSettings()
|
||||
memory = settings.memory_mib * 1024 * 1024
|
||||
resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (settings.cpu_seconds, settings.cpu_seconds))
|
||||
resource.setrlimit(
|
||||
resource.RLIMIT_CPU, (settings.cpu_seconds, settings.cpu_seconds)
|
||||
)
|
||||
source, directory, metadata, content_type, maximum = sys.argv[1:]
|
||||
code = 0
|
||||
try:
|
||||
result = create_variants(Path(source), Path(directory), content_type, int(maximum), settings)
|
||||
result = create_variants(
|
||||
Path(source), Path(directory), content_type, int(maximum), settings
|
||||
)
|
||||
Path(metadata).write_text(result.model_dump_json())
|
||||
except IMAGE_WORKER_ERRORS as error:
|
||||
code = pipeline_worker_error_code(error)
|
||||
|
||||
@@ -29,13 +29,17 @@ class Claim:
|
||||
acknowledge: bool = False
|
||||
|
||||
|
||||
async def enqueue_attachment_job(session: AsyncSession, attachment_id: UUID, staging_key: str) -> UUID:
|
||||
async def enqueue_attachment_job(
|
||||
session: AsyncSession, attachment_id: UUID, staging_key: str
|
||||
) -> UUID:
|
||||
"""Включить намерение обработки в транзакцию queued metadata; без commit."""
|
||||
return await jobs.create_job(session, attachment_id, staging_key)
|
||||
|
||||
|
||||
async def publish_next_job(
|
||||
session: AsyncSession, broker: JobBroker, *,
|
||||
session: AsyncSession,
|
||||
broker: JobBroker,
|
||||
*,
|
||||
attachment_id: UUID | None = None,
|
||||
before_publish: Callable[[UUID], None] | None = None,
|
||||
) -> bool:
|
||||
@@ -45,24 +49,33 @@ async def publish_next_job(
|
||||
if job is not None:
|
||||
if before_publish is not None:
|
||||
before_publish(job.attachment_id)
|
||||
await broker.publish_job(JobMessage(
|
||||
job_id=job.id, attachment_id=job.attachment_id,
|
||||
pipeline_version=job.pipeline_version, attempt=job.attempt + 1,
|
||||
created_at=job.created_at,
|
||||
))
|
||||
await broker.publish_job(
|
||||
JobMessage(
|
||||
job_id=job.id,
|
||||
attachment_id=job.attachment_id,
|
||||
pipeline_version=job.pipeline_version,
|
||||
attempt=job.attempt + 1,
|
||||
created_at=job.created_at,
|
||||
)
|
||||
)
|
||||
outbox.mark_published(job)
|
||||
await session.commit()
|
||||
return published
|
||||
|
||||
|
||||
async def claim_job(session: AsyncSession, message: JobMessage, settings: JobSettings) -> Claim:
|
||||
async def claim_job(
|
||||
session: AsyncSession, message: JobMessage, settings: JobSettings
|
||||
) -> Claim:
|
||||
"""Дубликат не захватывает живую аренду и не откатывает terminal-состояние."""
|
||||
row = await jobs.lock_job(session, message.job_id)
|
||||
result = Claim()
|
||||
if row is None:
|
||||
raise ProcessingError("unknown_job")
|
||||
job, attachment = row
|
||||
if message.attachment_id != attachment.id or message.pipeline_version != job.pipeline_version:
|
||||
if (
|
||||
message.attachment_id != attachment.id
|
||||
or message.pipeline_version != job.pipeline_version
|
||||
):
|
||||
raise ProcessingError("invalid_job")
|
||||
now = await jobs.database_time(session)
|
||||
if job.attempt_limit is None:
|
||||
@@ -77,16 +90,32 @@ async def claim_job(session: AsyncSession, message: JobMessage, settings: JobSet
|
||||
elif message.attempt > job.attempt + 1:
|
||||
raise ProcessingError("invalid_attempt")
|
||||
elif attachment.status == "queued" and job.next_attempt_at <= now:
|
||||
if job.attempt >= (job.attempt_limit or settings.job_max_attempts) or job.staging_key is None:
|
||||
jobs.record_failure(job, attachment, now, "retry_exhausted", terminal=True, retry_seconds=0)
|
||||
if (
|
||||
job.attempt >= (job.attempt_limit or settings.job_max_attempts)
|
||||
or job.staging_key is None
|
||||
):
|
||||
jobs.record_failure(
|
||||
job, attachment, now, "retry_exhausted", terminal=True, retry_seconds=0
|
||||
)
|
||||
result = Claim(acknowledge=True)
|
||||
else:
|
||||
result = Claim(work=jobs.start_job(job, attachment, uuid4(), now, settings.job_lease_seconds))
|
||||
result = Claim(
|
||||
work=jobs.start_job(
|
||||
job, attachment, uuid4(), now, settings.job_lease_seconds
|
||||
)
|
||||
)
|
||||
await session.commit()
|
||||
return result
|
||||
|
||||
|
||||
async def save_failure(session: AsyncSession, work: JobWork, settings: JobSettings, code: str, *, permanent: bool) -> None:
|
||||
async def save_failure(
|
||||
session: AsyncSession,
|
||||
work: JobWork,
|
||||
settings: JobSettings,
|
||||
code: str,
|
||||
*,
|
||||
permanent: bool,
|
||||
) -> None:
|
||||
# Неоднозначный COMMIT проверяется повторным чтением: ready сохраняется.
|
||||
await session.rollback()
|
||||
row = await jobs.lock_job(session, work.job_id)
|
||||
@@ -95,10 +124,14 @@ async def save_failure(session: AsyncSession, work: JobWork, settings: JobSettin
|
||||
if attachment.status == "processing" and job.lease_token == work.lease_token:
|
||||
exhausted = job.attempt >= (job.attempt_limit or settings.job_max_attempts)
|
||||
jobs.record_failure(
|
||||
job, attachment, await jobs.database_time(session),
|
||||
job,
|
||||
attachment,
|
||||
await jobs.database_time(session),
|
||||
"retry_exhausted" if exhausted and not permanent else code,
|
||||
terminal=permanent or exhausted,
|
||||
retry_seconds=retry_delay(settings, job.attempt - job.cycle_start_attempt),
|
||||
retry_seconds=retry_delay(
|
||||
settings, job.attempt - job.cycle_start_attempt
|
||||
),
|
||||
)
|
||||
job.last_error_code = code
|
||||
job.last_error_permanent = permanent
|
||||
@@ -106,7 +139,9 @@ async def save_failure(session: AsyncSession, work: JobWork, settings: JobSettin
|
||||
|
||||
|
||||
async def build_result(
|
||||
session: AsyncSession, storage: MinioStorage, work: JobWork,
|
||||
session: AsyncSession,
|
||||
storage: MinioStorage,
|
||||
work: JobWork,
|
||||
after_object: Callable[[UUID, str], None] | None = None,
|
||||
) -> bool:
|
||||
"""Фиксированные ключи и блокировка job защищают PUT от устаревшей попытки."""
|
||||
@@ -129,26 +164,42 @@ async def build_result(
|
||||
# Блокировка остаётся до завершения PUT/COMMIT; reaper использует SKIP LOCKED.
|
||||
# При отмене S3 adapter дожидается SDK-потока до освобождения блокировки.
|
||||
await storage.put_file(
|
||||
work.original_key, source, size_bytes=work.size_bytes,
|
||||
content_type=work.content_type, sha256=work.sha256,
|
||||
work.original_key,
|
||||
source,
|
||||
size_bytes=work.size_bytes,
|
||||
content_type=work.content_type,
|
||||
sha256=work.sha256,
|
||||
)
|
||||
if after_object is not None:
|
||||
after_object(work.attachment_id, "original")
|
||||
for variant in result.variants:
|
||||
await storage.put_file(
|
||||
work.variant_key(variant.name), Path(directory) / VARIANT_FILENAMES[variant.name],
|
||||
size_bytes=variant.size_bytes, content_type=variant.content_type, sha256=variant.sha256,
|
||||
work.variant_key(variant.name),
|
||||
Path(directory) / VARIANT_FILENAMES[variant.name],
|
||||
size_bytes=variant.size_bytes,
|
||||
content_type=variant.content_type,
|
||||
sha256=variant.sha256,
|
||||
)
|
||||
if after_object is not None:
|
||||
after_object(work.attachment_id, variant.name)
|
||||
jobs.complete_job(job, attachment, work, [variant.model_dump() for variant in result.variants], await jobs.database_time(session))
|
||||
jobs.complete_job(
|
||||
job,
|
||||
attachment,
|
||||
work,
|
||||
[variant.model_dump() for variant in result.variants],
|
||||
await jobs.database_time(session),
|
||||
)
|
||||
await session.commit()
|
||||
return True
|
||||
|
||||
|
||||
async def process_attachment_job(
|
||||
session: AsyncSession, storage: MinioStorage, message: JobMessage, settings: JobSettings,
|
||||
*, after_object: Callable[[UUID, str], None] | None = None,
|
||||
session: AsyncSession,
|
||||
storage: MinioStorage,
|
||||
message: JobMessage,
|
||||
settings: JobSettings,
|
||||
*,
|
||||
after_object: Callable[[UUID, str], None] | None = None,
|
||||
before_processing: Callable[[UUID], None] | None = None,
|
||||
) -> bool:
|
||||
claim = await claim_job(session, message, settings)
|
||||
@@ -160,7 +211,13 @@ async def process_attachment_job(
|
||||
if before_processing is not None:
|
||||
before_processing(work.attachment_id)
|
||||
acknowledge = await build_result(session, storage, work, after_object)
|
||||
except (ProcessingError, MinioException, StorageHTTPError, OSError, TimeoutError) as error:
|
||||
except (
|
||||
ProcessingError,
|
||||
MinioException,
|
||||
StorageHTTPError,
|
||||
OSError,
|
||||
TimeoutError,
|
||||
) as error:
|
||||
code, permanent = classify_failure(error)
|
||||
await save_failure(session, work, settings, code, permanent=permanent)
|
||||
acknowledge = True
|
||||
@@ -176,8 +233,12 @@ async def recover_expired_jobs(session: AsyncSession, settings: JobSettings) ->
|
||||
job.attempt_limit = settings.job_max_attempts
|
||||
exhausted = job.attempt >= (job.attempt_limit or settings.job_max_attempts)
|
||||
jobs.record_failure(
|
||||
job, attachment, now, "retry_exhausted" if exhausted else "worker_timeout",
|
||||
terminal=exhausted, retry_seconds=retry_delay(settings, job.attempt - job.cycle_start_attempt),
|
||||
job,
|
||||
attachment,
|
||||
now,
|
||||
"retry_exhausted" if exhausted else "worker_timeout",
|
||||
terminal=exhausted,
|
||||
retry_seconds=retry_delay(settings, job.attempt - job.cycle_start_attempt),
|
||||
)
|
||||
job.last_error_code = "worker_timeout"
|
||||
job.last_error_permanent = False
|
||||
@@ -185,8 +246,14 @@ async def recover_expired_jobs(session: AsyncSession, settings: JobSettings) ->
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def cleanup_staging(session: AsyncSession, storage: MinioStorage, settings: JobSettings, *, apply: bool) -> int:
|
||||
rows = await jobs.terminal_staging(session, settings.staging_retention_seconds, settings.failed_staging_retention_seconds)
|
||||
async def cleanup_staging(
|
||||
session: AsyncSession, storage: MinioStorage, settings: JobSettings, *, apply: bool
|
||||
) -> int:
|
||||
rows = await jobs.terminal_staging(
|
||||
session,
|
||||
settings.staging_retention_seconds,
|
||||
settings.failed_staging_retention_seconds,
|
||||
)
|
||||
if apply:
|
||||
for job, attachment in rows:
|
||||
if job.staging_key != attachment.object_key:
|
||||
|
||||
@@ -276,12 +276,20 @@ async def download_attachment(
|
||||
key = record.object_key
|
||||
info = DownloadInfo(result.filename, result.content_type, result.size_bytes)
|
||||
else:
|
||||
selected = next((item for item in result.variants if item.name == variant), None)
|
||||
keys = {"thumbnail": record.thumbnail_key, "crop": record.crop_key, "optimized": record.optimized_key}
|
||||
selected = next(
|
||||
(item for item in result.variants if item.name == variant), None
|
||||
)
|
||||
keys = {
|
||||
"thumbnail": record.thumbnail_key,
|
||||
"crop": record.crop_key,
|
||||
"optimized": record.optimized_key,
|
||||
}
|
||||
key = keys.get(variant)
|
||||
if selected is None or key is None:
|
||||
raise not_found()
|
||||
info = DownloadInfo(VARIANT_FILENAMES[variant], selected.content_type, selected.size_bytes)
|
||||
info = DownloadInfo(
|
||||
VARIANT_FILENAMES[variant], selected.content_type, selected.size_bytes
|
||||
)
|
||||
await session.rollback()
|
||||
stored = await storage.stat_object(key)
|
||||
if stored.size_bytes != info.size_bytes or stored.content_type != info.content_type:
|
||||
|
||||
@@ -14,12 +14,15 @@ from app.storage.s3 import MinioStorage
|
||||
|
||||
|
||||
def liveness() -> Health:
|
||||
return Health(status='ok')
|
||||
return Health(status="ok")
|
||||
|
||||
|
||||
async def readiness(
|
||||
engine: AsyncEngine, redis: Redis, storage: MinioStorage | None,
|
||||
lifecycle: Lifecycle, timeout_seconds: float,
|
||||
engine: AsyncEngine,
|
||||
redis: Redis,
|
||||
storage: MinioStorage | None,
|
||||
lifecycle: Lifecycle,
|
||||
timeout_seconds: float,
|
||||
) -> Health:
|
||||
if lifecycle.draining:
|
||||
raise unavailable()
|
||||
@@ -30,4 +33,4 @@ async def readiness(
|
||||
dependencies = await asyncio.gather(*checks, return_exceptions=True)
|
||||
if not all(result is True for result in dependencies):
|
||||
raise unavailable()
|
||||
return Health(status='ok')
|
||||
return Health(status="ok")
|
||||
|
||||
@@ -29,7 +29,7 @@ def validate_idempotency_key(key: str | None) -> str:
|
||||
def request_fingerprint(new_message: CreateMessage) -> str:
|
||||
"""Хеширует нормализованное содержимое запроса."""
|
||||
body = new_message.model_dump(mode="json")
|
||||
# Сохраняет отпечатки текстовых запросов lab3 и равенство absent / [].
|
||||
# Сохраняет прежние отпечатки текстовых запросов и равенство absent / [].
|
||||
if not body["attachment_ids"]:
|
||||
body.pop("attachment_ids")
|
||||
canonical = json.dumps(body, sort_keys=True, ensure_ascii=False)
|
||||
@@ -57,16 +57,22 @@ async def send_message_idempotent(
|
||||
raise conflict("Idempotency-Key уже использован для другого сообщения")
|
||||
message = await message_storage.get_message(session, previous.message_id)
|
||||
else:
|
||||
await validate_message_attachments(session, sender, chat_id, new_message.attachment_ids)
|
||||
await validate_message_attachments(
|
||||
session, sender, chat_id, new_message.attachment_ids
|
||||
)
|
||||
if not await message_storage.reserve_message_slot(session, max_messages):
|
||||
raise unavailable("Достигнут лимит количества сообщений")
|
||||
message = await message_storage.create_message(
|
||||
session, chat_id=chat_id, sender_id=sender.id, text=new_message.text
|
||||
)
|
||||
await attachment_storage.bind_attachments(session, message.id, new_message.attachment_ids)
|
||||
await attachment_storage.bind_attachments(
|
||||
session, message.id, new_message.attachment_ids
|
||||
)
|
||||
await key_storage.save_result(session, scope, fingerprint, message.id)
|
||||
|
||||
links = await attachment_storage.message_attachment_ids(session, [message.id])
|
||||
result = Message.model_validate(message).model_copy(update={"attachment_ids": links[message.id]})
|
||||
result = Message.model_validate(message).model_copy(
|
||||
update={"attachment_ids": links[message.id]}
|
||||
)
|
||||
await session.commit()
|
||||
return result
|
||||
|
||||
@@ -15,18 +15,27 @@ def fitted_size(size: tuple[int, int], maximum: int) -> tuple[int, int]:
|
||||
longest = max(size)
|
||||
result = size
|
||||
if longest > maximum:
|
||||
result = (max(1, size[0] * maximum // longest), max(1, size[1] * maximum // longest))
|
||||
result = (
|
||||
max(1, size[0] * maximum // longest),
|
||||
max(1, size[1] * maximum // longest),
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def describe_variant(name: str, content_type: str, path: Path, size: tuple[int, int]) -> Variant:
|
||||
def describe_variant(
|
||||
name: str, content_type: str, path: Path, size: tuple[int, int]
|
||||
) -> Variant:
|
||||
checksum = hashlib.sha256()
|
||||
with path.open("rb") as source:
|
||||
for chunk in iter(lambda: source.read(65536), b""):
|
||||
checksum.update(chunk)
|
||||
return Variant(
|
||||
name=name, content_type=content_type, size_bytes=path.stat().st_size,
|
||||
width=size[0], height=size[1], sha256=checksum.hexdigest(),
|
||||
name=name,
|
||||
content_type=content_type,
|
||||
size_bytes=path.stat().st_size,
|
||||
width=size[0],
|
||||
height=size[1],
|
||||
sha256=checksum.hexdigest(),
|
||||
)
|
||||
|
||||
|
||||
@@ -47,32 +56,49 @@ def create_thumbnail(image: Image.Image, destination: Path, quality: int) -> Var
|
||||
|
||||
def create_crop(image: Image.Image, destination: Path, quality: int) -> Variant:
|
||||
"""Центрированный JPEG 128×128; маленький исходник допускает увеличение."""
|
||||
with ImageOps.fit(image, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5)) as crop:
|
||||
with ImageOps.fit(
|
||||
image, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5)
|
||||
) as crop:
|
||||
save_jpeg(crop, destination, quality)
|
||||
return describe_variant("crop", "image/jpeg", destination, (128, 128))
|
||||
|
||||
|
||||
def create_optimized(image: Image.Image, destination: Path, settings: ImageSettings) -> Variant:
|
||||
def create_optimized(
|
||||
image: Image.Image, destination: Path, settings: ImageSettings
|
||||
) -> Variant:
|
||||
"""WebP ≤1280×1280 без увеличения; alpha сохраняется, метаданные удаляются."""
|
||||
size = fitted_size(image.size, 1280)
|
||||
with image.resize(size, Image.Resampling.LANCZOS) as resized:
|
||||
with Image.new("RGBA", size) as clean:
|
||||
clean.paste(resized)
|
||||
clean.save(
|
||||
destination, format="WEBP", lossless=False,
|
||||
quality=settings.webp_quality, method=settings.webp_method,
|
||||
exif=b"", icc_profile=b"", xmp=b"",
|
||||
destination,
|
||||
format="WEBP",
|
||||
lossless=False,
|
||||
quality=settings.webp_quality,
|
||||
method=settings.webp_method,
|
||||
exif=b"",
|
||||
icc_profile=b"",
|
||||
xmp=b"",
|
||||
)
|
||||
return describe_variant("optimized", "image/webp", destination, size)
|
||||
|
||||
|
||||
def create_variants(source: Path, directory: Path, content_type: str, max_pixels: int, settings: ImageSettings) -> PipelineResult:
|
||||
def create_variants(
|
||||
source: Path,
|
||||
directory: Path,
|
||||
content_type: str,
|
||||
max_pixels: int,
|
||||
settings: ImageSettings,
|
||||
) -> PipelineResult:
|
||||
decode_image(source, content_type, max_pixels)
|
||||
with Image.open(source, formats=["PNG", "JPEG"]) as image:
|
||||
ImageOps.exif_transpose(image, in_place=True)
|
||||
with image.convert("RGBA") as pixels:
|
||||
variants = [
|
||||
create_thumbnail(pixels, directory / "thumbnail.jpg", settings.jpeg_quality),
|
||||
create_thumbnail(
|
||||
pixels, directory / "thumbnail.jpg", settings.jpeg_quality
|
||||
),
|
||||
create_crop(pixels, directory / "crop.jpg", settings.jpeg_quality),
|
||||
create_optimized(pixels, directory / "optimized.webp", settings),
|
||||
]
|
||||
|
||||
+97
-29
@@ -17,15 +17,28 @@ REPLAY_REASONS = ("dependency_restored", "configuration_fixed", "manual_review")
|
||||
|
||||
|
||||
def snapshot(job, attachment):
|
||||
return dict(job_id=str(job.id), attachment_id=str(attachment.id), status=attachment.status,
|
||||
attempt=job.attempt, attempt_limit=job.attempt_limit, cycle_start_attempt=job.cycle_start_attempt,
|
||||
error_code=attachment.error_code, last_error_code=job.last_error_code,
|
||||
last_error_permanent=job.last_error_permanent, staging_retained=job.staging_key is not None,
|
||||
next_attempt_at=job.next_attempt_at, lease_until=job.lease_until, finished_at=job.finished_at)
|
||||
return dict(
|
||||
job_id=str(job.id),
|
||||
attachment_id=str(attachment.id),
|
||||
status=attachment.status,
|
||||
attempt=job.attempt,
|
||||
attempt_limit=job.attempt_limit,
|
||||
cycle_start_attempt=job.cycle_start_attempt,
|
||||
error_code=attachment.error_code,
|
||||
last_error_code=job.last_error_code,
|
||||
last_error_permanent=job.last_error_permanent,
|
||||
staging_retained=job.staging_key is not None,
|
||||
next_attempt_at=job.next_attempt_at,
|
||||
lease_until=job.lease_until,
|
||||
finished_at=job.finished_at,
|
||||
)
|
||||
|
||||
|
||||
async def list_failed(session, limit):
|
||||
return [snapshot(job, attachment) for job, attachment in await job_admin.failed_jobs(session, limit)]
|
||||
return [
|
||||
snapshot(job, attachment)
|
||||
for job, attachment in await job_admin.failed_jobs(session, limit)
|
||||
]
|
||||
|
||||
|
||||
async def show_job(session, job_id):
|
||||
@@ -38,37 +51,59 @@ async def show_job(session, job_id):
|
||||
|
||||
|
||||
async def history(session, job_id):
|
||||
return [dict(request_id=str(row.id), actor=row.actor, reason=row.reason,
|
||||
previous_attempt=row.previous_attempt, attempt_limit=row.attempt_limit,
|
||||
previous_error_code=row.previous_error_code, created_at=row.created_at)
|
||||
for row in await job_admin.replay_history(session, job_id)]
|
||||
return [
|
||||
dict(
|
||||
request_id=str(row.id),
|
||||
actor=row.actor,
|
||||
reason=row.reason,
|
||||
previous_attempt=row.previous_attempt,
|
||||
attempt_limit=row.attempt_limit,
|
||||
previous_error_code=row.previous_error_code,
|
||||
created_at=row.created_at,
|
||||
)
|
||||
for row in await job_admin.replay_history(session, job_id)
|
||||
]
|
||||
|
||||
|
||||
def same_request(record, job_id, actor, reason):
|
||||
if record.job_id != job_id or record.actor != actor or record.reason != reason:
|
||||
raise JobOperationError("request_conflict")
|
||||
return {"request_id": str(record.id), "job_id": str(job_id), "already_applied": True}
|
||||
return {
|
||||
"request_id": str(record.id),
|
||||
"job_id": str(job_id),
|
||||
"already_applied": True,
|
||||
}
|
||||
|
||||
|
||||
async def replay_failed_job(session, storage, settings, job_id, *, request_id, actor, reason):
|
||||
if re.fullmatch(r"[A-Za-z0-9._-]{1,64}", actor) is None or reason not in REPLAY_REASONS:
|
||||
def validate_replay_request(actor: str, reason: str) -> None:
|
||||
"""Проверить данные оператора для записи аудита."""
|
||||
if (
|
||||
re.fullmatch(r"[A-Za-z0-9._-]{1,64}", actor) is None
|
||||
or reason not in REPLAY_REASONS
|
||||
):
|
||||
raise JobOperationError("invalid_audit_fields")
|
||||
row = await jobs.lock_job(session, job_id)
|
||||
if row is None:
|
||||
raise JobOperationError("unknown_job")
|
||||
record = await job_admin.replay_record(session, request_id)
|
||||
if record is not None:
|
||||
result = same_request(record, job_id, actor, reason)
|
||||
await session.rollback()
|
||||
return result
|
||||
job, attachment = row
|
||||
|
||||
|
||||
def validate_replay_job(job, attachment) -> None:
|
||||
"""Разрешить новый replay только для failed с сохранённым исходником."""
|
||||
if attachment.status != "failed":
|
||||
raise JobOperationError("job_not_failed")
|
||||
if job.staging_key is None:
|
||||
raise JobOperationError("source_expired")
|
||||
# Та же блокировка защищает исходник от cleanup до окончания проверки и COMMIT.
|
||||
work = JobWork(job.id, attachment.id, uuid4(), job.pipeline_version, job.staging_key,
|
||||
attachment.content_type, attachment.size_bytes, attachment.sha256)
|
||||
|
||||
|
||||
async def verify_replay_source(storage, settings, job, attachment) -> None:
|
||||
"""Проверить размер и SHA-256 исходника в S3 под блокировкой job."""
|
||||
work = JobWork(
|
||||
job.id,
|
||||
attachment.id,
|
||||
uuid4(),
|
||||
job.pipeline_version,
|
||||
job.staging_key,
|
||||
attachment.content_type,
|
||||
attachment.size_bytes,
|
||||
attachment.sha256,
|
||||
)
|
||||
try:
|
||||
async with asyncio.timeout(settings.job_timeout_seconds):
|
||||
with TemporaryDirectory(prefix="replay-source-") as directory:
|
||||
@@ -79,15 +114,48 @@ async def replay_failed_job(session, storage, settings, job_id, *, request_id, a
|
||||
if error.code in {"NoSuchKey", "NoSuchObject"}:
|
||||
raise JobOperationError("source_missing") from None
|
||||
raise
|
||||
|
||||
|
||||
async def replay_failed_job(
|
||||
session, storage, settings, job_id, *, request_id, actor, reason
|
||||
):
|
||||
"""Организовать replay; блокировка, rollback и commit остаются здесь."""
|
||||
validate_replay_request(actor, reason)
|
||||
row = await jobs.lock_job(session, job_id)
|
||||
if row is None:
|
||||
raise JobOperationError("unknown_job")
|
||||
record = await job_admin.replay_record(session, request_id)
|
||||
if record is not None:
|
||||
result = same_request(record, job_id, actor, reason)
|
||||
await session.rollback()
|
||||
return result
|
||||
job, attachment = row
|
||||
validate_replay_job(job, attachment)
|
||||
# Блокировка сохраняется во время проверки S3, аудита и изменения job.
|
||||
await verify_replay_source(storage, settings, job, attachment)
|
||||
limit = job.attempt + settings.job_max_attempts
|
||||
inserted = await job_admin.insert_replay(
|
||||
session, id=request_id, job_id=job_id, actor=actor, reason=reason,
|
||||
previous_attempt=job.attempt, attempt_limit=limit, previous_error_code=job.last_error_code,
|
||||
session,
|
||||
id=request_id,
|
||||
job_id=job_id,
|
||||
actor=actor,
|
||||
reason=reason,
|
||||
previous_attempt=job.attempt,
|
||||
attempt_limit=limit,
|
||||
previous_error_code=job.last_error_code,
|
||||
)
|
||||
if not inserted:
|
||||
result = same_request(await job_admin.replay_record(session, request_id), job_id, actor, reason)
|
||||
result = same_request(
|
||||
await job_admin.replay_record(session, request_id), job_id, actor, reason
|
||||
)
|
||||
await session.rollback()
|
||||
return result
|
||||
job_admin.reset_failed(job, attachment, await jobs.database_time(session), limit)
|
||||
await session.commit()
|
||||
return {"request_id": str(request_id), "job_id": str(job_id), "already_applied": False, "status": "queued", "attempt_limit": limit}
|
||||
return {
|
||||
"request_id": str(request_id),
|
||||
"job_id": str(job_id),
|
||||
"already_applied": False,
|
||||
"status": "queued",
|
||||
"attempt_limit": limit,
|
||||
}
|
||||
|
||||
+16
-5
@@ -14,7 +14,9 @@ from app.storage.jobs import JobWork
|
||||
from app.storage.s3 import MinioStorage
|
||||
|
||||
|
||||
async def fetch_original(storage: MinioStorage, work: JobWork, destination: Path) -> None:
|
||||
async def fetch_original(
|
||||
storage: MinioStorage, work: JobWork, destination: Path
|
||||
) -> None:
|
||||
if work.size_bytes > storage.settings.max_upload_bytes:
|
||||
raise ProcessingError("image_limits")
|
||||
checksum = hashlib.sha256()
|
||||
@@ -34,12 +36,21 @@ async def fetch_original(storage: MinioStorage, work: JobWork, destination: Path
|
||||
raise ProcessingError("source_mismatch")
|
||||
|
||||
|
||||
async def render_variants(storage: MinioStorage, work: JobWork, source: Path, directory: Path) -> PipelineResult:
|
||||
async def render_variants(
|
||||
storage: MinioStorage, work: JobWork, source: Path, directory: Path
|
||||
) -> PipelineResult:
|
||||
metadata = directory / "variants.json"
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
sys.executable, "-m", "app.core.thumbnail_worker", str(source), str(directory),
|
||||
str(metadata), work.content_type, str(storage.settings.max_image_pixels),
|
||||
stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL,
|
||||
sys.executable,
|
||||
"-m",
|
||||
"app.core.thumbnail_worker",
|
||||
str(source),
|
||||
str(directory),
|
||||
str(metadata),
|
||||
work.content_type,
|
||||
str(storage.settings.max_image_pixels),
|
||||
stdout=asyncio.subprocess.DEVNULL,
|
||||
stderr=asyncio.subprocess.DEVNULL,
|
||||
)
|
||||
try:
|
||||
code = await process.wait()
|
||||
|
||||
+23
-4
@@ -10,7 +10,10 @@ from app.errors.exceptions import ProcessingError
|
||||
|
||||
|
||||
def retry_delay(settings: JobSettings, cycle_attempt: int) -> float:
|
||||
ceiling = min(settings.job_retry_max_seconds, settings.job_retry_seconds * 2 ** min(30, max(0, cycle_attempt - 1)))
|
||||
ceiling = min(
|
||||
settings.job_retry_max_seconds,
|
||||
settings.job_retry_seconds * 2 ** min(30, max(0, cycle_attempt - 1)),
|
||||
)
|
||||
return random.uniform(ceiling / 2, ceiling)
|
||||
|
||||
|
||||
@@ -20,13 +23,29 @@ def classify_failure(error: Exception) -> tuple[str, bool]:
|
||||
if isinstance(error, S3Error):
|
||||
if error.code in {"NoSuchKey", "NoSuchObject"}:
|
||||
return "source_missing", True
|
||||
if error.code in {"AccessDenied", "InvalidAccessKeyId", "SignatureDoesNotMatch", "NoSuchBucket"}:
|
||||
if error.code in {
|
||||
"AccessDenied",
|
||||
"InvalidAccessKeyId",
|
||||
"SignatureDoesNotMatch",
|
||||
"NoSuchBucket",
|
||||
}:
|
||||
return "storage_configuration", True
|
||||
if error.code in {"InternalError", "SlowDown", "ServiceUnavailable", "RequestTimeout", "Throttling"}:
|
||||
if error.code in {
|
||||
"InternalError",
|
||||
"SlowDown",
|
||||
"ServiceUnavailable",
|
||||
"RequestTimeout",
|
||||
"Throttling",
|
||||
}:
|
||||
return "storage_unavailable", False
|
||||
return "storage_rejected", True
|
||||
if isinstance(error, TimeoutError):
|
||||
return "processing_timeout", False
|
||||
if isinstance(error, OSError) and error.errno in {errno.EACCES, errno.EPERM, errno.EROFS, errno.ENOENT}:
|
||||
if isinstance(error, OSError) and error.errno in {
|
||||
errno.EACCES,
|
||||
errno.EPERM,
|
||||
errno.EROFS,
|
||||
errno.ENOENT,
|
||||
}:
|
||||
return "processing_configuration", True
|
||||
return "processing_unavailable", False
|
||||
|
||||
@@ -32,10 +32,15 @@ async def list_messages(
|
||||
|
||||
rows = await messages_storage.list_messages(session, chat_id, after, limit + 1)
|
||||
page_rows, has_next = split_page(rows, limit)
|
||||
links = await attachments_storage.message_attachment_ids(session, [message.id for message in page_rows])
|
||||
items = [Message.model_validate(message).model_copy(
|
||||
update={"attachment_ids": links[message.id]},
|
||||
) for message in page_rows]
|
||||
links = await attachments_storage.message_attachment_ids(
|
||||
session, [message.id for message in page_rows]
|
||||
)
|
||||
items = [
|
||||
Message.model_validate(message).model_copy(
|
||||
update={"attachment_ids": links[message.id]},
|
||||
)
|
||||
for message in page_rows
|
||||
]
|
||||
page = MessagePage(
|
||||
items=items,
|
||||
next_cursor=build_next_cursor(KIND_MESSAGES, chat_id, items, has_next),
|
||||
|
||||
@@ -12,41 +12,63 @@ from app.domain import attachments
|
||||
from app.endpoints.dependencies import CurrentUser, DbSession, S3Storage, UploadCapacity
|
||||
from app.schemas.attachment import Attachment
|
||||
|
||||
router = APIRouter(prefix='/api/v1', tags=['attachments'])
|
||||
router = APIRouter(prefix="/api/v1", tags=["attachments"])
|
||||
|
||||
|
||||
@router.post('/chats/{chat_id}/attachments', status_code=202)
|
||||
@router.post("/chats/{chat_id}/attachments", status_code=202)
|
||||
async def upload(
|
||||
request: Request, chat_id: UUID, user: CurrentUser, session: DbSession,
|
||||
storage: S3Storage, capacity: UploadCapacity,
|
||||
request: Request,
|
||||
chat_id: UUID,
|
||||
user: CurrentUser,
|
||||
session: DbSession,
|
||||
storage: S3Storage,
|
||||
capacity: UploadCapacity,
|
||||
filename: Annotated[str, Query(min_length=1, max_length=255)],
|
||||
) -> Attachment:
|
||||
return await attachments.receive_attachment(
|
||||
session, storage, user, chat_id, capacity=capacity, filename=filename,
|
||||
content_type=request.headers.get('content-type', '').lower(),
|
||||
declared_length=request.headers.get('content-length'), chunks=request.stream(),
|
||||
session,
|
||||
storage,
|
||||
user,
|
||||
chat_id,
|
||||
capacity=capacity,
|
||||
filename=filename,
|
||||
content_type=request.headers.get("content-type", "").lower(),
|
||||
declared_length=request.headers.get("content-length"),
|
||||
chunks=request.stream(),
|
||||
)
|
||||
|
||||
|
||||
@router.get('/attachments/{attachment_id}')
|
||||
async def metadata(attachment_id: UUID, user: CurrentUser, session: DbSession) -> Attachment:
|
||||
@router.get("/attachments/{attachment_id}")
|
||||
async def metadata(
|
||||
attachment_id: UUID, user: CurrentUser, session: DbSession
|
||||
) -> Attachment:
|
||||
return await attachments.get_attachment(session, user, attachment_id)
|
||||
|
||||
|
||||
@router.get('/attachments/{attachment_id}/content')
|
||||
@router.get("/attachments/{attachment_id}/content")
|
||||
async def content(
|
||||
attachment_id: UUID, user: CurrentUser, session: DbSession, storage: S3Storage,
|
||||
variant: Annotated[str, Query()] = 'original',
|
||||
attachment_id: UUID,
|
||||
user: CurrentUser,
|
||||
session: DbSession,
|
||||
storage: S3Storage,
|
||||
variant: Annotated[str, Query()] = "original",
|
||||
) -> StreamingResponse:
|
||||
record, stream = await attachments.download_attachment(
|
||||
session, storage, user, attachment_id, variant=variant,
|
||||
session,
|
||||
storage,
|
||||
user,
|
||||
attachment_id,
|
||||
variant=variant,
|
||||
)
|
||||
return StreamingResponse(
|
||||
stream, media_type=record.content_type,
|
||||
stream,
|
||||
media_type=record.content_type,
|
||||
headers={
|
||||
'Content-Length': str(record.size_bytes),
|
||||
'Content-Disposition': "attachment; filename*=UTF-8''" + quote(record.filename, safe=''),
|
||||
'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'private, no-store',
|
||||
"Content-Length": str(record.size_bytes),
|
||||
"Content-Disposition": "attachment; filename*=UTF-8''"
|
||||
+ quote(record.filename, safe=""),
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Cache-Control": "private, no-store",
|
||||
},
|
||||
background=BackgroundTask(stream.aclose),
|
||||
)
|
||||
|
||||
@@ -3,18 +3,21 @@ from fastapi import APIRouter, Request
|
||||
from app.domain import health
|
||||
from app.schemas.base import Health
|
||||
|
||||
router = APIRouter(prefix='/health', tags=['health'])
|
||||
router = APIRouter(prefix="/health", tags=["health"])
|
||||
|
||||
|
||||
@router.get('/live')
|
||||
@router.get("/live")
|
||||
async def liveness() -> Health:
|
||||
return health.liveness()
|
||||
|
||||
|
||||
@router.get('/ready')
|
||||
@router.get("/ready")
|
||||
async def readiness(request: Request) -> Health:
|
||||
state = request.app.state
|
||||
return await health.readiness(
|
||||
state.engine, state.redis, state.s3, state.lifecycle,
|
||||
state.engine,
|
||||
state.redis,
|
||||
state.s3,
|
||||
state.lifecycle,
|
||||
state.settings.readiness_timeout_seconds,
|
||||
)
|
||||
|
||||
@@ -21,9 +21,13 @@ async def send_new_message(
|
||||
idempotency_key: Annotated[str | None, Header(alias="Idempotency-Key")] = None,
|
||||
) -> Message:
|
||||
return await send_message_idempotent(
|
||||
session, sender, chat_id, new_message,
|
||||
session,
|
||||
sender,
|
||||
chat_id,
|
||||
new_message,
|
||||
validate_idempotency_key(idempotency_key),
|
||||
settings.max_messages, settings.idempotency_ttl_seconds,
|
||||
settings.max_messages,
|
||||
settings.idempotency_ttl_seconds,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -90,14 +90,23 @@ def internal_error() -> ApiError:
|
||||
|
||||
|
||||
IMAGE_WORKER_ERRORS = (
|
||||
ApiError, Image.DecompressionBombError, Image.DecompressionBombWarning,
|
||||
MemoryError, UnidentifiedImageError, OSError, ValueError, SyntaxError,
|
||||
ApiError,
|
||||
Image.DecompressionBombError,
|
||||
Image.DecompressionBombWarning,
|
||||
MemoryError,
|
||||
UnidentifiedImageError,
|
||||
OSError,
|
||||
ValueError,
|
||||
SyntaxError,
|
||||
)
|
||||
|
||||
|
||||
def image_worker_error_code(error: Exception) -> int:
|
||||
code = 2
|
||||
resource_error = isinstance(error, (Image.DecompressionBombError, Image.DecompressionBombWarning, MemoryError))
|
||||
resource_error = isinstance(
|
||||
error,
|
||||
(Image.DecompressionBombError, Image.DecompressionBombWarning, MemoryError),
|
||||
)
|
||||
declared_limit = isinstance(error, ApiError) and error.status_code == 413
|
||||
if resource_error or declared_limit:
|
||||
code = 3
|
||||
|
||||
+17
-4
@@ -18,14 +18,25 @@ from urllib3.exceptions import HTTPError as StorageHTTPError
|
||||
|
||||
from app.core.instance import INSTANCE_ID_HEADER
|
||||
from app.core.request_id import REQUEST_ID_HEADER
|
||||
from app.errors.exceptions import ApiError, internal_error, invalid_request, not_found, unavailable
|
||||
from app.errors.exceptions import (
|
||||
ApiError,
|
||||
internal_error,
|
||||
invalid_request,
|
||||
not_found,
|
||||
unavailable,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TRANSIENT_SQLSTATE_CLASSES = ("08", "40", "53", "57")
|
||||
TRANSIENT_SQLSTATES = frozenset({"55P03"})
|
||||
RECOVERABLE_STORAGE_ERRORS = (
|
||||
ApiError, SQLAlchemyError, MinioException, StorageHTTPError, OSError, TimeoutError,
|
||||
ApiError,
|
||||
SQLAlchemyError,
|
||||
MinioException,
|
||||
StorageHTTPError,
|
||||
OSError,
|
||||
TimeoutError,
|
||||
)
|
||||
|
||||
|
||||
@@ -40,12 +51,14 @@ async def operation_timeout(seconds: float, error: ApiError):
|
||||
|
||||
|
||||
async def client_disconnect_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
return await api_error_handler(request, invalid_request("Загрузка прервана клиентом"))
|
||||
return await api_error_handler(
|
||||
request, invalid_request("Загрузка прервана клиентом")
|
||||
)
|
||||
|
||||
|
||||
def log_recoverable_error(operation: str, error: Exception) -> None:
|
||||
"""Согласованный безопасный лог восстановления без содержимого SDK-ошибки."""
|
||||
logger.warning('%s deferred: %s', operation, type(error).__name__)
|
||||
logger.warning("%s deferred: %s", operation, type(error).__name__)
|
||||
|
||||
|
||||
def _get_request_id(request: Request) -> str:
|
||||
|
||||
+3
-1
@@ -52,7 +52,9 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
application.state.session_factory = create_session_factory(engine)
|
||||
application.state.redis = redis
|
||||
application.state.s3 = s3
|
||||
application.state.upload_capacity = create_request_capacity(settings.s3.max_concurrent_uploads)
|
||||
application.state.upload_capacity = create_request_capacity(
|
||||
settings.s3.max_concurrent_uploads
|
||||
)
|
||||
application.state.request_capacity = create_request_capacity(settings.max_in_flight)
|
||||
application.state.instance_id = resolve_instance_id(settings.instance_id)
|
||||
application.state.lifecycle = Lifecycle()
|
||||
|
||||
+14
-1
@@ -9,4 +9,17 @@ from app.models.idempotency_key import IdempotencyKey
|
||||
from app.models.message import Message
|
||||
from app.models.user import User
|
||||
|
||||
__all__ = ["JobReplay", "AttachmentJob", "Base", "Attachment", "MessageAttachment", "UploadIntent", "Chat", "ChatMember", "Counter", "IdempotencyKey", "Message", "User"]
|
||||
__all__ = [
|
||||
"JobReplay",
|
||||
"AttachmentJob",
|
||||
"Base",
|
||||
"Attachment",
|
||||
"MessageAttachment",
|
||||
"UploadIntent",
|
||||
"Chat",
|
||||
"ChatMember",
|
||||
"Counter",
|
||||
"IdempotencyKey",
|
||||
"Message",
|
||||
"User",
|
||||
]
|
||||
|
||||
@@ -18,8 +18,13 @@ class Attachment(Base):
|
||||
"content_type IN ('image/png', 'image/jpeg')", name="content_type"
|
||||
),
|
||||
CheckConstraint("sha256 ~ '^[a-f0-9]{64}$'", name="sha256"),
|
||||
CheckConstraint("status IN ('queued', 'processing', 'ready', 'failed')", name="status"),
|
||||
CheckConstraint("(status = 'failed' AND error_code IS NOT NULL) OR (status <> 'failed' AND error_code IS NULL)", name="error_code"),
|
||||
CheckConstraint(
|
||||
"status IN ('queued', 'processing', 'ready', 'failed')", name="status"
|
||||
),
|
||||
CheckConstraint(
|
||||
"(status = 'failed' AND error_code IS NOT NULL) OR (status <> 'failed' AND error_code IS NULL)",
|
||||
name="error_code",
|
||||
),
|
||||
Index("ix_attachments_chat_id", "chat_id"),
|
||||
)
|
||||
|
||||
@@ -36,7 +41,9 @@ class Attachment(Base):
|
||||
thumbnail_key: Mapped[str | None] = mapped_column(String(128))
|
||||
crop_key: Mapped[str | None] = mapped_column(String(128))
|
||||
optimized_key: Mapped[str | None] = mapped_column(String(128))
|
||||
variants: Mapped[list[dict]] = mapped_column(JSONB, default=list, server_default=text("'[]'::jsonb"))
|
||||
variants: Mapped[list[dict]] = mapped_column(
|
||||
JSONB, default=list, server_default=text("'[]'::jsonb")
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(server_default=func.clock_timestamp())
|
||||
updated_at: Mapped[datetime] = mapped_column(server_default=func.clock_timestamp())
|
||||
|
||||
|
||||
+5
-2
@@ -20,7 +20,8 @@ class AttachmentJob(Base):
|
||||
|
||||
id: Mapped[UUID] = mapped_column(primary_key=True, default=uuid4)
|
||||
attachment_id: Mapped[UUID] = mapped_column(
|
||||
ForeignKey("attachments.id"), unique=True,
|
||||
ForeignKey("attachments.id"),
|
||||
unique=True,
|
||||
)
|
||||
staging_key: Mapped[str | None] = mapped_column(String(128))
|
||||
pipeline_version: Mapped[int] = mapped_column(server_default="1")
|
||||
@@ -29,7 +30,9 @@ class AttachmentJob(Base):
|
||||
attempt_limit: Mapped[int | None]
|
||||
last_error_permanent: Mapped[bool | None]
|
||||
published_attempt: Mapped[int] = mapped_column(server_default="0")
|
||||
next_attempt_at: Mapped[datetime] = mapped_column(server_default=func.clock_timestamp())
|
||||
next_attempt_at: Mapped[datetime] = mapped_column(
|
||||
server_default=func.clock_timestamp()
|
||||
)
|
||||
lease_token: Mapped[UUID | None]
|
||||
lease_until: Mapped[datetime | None]
|
||||
last_error_code: Mapped[str | None] = mapped_column(String(64))
|
||||
|
||||
@@ -35,7 +35,9 @@ class Attachment(Base):
|
||||
|
||||
|
||||
VARIANT_FILENAMES = {
|
||||
"thumbnail": "thumbnail.jpg", "crop": "crop.jpg", "optimized": "optimized.webp",
|
||||
"thumbnail": "thumbnail.jpg",
|
||||
"crop": "crop.jpg",
|
||||
"optimized": "optimized.webp",
|
||||
}
|
||||
|
||||
|
||||
|
||||
+3
-1
@@ -16,5 +16,7 @@ class JobMessage(BaseModel):
|
||||
pipeline_version: int = Field(default=1, ge=1)
|
||||
attempt: int = Field(ge=1)
|
||||
created_at: AwareDatetime
|
||||
traceparent: str | None = Field(default=None, pattern=r"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$")
|
||||
traceparent: str | None = Field(
|
||||
default=None, pattern=r"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$"
|
||||
)
|
||||
tracestate: str | None = Field(default=None, max_length=512)
|
||||
|
||||
+23
-7
@@ -28,26 +28,42 @@ class JobBroker:
|
||||
logging.getLogger("aiormq").setLevel(logging.CRITICAL)
|
||||
|
||||
async def ensure_ready(self) -> None:
|
||||
if self.connection is None or self.connection.is_closed or self.channel is None or self.channel.is_closed:
|
||||
if (
|
||||
self.connection is None
|
||||
or self.connection.is_closed
|
||||
or self.channel is None
|
||||
or self.channel.is_closed
|
||||
):
|
||||
await self.aclose()
|
||||
self.connection = await aio_pika.connect(
|
||||
host=self.settings.broker_host, port=self.settings.broker_port,
|
||||
host=self.settings.broker_host,
|
||||
port=self.settings.broker_port,
|
||||
login=self.settings.broker_user,
|
||||
password=self.settings.broker_password_file.read_text().strip(),
|
||||
virtualhost=self.settings.broker_vhost, timeout=5, heartbeat=30,
|
||||
virtualhost=self.settings.broker_vhost,
|
||||
timeout=5,
|
||||
heartbeat=30,
|
||||
)
|
||||
self.channel = await self.connection.channel(
|
||||
publisher_confirms=True, on_return_raises=True
|
||||
)
|
||||
self.channel = await self.connection.channel(publisher_confirms=True, on_return_raises=True)
|
||||
await self.channel.set_qos(prefetch_count=1)
|
||||
self.queue = await self.channel.declare_queue(self.settings.broker_queue, durable=True)
|
||||
self.queue = await self.channel.declare_queue(
|
||||
self.settings.broker_queue, durable=True
|
||||
)
|
||||
|
||||
async def publish_job(self, message: JobMessage) -> None:
|
||||
await self.ensure_ready()
|
||||
await self.channel.default_exchange.publish(
|
||||
aio_pika.Message(
|
||||
body=message.model_dump_json(exclude_none=True).encode(),
|
||||
content_type="application/json", delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
content_type="application/json",
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
message_id=f"{message.job_id}:{message.attempt}",
|
||||
), routing_key=self.settings.broker_queue, mandatory=True, timeout=10,
|
||||
),
|
||||
routing_key=self.settings.broker_queue,
|
||||
mandatory=True,
|
||||
timeout=10,
|
||||
)
|
||||
|
||||
async def receive(self, consumer: str) -> Delivery:
|
||||
|
||||
@@ -7,7 +7,7 @@ from sqlalchemy.ext.asyncio import AsyncEngine
|
||||
|
||||
async def check_database(engine: AsyncEngine) -> bool:
|
||||
async with engine.connect() as connection:
|
||||
await connection.execute(text('SELECT 1'))
|
||||
await connection.execute(text("SELECT 1"))
|
||||
return True
|
||||
|
||||
|
||||
|
||||
@@ -33,7 +33,8 @@ async def get_active_key(
|
||||
IdempotencyKey.method,
|
||||
IdempotencyKey.path,
|
||||
IdempotencyKey.key,
|
||||
) == tuple_(*scope),
|
||||
)
|
||||
== tuple_(*scope),
|
||||
IdempotencyKey.created_at
|
||||
> func.clock_timestamp() - timedelta(seconds=ttl_seconds),
|
||||
)
|
||||
@@ -45,14 +46,20 @@ async def save_result(
|
||||
) -> None:
|
||||
"""Сохраняет новый результат или заменяет истёкший."""
|
||||
stmt = insert(IdempotencyKey).values(
|
||||
user_id=scope[0], method=scope[1], path=scope[2], key=scope[3],
|
||||
request_hash=request_hash, message_id=message_id,
|
||||
user_id=scope[0],
|
||||
method=scope[1],
|
||||
path=scope[2],
|
||||
key=scope[3],
|
||||
request_hash=request_hash,
|
||||
message_id=message_id,
|
||||
)
|
||||
await session.execute(
|
||||
stmt.on_conflict_do_update(
|
||||
index_elements=[
|
||||
IdempotencyKey.user_id, IdempotencyKey.method,
|
||||
IdempotencyKey.path, IdempotencyKey.key,
|
||||
IdempotencyKey.user_id,
|
||||
IdempotencyKey.method,
|
||||
IdempotencyKey.path,
|
||||
IdempotencyKey.key,
|
||||
],
|
||||
set_={
|
||||
"request_hash": request_hash,
|
||||
|
||||
@@ -13,7 +13,8 @@ async def failed_jobs(session, limit: int):
|
||||
select(AttachmentJob, Attachment)
|
||||
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||
.where(Attachment.status == "failed")
|
||||
.order_by(AttachmentJob.finished_at.desc(), AttachmentJob.id).limit(limit)
|
||||
.order_by(AttachmentJob.finished_at.desc(), AttachmentJob.id)
|
||||
.limit(limit)
|
||||
)
|
||||
return result.all()
|
||||
|
||||
@@ -23,12 +24,24 @@ async def replay_record(session, request_id):
|
||||
|
||||
|
||||
async def insert_replay(session, **values) -> bool:
|
||||
result = await session.scalar(insert(JobReplay).values(**values).on_conflict_do_nothing(index_elements=[JobReplay.id]).returning(JobReplay.id))
|
||||
result = await session.scalar(
|
||||
insert(JobReplay)
|
||||
.values(**values)
|
||||
.on_conflict_do_nothing(index_elements=[JobReplay.id])
|
||||
.returning(JobReplay.id)
|
||||
)
|
||||
return result is not None
|
||||
|
||||
|
||||
async def replay_history(session, job_id):
|
||||
return (await session.scalars(select(JobReplay).where(JobReplay.job_id == job_id).order_by(JobReplay.created_at).limit(100))).all()
|
||||
return (
|
||||
await session.scalars(
|
||||
select(JobReplay)
|
||||
.where(JobReplay.job_id == job_id)
|
||||
.order_by(JobReplay.created_at)
|
||||
.limit(100)
|
||||
)
|
||||
).all()
|
||||
|
||||
|
||||
def reset_failed(job, attachment, now, attempt_limit):
|
||||
|
||||
+43
-10
@@ -32,7 +32,9 @@ class JobWork:
|
||||
return f"variants/{self.attachment_id.hex}/v{self.pipeline_version}/{filename}"
|
||||
|
||||
|
||||
async def create_job(session: AsyncSession, attachment_id: UUID, staging_key: str) -> UUID:
|
||||
async def create_job(
|
||||
session: AsyncSession, attachment_id: UUID, staging_key: str
|
||||
) -> UUID:
|
||||
job = AttachmentJob(attachment_id=attachment_id, staging_key=staging_key)
|
||||
session.add(job)
|
||||
await session.flush()
|
||||
@@ -58,7 +60,10 @@ async def expired_jobs(session: AsyncSession, limit: int = 20):
|
||||
result = await session.execute(
|
||||
select(AttachmentJob, Attachment)
|
||||
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||
.where(Attachment.status == "processing", AttachmentJob.lease_until < func.clock_timestamp())
|
||||
.where(
|
||||
Attachment.status == "processing",
|
||||
AttachmentJob.lease_until < func.clock_timestamp(),
|
||||
)
|
||||
.order_by(AttachmentJob.lease_until)
|
||||
.limit(limit)
|
||||
.with_for_update(of=AttachmentJob, skip_locked=True)
|
||||
@@ -66,19 +71,35 @@ async def expired_jobs(session: AsyncSession, limit: int = 20):
|
||||
return result.all()
|
||||
|
||||
|
||||
def start_job(job, attachment, token: UUID, now: datetime, lease_seconds: int) -> JobWork:
|
||||
def start_job(
|
||||
job, attachment, token: UUID, now: datetime, lease_seconds: int
|
||||
) -> JobWork:
|
||||
job.attempt += 1
|
||||
job.lease_token = token
|
||||
job.lease_until = now + timedelta(seconds=lease_seconds)
|
||||
attachment.status = "processing"
|
||||
attachment.updated_at = now
|
||||
return JobWork(
|
||||
job.id, attachment.id, token, job.pipeline_version, job.staging_key,
|
||||
attachment.content_type, attachment.size_bytes, attachment.sha256,
|
||||
job.id,
|
||||
attachment.id,
|
||||
token,
|
||||
job.pipeline_version,
|
||||
job.staging_key,
|
||||
attachment.content_type,
|
||||
attachment.size_bytes,
|
||||
attachment.sha256,
|
||||
)
|
||||
|
||||
|
||||
def record_failure(job, attachment, now: datetime, error_code: str, *, terminal: bool, retry_seconds: float) -> None:
|
||||
def record_failure(
|
||||
job,
|
||||
attachment,
|
||||
now: datetime,
|
||||
error_code: str,
|
||||
*,
|
||||
terminal: bool,
|
||||
retry_seconds: float,
|
||||
) -> None:
|
||||
job.lease_token = None
|
||||
job.lease_until = None
|
||||
job.last_error_code = error_code
|
||||
@@ -89,7 +110,9 @@ def record_failure(job, attachment, now: datetime, error_code: str, *, terminal:
|
||||
attachment.updated_at = now
|
||||
|
||||
|
||||
def complete_job(job, attachment, work: JobWork, variants: list[dict], now: datetime) -> None:
|
||||
def complete_job(
|
||||
job, attachment, work: JobWork, variants: list[dict], now: datetime
|
||||
) -> None:
|
||||
attachment.object_key = work.original_key
|
||||
attachment.thumbnail_key = work.variant_key("thumbnail")
|
||||
attachment.crop_key = work.variant_key("crop")
|
||||
@@ -105,15 +128,25 @@ def complete_job(job, attachment, work: JobWork, variants: list[dict], now: date
|
||||
job.finished_at = now
|
||||
|
||||
|
||||
async def terminal_staging(session: AsyncSession, retention: int, failed_retention: int, limit: int = 20):
|
||||
async def terminal_staging(
|
||||
session: AsyncSession, retention: int, failed_retention: int, limit: int = 20
|
||||
):
|
||||
result = await session.execute(
|
||||
select(AttachmentJob, Attachment)
|
||||
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||
.where(
|
||||
AttachmentJob.staging_key.is_not(None),
|
||||
or_(
|
||||
and_(Attachment.status == "ready", AttachmentJob.finished_at < func.clock_timestamp() - timedelta(seconds=retention)),
|
||||
and_(Attachment.status == "failed", AttachmentJob.finished_at < func.clock_timestamp() - timedelta(seconds=failed_retention)),
|
||||
and_(
|
||||
Attachment.status == "ready",
|
||||
AttachmentJob.finished_at
|
||||
< func.clock_timestamp() - timedelta(seconds=retention),
|
||||
),
|
||||
and_(
|
||||
Attachment.status == "failed",
|
||||
AttachmentJob.finished_at
|
||||
< func.clock_timestamp() - timedelta(seconds=failed_retention),
|
||||
),
|
||||
),
|
||||
)
|
||||
.order_by(AttachmentJob.finished_at)
|
||||
|
||||
@@ -9,7 +9,9 @@ from app.models.attachment import Attachment
|
||||
from app.models.job import AttachmentJob
|
||||
|
||||
|
||||
async def next_unpublished_job(session: AsyncSession, *, attachment_id: UUID | None = None) -> AttachmentJob | None:
|
||||
async def next_unpublished_job(
|
||||
session: AsyncSession, *, attachment_id: UUID | None = None
|
||||
) -> AttachmentJob | None:
|
||||
statement = (
|
||||
select(AttachmentJob)
|
||||
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
name: mtusi-messenger-lab5
|
||||
name: messenger
|
||||
|
||||
x-api-image: &api-image
|
||||
build:
|
||||
@@ -73,7 +73,7 @@ services:
|
||||
context: .
|
||||
dockerfile: infra/minio/Dockerfile
|
||||
target: server
|
||||
image: mtusi-messenger-minio:lab5
|
||||
image: messenger-minio:local
|
||||
command: ["server", "/data", "--console-address", "127.0.0.1:9001"]
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
@@ -104,7 +104,7 @@ services:
|
||||
context: .
|
||||
dockerfile: infra/minio/Dockerfile
|
||||
target: bootstrap
|
||||
image: mtusi-messenger-minio-bootstrap:lab5
|
||||
image: messenger-minio-bootstrap:local
|
||||
environment:
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:?Set S3_ENDPOINT in .env}
|
||||
S3_BUCKET: ${S3_BUCKET:?Set S3_BUCKET in .env}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"results": [
|
||||
{
|
||||
"scenario": "worker_stopped_restart_all",
|
||||
"attachment_id": "96d4fc78-4e72-473c-a2a9-57db94421707",
|
||||
"attachment_id": "f5cc75ba-d2c7-43ff-8cf4-123b723118b8",
|
||||
"queue_before": {
|
||||
"name": "attachment-jobs",
|
||||
"messages_unacknowledged": 0,
|
||||
@@ -19,13 +19,13 @@
|
||||
"messages_ready": 1
|
||||
},
|
||||
"after": {
|
||||
"job_id": "b3a81ec6-65d6-4201-aeb9-fedbe92fdaaf",
|
||||
"job_id": "9adcea8e-9046-4736-9763-c24bb6daf417",
|
||||
"status": "ready",
|
||||
"attempt": 1,
|
||||
"published_attempt": 1,
|
||||
"limit": 5,
|
||||
"updated_at": "2026-11-10 03:27:44.556734+00:00",
|
||||
"next_attempt_at": "2026-11-10 03:26:56.662360+00:00",
|
||||
"updated_at": "2026-11-10 04:36:45.543612+00:00",
|
||||
"next_attempt_at": "2026-11-10 04:35:56.727228+00:00",
|
||||
"last_error_code": null,
|
||||
"permanent": null,
|
||||
"objects": [
|
||||
@@ -33,41 +33,41 @@
|
||||
"name": "crop.jpg",
|
||||
"size": 2462,
|
||||
"sha256": "fae35500205a78065cf7d589f121cc909b017e2a4cde882177e24f5608fb4c1f",
|
||||
"last_modified": "2026-11-10 03:27:44.548000+00:00"
|
||||
"last_modified": "2026-11-10 04:36:45.525000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "optimized.webp",
|
||||
"size": 2462,
|
||||
"sha256": "1090d84ed8411226010ae498b08e1b9e6d81c8eee02ee77143a0dc327b894beb",
|
||||
"last_modified": "2026-11-10 03:27:44.552000+00:00"
|
||||
"last_modified": "2026-11-10 04:36:45.533000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "thumbnail.jpg",
|
||||
"size": 5813,
|
||||
"sha256": "b8e59b0cad429b1c49c27c4a1c79e52bfc23e2fab7c7238d18d5addd4df4b546",
|
||||
"last_modified": "2026-11-10 03:27:44.543000+00:00"
|
||||
"last_modified": "2026-11-10 04:36:45.521000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "v1",
|
||||
"size": 111817,
|
||||
"sha256": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75",
|
||||
"last_modified": "2026-11-10 03:27:44.536000+00:00"
|
||||
"last_modified": "2026-11-10 04:36:45.508000+00:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"scenario": "crash-after-object",
|
||||
"attachment_id": "115c5e05-3d09-4f04-9b32-0d27597b65fc",
|
||||
"attachment_id": "1927c264-c721-4de1-8914-32d9beab48e5",
|
||||
"exit_code": 137,
|
||||
"before": {
|
||||
"job_id": "ba3dc221-5651-4c1d-8bfd-9fd61c8aa854",
|
||||
"job_id": "bda1d00d-41c7-4d28-b2e5-07759be55985",
|
||||
"status": "processing",
|
||||
"attempt": 1,
|
||||
"published_attempt": 1,
|
||||
"limit": 5,
|
||||
"updated_at": "2026-11-10 03:27:49.144648+00:00",
|
||||
"next_attempt_at": "2026-11-10 03:27:47.218612+00:00",
|
||||
"updated_at": "2026-11-10 04:36:50.666631+00:00",
|
||||
"next_attempt_at": "2026-11-10 04:36:48.673346+00:00",
|
||||
"last_error_code": null,
|
||||
"permanent": null,
|
||||
"objects": [
|
||||
@@ -75,36 +75,36 @@
|
||||
"name": "crop.jpg",
|
||||
"size": 2462,
|
||||
"sha256": "fae35500205a78065cf7d589f121cc909b017e2a4cde882177e24f5608fb4c1f",
|
||||
"last_modified": "2026-11-10 03:27:49.912000+00:00"
|
||||
"last_modified": "2026-11-10 04:36:51.443000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "optimized.webp",
|
||||
"size": 2462,
|
||||
"sha256": "1090d84ed8411226010ae498b08e1b9e6d81c8eee02ee77143a0dc327b894beb",
|
||||
"last_modified": "2026-11-10 03:27:49.917000+00:00"
|
||||
"last_modified": "2026-11-10 04:36:51.448000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "thumbnail.jpg",
|
||||
"size": 5813,
|
||||
"sha256": "b8e59b0cad429b1c49c27c4a1c79e52bfc23e2fab7c7238d18d5addd4df4b546",
|
||||
"last_modified": "2026-11-10 03:27:49.907000+00:00"
|
||||
"last_modified": "2026-11-10 04:36:51.434000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "v1",
|
||||
"size": 111817,
|
||||
"sha256": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75",
|
||||
"last_modified": "2026-11-10 03:27:49.894000+00:00"
|
||||
"last_modified": "2026-11-10 04:36:51.420000+00:00"
|
||||
}
|
||||
]
|
||||
},
|
||||
"after": {
|
||||
"job_id": "ba3dc221-5651-4c1d-8bfd-9fd61c8aa854",
|
||||
"job_id": "bda1d00d-41c7-4d28-b2e5-07759be55985",
|
||||
"status": "ready",
|
||||
"attempt": 2,
|
||||
"published_attempt": 2,
|
||||
"limit": 5,
|
||||
"updated_at": "2026-11-10 03:29:24.765539+00:00",
|
||||
"next_attempt_at": "2026-11-10 03:29:23.142176+00:00",
|
||||
"updated_at": "2026-11-10 04:38:26.694238+00:00",
|
||||
"next_attempt_at": "2026-11-10 04:38:25.019759+00:00",
|
||||
"last_error_code": null,
|
||||
"permanent": null,
|
||||
"objects": [
|
||||
@@ -112,41 +112,41 @@
|
||||
"name": "crop.jpg",
|
||||
"size": 2462,
|
||||
"sha256": "fae35500205a78065cf7d589f121cc909b017e2a4cde882177e24f5608fb4c1f",
|
||||
"last_modified": "2026-11-10 03:29:24.750000+00:00"
|
||||
"last_modified": "2026-11-10 04:38:26.675000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "optimized.webp",
|
||||
"size": 2462,
|
||||
"sha256": "1090d84ed8411226010ae498b08e1b9e6d81c8eee02ee77143a0dc327b894beb",
|
||||
"last_modified": "2026-11-10 03:29:24.758000+00:00"
|
||||
"last_modified": "2026-11-10 04:38:26.686000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "thumbnail.jpg",
|
||||
"size": 5813,
|
||||
"sha256": "b8e59b0cad429b1c49c27c4a1c79e52bfc23e2fab7c7238d18d5addd4df4b546",
|
||||
"last_modified": "2026-11-10 03:29:24.742000+00:00"
|
||||
"last_modified": "2026-11-10 04:38:26.666000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "v1",
|
||||
"size": 111817,
|
||||
"sha256": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75",
|
||||
"last_modified": "2026-11-10 03:29:24.725000+00:00"
|
||||
"last_modified": "2026-11-10 04:38:26.656000+00:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"scenario": "crash-before-ack",
|
||||
"attachment_id": "2f97fc61-fc07-47da-98a8-9d9894ed4cd1",
|
||||
"attachment_id": "e02d817d-9615-4058-ae5c-63ab895aa6f5",
|
||||
"exit_code": 137,
|
||||
"before": {
|
||||
"job_id": "4a0bc78c-d79a-4e1a-88f7-11ad03045135",
|
||||
"job_id": "9bfea78c-ce05-4a00-bf76-a2213ed3a8df",
|
||||
"status": "ready",
|
||||
"attempt": 1,
|
||||
"published_attempt": 1,
|
||||
"limit": 5,
|
||||
"updated_at": "2026-11-10 03:29:29.833142+00:00",
|
||||
"next_attempt_at": "2026-11-10 03:29:27.262932+00:00",
|
||||
"updated_at": "2026-11-10 04:38:32.063984+00:00",
|
||||
"next_attempt_at": "2026-11-10 04:38:29.436074+00:00",
|
||||
"last_error_code": null,
|
||||
"permanent": null,
|
||||
"objects": [
|
||||
@@ -154,36 +154,36 @@
|
||||
"name": "crop.jpg",
|
||||
"size": 2462,
|
||||
"sha256": "fae35500205a78065cf7d589f121cc909b017e2a4cde882177e24f5608fb4c1f",
|
||||
"last_modified": "2026-11-10 03:29:29.824000+00:00"
|
||||
"last_modified": "2026-11-10 04:38:32.054000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "optimized.webp",
|
||||
"size": 2462,
|
||||
"sha256": "1090d84ed8411226010ae498b08e1b9e6d81c8eee02ee77143a0dc327b894beb",
|
||||
"last_modified": "2026-11-10 03:29:29.829000+00:00"
|
||||
"last_modified": "2026-11-10 04:38:32.059000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "thumbnail.jpg",
|
||||
"size": 5813,
|
||||
"sha256": "b8e59b0cad429b1c49c27c4a1c79e52bfc23e2fab7c7238d18d5addd4df4b546",
|
||||
"last_modified": "2026-11-10 03:29:29.818000+00:00"
|
||||
"last_modified": "2026-11-10 04:38:32.048000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "v1",
|
||||
"size": 111817,
|
||||
"sha256": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75",
|
||||
"last_modified": "2026-11-10 03:29:29.805000+00:00"
|
||||
"last_modified": "2026-11-10 04:38:32.032000+00:00"
|
||||
}
|
||||
]
|
||||
},
|
||||
"after": {
|
||||
"job_id": "4a0bc78c-d79a-4e1a-88f7-11ad03045135",
|
||||
"job_id": "9bfea78c-ce05-4a00-bf76-a2213ed3a8df",
|
||||
"status": "ready",
|
||||
"attempt": 1,
|
||||
"published_attempt": 1,
|
||||
"limit": 5,
|
||||
"updated_at": "2026-11-10 03:29:29.833142+00:00",
|
||||
"next_attempt_at": "2026-11-10 03:29:27.262932+00:00",
|
||||
"updated_at": "2026-11-10 04:38:32.063984+00:00",
|
||||
"next_attempt_at": "2026-11-10 04:38:29.436074+00:00",
|
||||
"last_error_code": null,
|
||||
"permanent": null,
|
||||
"objects": [
|
||||
@@ -191,102 +191,102 @@
|
||||
"name": "crop.jpg",
|
||||
"size": 2462,
|
||||
"sha256": "fae35500205a78065cf7d589f121cc909b017e2a4cde882177e24f5608fb4c1f",
|
||||
"last_modified": "2026-11-10 03:29:29.824000+00:00"
|
||||
"last_modified": "2026-11-10 04:38:32.054000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "optimized.webp",
|
||||
"size": 2462,
|
||||
"sha256": "1090d84ed8411226010ae498b08e1b9e6d81c8eee02ee77143a0dc327b894beb",
|
||||
"last_modified": "2026-11-10 03:29:29.829000+00:00"
|
||||
"last_modified": "2026-11-10 04:38:32.059000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "thumbnail.jpg",
|
||||
"size": 5813,
|
||||
"sha256": "b8e59b0cad429b1c49c27c4a1c79e52bfc23e2fab7c7238d18d5addd4df4b546",
|
||||
"last_modified": "2026-11-10 03:29:29.818000+00:00"
|
||||
"last_modified": "2026-11-10 04:38:32.048000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "v1",
|
||||
"size": 111817,
|
||||
"sha256": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75",
|
||||
"last_modified": "2026-11-10 03:29:29.805000+00:00"
|
||||
"last_modified": "2026-11-10 04:38:32.032000+00:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"scenario": "fail-transient",
|
||||
"attachment_id": "92c4de14-53cd-4805-a842-9892a8b7a5ea",
|
||||
"attachment_id": "a9c15ce8-cacf-43c0-8373-8e3ff5fa23aa",
|
||||
"samples": [
|
||||
{
|
||||
"job_id": "f44f6bfa-9fde-4616-b3cf-83dde54b1154",
|
||||
"job_id": "ffa9abca-645a-4ee2-ab2a-7bd06a7e0a59",
|
||||
"status": "queued",
|
||||
"attempt": 1,
|
||||
"published_attempt": 1,
|
||||
"limit": 5,
|
||||
"updated_at": "2026-11-10 03:29:45.863494+00:00",
|
||||
"next_attempt_at": "2026-11-10 03:29:50.476742+00:00",
|
||||
"updated_at": "2026-11-10 04:38:46.283315+00:00",
|
||||
"next_attempt_at": "2026-11-10 04:38:50.994899+00:00",
|
||||
"last_error_code": "processing_timeout",
|
||||
"permanent": false,
|
||||
"objects": []
|
||||
},
|
||||
{
|
||||
"job_id": "f44f6bfa-9fde-4616-b3cf-83dde54b1154",
|
||||
"job_id": "ffa9abca-645a-4ee2-ab2a-7bd06a7e0a59",
|
||||
"status": "queued",
|
||||
"attempt": 2,
|
||||
"published_attempt": 2,
|
||||
"limit": 5,
|
||||
"updated_at": "2026-11-10 03:29:51.216904+00:00",
|
||||
"next_attempt_at": "2026-11-10 03:29:58.053724+00:00",
|
||||
"updated_at": "2026-11-10 04:38:51.039278+00:00",
|
||||
"next_attempt_at": "2026-11-10 04:38:59.940067+00:00",
|
||||
"last_error_code": "processing_timeout",
|
||||
"permanent": false,
|
||||
"objects": []
|
||||
},
|
||||
{
|
||||
"job_id": "f44f6bfa-9fde-4616-b3cf-83dde54b1154",
|
||||
"job_id": "ffa9abca-645a-4ee2-ab2a-7bd06a7e0a59",
|
||||
"status": "queued",
|
||||
"attempt": 3,
|
||||
"published_attempt": 3,
|
||||
"limit": 5,
|
||||
"updated_at": "2026-11-10 03:29:58.279470+00:00",
|
||||
"next_attempt_at": "2026-11-10 03:30:15.602067+00:00",
|
||||
"updated_at": "2026-11-10 04:39:00.122276+00:00",
|
||||
"next_attempt_at": "2026-11-10 04:39:19.754304+00:00",
|
||||
"last_error_code": "processing_timeout",
|
||||
"permanent": false,
|
||||
"objects": []
|
||||
},
|
||||
{
|
||||
"job_id": "f44f6bfa-9fde-4616-b3cf-83dde54b1154",
|
||||
"job_id": "ffa9abca-645a-4ee2-ab2a-7bd06a7e0a59",
|
||||
"status": "queued",
|
||||
"attempt": 4,
|
||||
"published_attempt": 4,
|
||||
"limit": 5,
|
||||
"updated_at": "2026-11-10 03:30:16.386336+00:00",
|
||||
"next_attempt_at": "2026-11-10 03:30:47.271081+00:00",
|
||||
"updated_at": "2026-11-10 04:39:20.250087+00:00",
|
||||
"next_attempt_at": "2026-11-10 04:39:56.121121+00:00",
|
||||
"last_error_code": "processing_timeout",
|
||||
"permanent": false,
|
||||
"objects": []
|
||||
},
|
||||
{
|
||||
"job_id": "f44f6bfa-9fde-4616-b3cf-83dde54b1154",
|
||||
"job_id": "ffa9abca-645a-4ee2-ab2a-7bd06a7e0a59",
|
||||
"status": "failed",
|
||||
"attempt": 5,
|
||||
"published_attempt": 5,
|
||||
"limit": 5,
|
||||
"updated_at": "2026-11-10 03:30:47.622716+00:00",
|
||||
"next_attempt_at": "2026-11-10 03:31:30.255216+00:00",
|
||||
"updated_at": "2026-11-10 04:39:56.526646+00:00",
|
||||
"next_attempt_at": "2026-11-10 04:41:15.809038+00:00",
|
||||
"last_error_code": "processing_timeout",
|
||||
"permanent": false,
|
||||
"objects": []
|
||||
}
|
||||
],
|
||||
"after": {
|
||||
"job_id": "f44f6bfa-9fde-4616-b3cf-83dde54b1154",
|
||||
"job_id": "ffa9abca-645a-4ee2-ab2a-7bd06a7e0a59",
|
||||
"status": "ready",
|
||||
"attempt": 6,
|
||||
"published_attempt": 6,
|
||||
"limit": 10,
|
||||
"updated_at": "2026-11-10 03:30:59.696883+00:00",
|
||||
"next_attempt_at": "2026-11-10 03:30:53.135190+00:00",
|
||||
"updated_at": "2026-11-10 04:40:09.651133+00:00",
|
||||
"next_attempt_at": "2026-11-10 04:40:03.031585+00:00",
|
||||
"last_error_code": null,
|
||||
"permanent": null,
|
||||
"objects": [
|
||||
@@ -294,25 +294,25 @@
|
||||
"name": "crop.jpg",
|
||||
"size": 2462,
|
||||
"sha256": "fae35500205a78065cf7d589f121cc909b017e2a4cde882177e24f5608fb4c1f",
|
||||
"last_modified": "2026-11-10 03:30:59.687000+00:00"
|
||||
"last_modified": "2026-11-10 04:40:09.642000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "optimized.webp",
|
||||
"size": 2462,
|
||||
"sha256": "1090d84ed8411226010ae498b08e1b9e6d81c8eee02ee77143a0dc327b894beb",
|
||||
"last_modified": "2026-11-10 03:30:59.692000+00:00"
|
||||
"last_modified": "2026-11-10 04:40:09.647000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "thumbnail.jpg",
|
||||
"size": 5813,
|
||||
"sha256": "b8e59b0cad429b1c49c27c4a1c79e52bfc23e2fab7c7238d18d5addd4df4b546",
|
||||
"last_modified": "2026-11-10 03:30:59.683000+00:00"
|
||||
"last_modified": "2026-11-10 04:40:09.637000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "v1",
|
||||
"size": 111817,
|
||||
"sha256": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75",
|
||||
"last_modified": "2026-11-10 03:30:59.670000+00:00"
|
||||
"last_modified": "2026-11-10 04:40:09.624000+00:00"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -320,29 +320,29 @@
|
||||
},
|
||||
{
|
||||
"scenario": "fail-permanent",
|
||||
"attachment_id": "92e2baff-5b26-4326-bee6-269382ff80c9",
|
||||
"attachment_id": "d8a6e312-e468-4e4b-a7ee-1d84751d5843",
|
||||
"samples": [
|
||||
{
|
||||
"job_id": "f462098d-43b7-41cc-afe8-399aaf3ed0bd",
|
||||
"job_id": "0da2ef52-65a8-4a74-8d43-015666e2975c",
|
||||
"status": "failed",
|
||||
"attempt": 1,
|
||||
"published_attempt": 1,
|
||||
"limit": 5,
|
||||
"updated_at": "2026-11-10 03:31:12.333162+00:00",
|
||||
"next_attempt_at": "2026-11-10 03:31:16.827024+00:00",
|
||||
"updated_at": "2026-11-10 04:40:24.826416+00:00",
|
||||
"next_attempt_at": "2026-11-10 04:40:29.630307+00:00",
|
||||
"last_error_code": "injected_permanent",
|
||||
"permanent": true,
|
||||
"objects": []
|
||||
}
|
||||
],
|
||||
"after": {
|
||||
"job_id": "f462098d-43b7-41cc-afe8-399aaf3ed0bd",
|
||||
"job_id": "0da2ef52-65a8-4a74-8d43-015666e2975c",
|
||||
"status": "ready",
|
||||
"attempt": 2,
|
||||
"published_attempt": 2,
|
||||
"limit": 6,
|
||||
"updated_at": "2026-11-10 03:31:24.282794+00:00",
|
||||
"next_attempt_at": "2026-11-10 03:31:17.137221+00:00",
|
||||
"updated_at": "2026-11-10 04:40:40.004814+00:00",
|
||||
"next_attempt_at": "2026-11-10 04:40:30.084006+00:00",
|
||||
"last_error_code": null,
|
||||
"permanent": null,
|
||||
"objects": [
|
||||
@@ -350,25 +350,25 @@
|
||||
"name": "crop.jpg",
|
||||
"size": 2462,
|
||||
"sha256": "fae35500205a78065cf7d589f121cc909b017e2a4cde882177e24f5608fb4c1f",
|
||||
"last_modified": "2026-11-10 03:31:24.272000+00:00"
|
||||
"last_modified": "2026-11-10 04:40:39.988000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "optimized.webp",
|
||||
"size": 2462,
|
||||
"sha256": "1090d84ed8411226010ae498b08e1b9e6d81c8eee02ee77143a0dc327b894beb",
|
||||
"last_modified": "2026-11-10 03:31:24.278000+00:00"
|
||||
"last_modified": "2026-11-10 04:40:39.996000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "thumbnail.jpg",
|
||||
"size": 5813,
|
||||
"sha256": "b8e59b0cad429b1c49c27c4a1c79e52bfc23e2fab7c7238d18d5addd4df4b546",
|
||||
"last_modified": "2026-11-10 03:31:24.267000+00:00"
|
||||
"last_modified": "2026-11-10 04:40:39.982000+00:00"
|
||||
},
|
||||
{
|
||||
"name": "v1",
|
||||
"size": 111817,
|
||||
"sha256": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75",
|
||||
"last_modified": "2026-11-10 03:31:24.254000+00:00"
|
||||
"last_modified": "2026-11-10 04:40:39.968000+00:00"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 tests/smoke.py --base-url "http://localhost:28080"
|
||||
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -157,7 +157,7 @@
|
||||
{
|
||||
"name": "worker_fault_retry_replay",
|
||||
"exit_code": 0,
|
||||
"evidence": "lab5-jobs.json",
|
||||
"evidence": "jobs.json",
|
||||
"scenarios": [
|
||||
"worker_stopped_restart_all",
|
||||
"crash-after-object",
|
||||
@@ -267,5 +267,42 @@
|
||||
"Single Docker host, no disk-loss or cluster failover claim",
|
||||
"Grade 5 experiments not performed",
|
||||
"No production-scale performance/security claim"
|
||||
]
|
||||
],
|
||||
"post_test_cleanup": {
|
||||
"date": "2026-11-10",
|
||||
"project_removed": "mtusi-lab5-verification",
|
||||
"test_volumes_removed": 4,
|
||||
"conserver_removed": true,
|
||||
"old_lab3_image_removed": true,
|
||||
"old_empty_networks_removed": true,
|
||||
"current_lab5_images_retained": true
|
||||
},
|
||||
"maintenance_checks": {
|
||||
"status": "passed",
|
||||
"command": "make test-suite",
|
||||
"project": "messenger-test",
|
||||
"pipeline_tests": 42,
|
||||
"checks": [
|
||||
"contract",
|
||||
"OpenAPI",
|
||||
"Compose startup",
|
||||
"public smoke",
|
||||
"MinIO private access/bootstrap",
|
||||
"outbox recovery",
|
||||
"worker_stopped_restart_all",
|
||||
"crash-after-object",
|
||||
"crash-before-ack",
|
||||
"fail-transient",
|
||||
"fail-permanent"
|
||||
],
|
||||
"standalone_nginx": "passed",
|
||||
"test_resources_removed": true,
|
||||
"obsolete_image_tags_removed": [
|
||||
"mtusi-messenger-minio-bootstrap:lab5",
|
||||
"mtusi-messenger-minio:lab5",
|
||||
"mtusi-messenger:lab5"
|
||||
],
|
||||
"regression_tests_preserved": true,
|
||||
"note": "Earlier recorded commands retain their original names as historical evidence; operational scripts and resource names are now neutral."
|
||||
}
|
||||
}
|
||||
+13
-24
@@ -1,27 +1,16 @@
|
||||
# Инфраструктура студента
|
||||
# Инфраструктура
|
||||
|
||||
Топология — compose.yaml. compose.test.yaml публикует тестовые PostgreSQL/Redis
|
||||
только на localhost. Nginx направляет запросы на две API-реплики.
|
||||
compose.yaml запускает две API-реплики за nginx, PostgreSQL, Redis сессий,
|
||||
RabbitMQ, приватный MinIO, publisher, worker и cleanup. Все environment-настройки
|
||||
берутся из .env; credentials передаются файлами secrets. Миграции и bootstrap
|
||||
завершаются до старта зависимых сервисов.
|
||||
|
||||
PostgreSQL хранит сообщения, metadata, jobs/outbox и аудит replay. Redis 7.4.2
|
||||
с AOF хранит сессии. RabbitMQ 4.4.0 — отдельный брокер заданий: durable очередь,
|
||||
persistent сообщения, publisher confirms, manual consumer ack и rabbitmqdata.
|
||||
Broker и MinIO не публикуют внешние порты. API не получает credentials брокера.
|
||||
Publisher читает outbox PostgreSQL и ждёт подтверждения RabbitMQ. Worker фиксирует
|
||||
результат в MinIO/PostgreSQL до ack; prefetch=1 на consumer. init:true обеспечивает
|
||||
корректные сигналы. Broker и хранилища не публикуют внешние порты.
|
||||
|
||||
Publisher читает jobs из PostgreSQL и публикует их в RabbitMQ. Worker сохраняет
|
||||
original/thumbnail/crop/optimized в приватный MinIO и фиксирует ready до ack.
|
||||
Конкуренция ограничена WORKER_CONCURRENCY; prefetch=1 на отдельный канал каждого
|
||||
consumer. Publisher/worker используют init:true для корректных сигналов и
|
||||
воспроизводимого SIGKILL. Обычный Compose-запуск fault hooks не включает.
|
||||
|
||||
Все environment-настройки Compose берутся из .env; образец — .env.example.
|
||||
Credentials передаются файлами secrets; make init создаёт только отсутствующие.
|
||||
Migrate и minio-bootstrap завершаются до старта зависимых сервисов.
|
||||
Перед обновлением остановить старые процессы без удаления volumes. Миграция
|
||||
a62c950e18b3 повторно публикует queued jobs при переходе на RabbitMQ.
|
||||
|
||||
Restart hook сохраняет volumes и состояние заранее остановленного worker.
|
||||
Failover hook останавливает выбранную API-реплику. Retry, retention, операторские
|
||||
команды, ограничения и результаты проверок описаны в REPORT.md.
|
||||
Полный прогон lab5 уровня 4 — make test-grade4; отдельные сценарии —
|
||||
make test-outbox-recovery и make test-jobs на выбранном работающем стенде.
|
||||
make up/down управляют основным проектом messenger и сохраняют volumes.
|
||||
make test-suite использует отдельный messenger-test и удаляет его вместе с
|
||||
volumes и сетями при завершении. compose.test.yaml открывает тестовые PostgreSQL
|
||||
и Redis только на localhost. Полная регрессия доступна через make test-unit,
|
||||
отдельные проверки — make test-nginx, test-storage, test-outbox и test-jobs.
|
||||
|
||||
@@ -81,7 +81,10 @@ def main():
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
|
||||
"Resource": [f"arn:aws:s3:::{bucket}/{prefix}/*" for prefix in ("originals", "staging", "variants")],
|
||||
"Resource": [
|
||||
f"arn:aws:s3:::{bucket}/{prefix}/*"
|
||||
for prefix in ("originals", "staging", "variants")
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
@@ -20,21 +20,26 @@ def upgrade() -> None:
|
||||
sa.Column("request_hash", sa.String(64), nullable=False),
|
||||
sa.Column("message_id", sa.UUID(), nullable=False),
|
||||
sa.Column(
|
||||
"created_at", sa.DateTime(timezone=True),
|
||||
server_default=sa.text("clock_timestamp()"), nullable=False,
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("clock_timestamp()"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["user_id"], ["users.id"], name=op.f("fk_idempotency_keys_user_id_users")
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["message_id"], ["messages.id"],
|
||||
["message_id"],
|
||||
["messages.id"],
|
||||
name=op.f("fk_idempotency_keys_message_id_messages"),
|
||||
),
|
||||
sa.PrimaryKeyConstraint(
|
||||
"user_id", "method", "path", "key", name=op.f("pk_idempotency_keys")
|
||||
),
|
||||
)
|
||||
op.create_index("ix_idempotency_keys_created_at", "idempotency_keys", ["created_at"])
|
||||
op.create_index(
|
||||
"ix_idempotency_keys_created_at", "idempotency_keys", ["created_at"]
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
|
||||
@@ -21,14 +21,35 @@ def upgrade() -> None:
|
||||
sa.Column("size_bytes", sa.Integer(), nullable=False),
|
||||
sa.Column("sha256", sa.String(64), nullable=False),
|
||||
sa.Column("status", sa.String(16), server_default="ready", nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("clock_timestamp()"), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("clock_timestamp()"), nullable=False),
|
||||
sa.CheckConstraint("size_bytes BETWEEN 1 AND 10485760", name=op.f("ck_attachments_size_bytes")),
|
||||
sa.CheckConstraint("content_type IN ('image/png', 'image/jpeg')", name=op.f("ck_attachments_content_type")),
|
||||
sa.CheckConstraint("sha256 ~ '^[a-f0-9]{64}$'", name=op.f("ck_attachments_sha256")),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("clock_timestamp()"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column(
|
||||
"updated_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("clock_timestamp()"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"size_bytes BETWEEN 1 AND 10485760", name=op.f("ck_attachments_size_bytes")
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"content_type IN ('image/png', 'image/jpeg')",
|
||||
name=op.f("ck_attachments_content_type"),
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"sha256 ~ '^[a-f0-9]{64}$'", name=op.f("ck_attachments_sha256")
|
||||
),
|
||||
sa.CheckConstraint("status = 'ready'", name=op.f("ck_attachments_status")),
|
||||
sa.ForeignKeyConstraint(["chat_id"], ["chats.id"], name=op.f("fk_attachments_chat_id_chats")),
|
||||
sa.ForeignKeyConstraint(["owner_id"], ["users.id"], name=op.f("fk_attachments_owner_id_users")),
|
||||
sa.ForeignKeyConstraint(
|
||||
["chat_id"], ["chats.id"], name=op.f("fk_attachments_chat_id_chats")
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["owner_id"], ["users.id"], name=op.f("fk_attachments_owner_id_users")
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_attachments")),
|
||||
sa.UniqueConstraint("object_key", name=op.f("uq_attachments_object_key")),
|
||||
)
|
||||
@@ -38,15 +59,31 @@ def upgrade() -> None:
|
||||
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(["message_id"], ["messages.id"], ondelete="CASCADE", name=op.f("fk_message_attachments_message_id_messages")),
|
||||
sa.ForeignKeyConstraint(["attachment_id"], ["attachments.id"], name=op.f("fk_message_attachments_attachment_id_attachments")),
|
||||
sa.PrimaryKeyConstraint("message_id", "attachment_id", name=op.f("pk_message_attachments")),
|
||||
sa.ForeignKeyConstraint(
|
||||
["message_id"],
|
||||
["messages.id"],
|
||||
ondelete="CASCADE",
|
||||
name=op.f("fk_message_attachments_message_id_messages"),
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["attachment_id"],
|
||||
["attachments.id"],
|
||||
name=op.f("fk_message_attachments_attachment_id_attachments"),
|
||||
),
|
||||
sa.PrimaryKeyConstraint(
|
||||
"message_id", "attachment_id", name=op.f("pk_message_attachments")
|
||||
),
|
||||
)
|
||||
op.create_table(
|
||||
"upload_intents",
|
||||
sa.Column("id", sa.UUID(), nullable=False),
|
||||
sa.Column("object_key", sa.String(128), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("clock_timestamp()"), nullable=False),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("clock_timestamp()"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_upload_intents")),
|
||||
sa.UniqueConstraint("object_key", name=op.f("uq_upload_intents_object_key")),
|
||||
)
|
||||
|
||||
@@ -5,29 +5,30 @@ Revises: db06fd3126ff
|
||||
Create Date: 2026-10-26 22:01:01.910396
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = 'abd273076068'
|
||||
down_revision: Union[str, None] = 'db06fd3126ff'
|
||||
revision: str = "abd273076068"
|
||||
down_revision: Union[str, None] = "db06fd3126ff"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('counters',
|
||||
sa.Column('name', sa.String(length=64), nullable=False),
|
||||
sa.Column('value', sa.BigInteger(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('name', name=op.f('pk_counters'))
|
||||
op.create_table(
|
||||
"counters",
|
||||
sa.Column("name", sa.String(length=64), nullable=False),
|
||||
sa.Column("value", sa.BigInteger(), nullable=False),
|
||||
sa.PrimaryKeyConstraint("name", name=op.f("pk_counters")),
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table('counters')
|
||||
op.drop_table("counters")
|
||||
# ### end Alembic commands ###
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Lab5: состояния, варианты и устойчивые jobs с намерением публикации."""
|
||||
"""Состояния, варианты и устойчивые jobs с намерением публикации."""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
@@ -12,12 +12,30 @@ depends_on = None
|
||||
|
||||
def upgrade() -> None:
|
||||
op.drop_constraint(op.f("ck_attachments_status"), "attachments", type_="check")
|
||||
op.create_check_constraint(op.f("ck_attachments_status"), "attachments", "status IN ('queued', 'processing', 'ready', 'failed')")
|
||||
op.create_check_constraint(
|
||||
op.f("ck_attachments_status"),
|
||||
"attachments",
|
||||
"status IN ('queued', 'processing', 'ready', 'failed')",
|
||||
)
|
||||
op.alter_column("attachments", "status", server_default="queued")
|
||||
op.add_column("attachments", sa.Column("error_code", sa.String(64), nullable=True))
|
||||
op.add_column("attachments", sa.Column("thumbnail_key", sa.String(128), nullable=True))
|
||||
op.add_column("attachments", sa.Column("variants", postgresql.JSONB(), nullable=False, server_default=sa.text("'[]'::jsonb")))
|
||||
op.create_check_constraint(op.f("ck_attachments_error_code"), "attachments", "(status = 'failed' AND error_code IS NOT NULL) OR (status <> 'failed' AND error_code IS NULL)")
|
||||
op.add_column(
|
||||
"attachments", sa.Column("thumbnail_key", sa.String(128), nullable=True)
|
||||
)
|
||||
op.add_column(
|
||||
"attachments",
|
||||
sa.Column(
|
||||
"variants",
|
||||
postgresql.JSONB(),
|
||||
nullable=False,
|
||||
server_default=sa.text("'[]'::jsonb"),
|
||||
),
|
||||
)
|
||||
op.create_check_constraint(
|
||||
op.f("ck_attachments_error_code"),
|
||||
"attachments",
|
||||
"(status = 'failed' AND error_code IS NOT NULL) OR (status <> 'failed' AND error_code IS NULL)",
|
||||
)
|
||||
op.create_table(
|
||||
"attachment_jobs",
|
||||
sa.Column("id", sa.UUID(), nullable=False),
|
||||
@@ -25,31 +43,62 @@ def upgrade() -> None:
|
||||
sa.Column("staging_key", sa.String(128), nullable=True),
|
||||
sa.Column("pipeline_version", sa.Integer(), server_default="1", nullable=False),
|
||||
sa.Column("attempt", sa.Integer(), server_default="0", nullable=False),
|
||||
sa.Column("published_attempt", sa.Integer(), server_default="0", nullable=False),
|
||||
sa.Column("next_attempt_at", sa.DateTime(timezone=True), server_default=sa.text("clock_timestamp()"), nullable=False),
|
||||
sa.Column(
|
||||
"published_attempt", sa.Integer(), server_default="0", nullable=False
|
||||
),
|
||||
sa.Column(
|
||||
"next_attempt_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("clock_timestamp()"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("lease_token", sa.UUID(), nullable=True),
|
||||
sa.Column("lease_until", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("last_error_code", sa.String(64), nullable=True),
|
||||
sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("clock_timestamp()"), nullable=False),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("clock_timestamp()"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_attachment_jobs")),
|
||||
sa.ForeignKeyConstraint(["attachment_id"], ["attachments.id"], name=op.f("fk_attachment_jobs_attachment_id_attachments")),
|
||||
sa.UniqueConstraint("attachment_id", name=op.f("uq_attachment_jobs_attachment_id")),
|
||||
sa.CheckConstraint("pipeline_version = 1", name=op.f("ck_attachment_jobs_pipeline_version")),
|
||||
sa.CheckConstraint("attempt >= 0 AND published_attempt >= 0", name=op.f("ck_attachment_jobs_attempt")),
|
||||
sa.ForeignKeyConstraint(
|
||||
["attachment_id"],
|
||||
["attachments.id"],
|
||||
name=op.f("fk_attachment_jobs_attachment_id_attachments"),
|
||||
),
|
||||
sa.UniqueConstraint(
|
||||
"attachment_id", name=op.f("uq_attachment_jobs_attachment_id")
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"pipeline_version = 1", name=op.f("ck_attachment_jobs_pipeline_version")
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"attempt >= 0 AND published_attempt >= 0",
|
||||
name=op.f("ck_attachment_jobs_attempt"),
|
||||
),
|
||||
)
|
||||
op.create_index("ix_attachment_jobs_due", "attachment_jobs", ["next_attempt_at"])
|
||||
op.create_index("ix_attachment_jobs_lease", "attachment_jobs", ["lease_until"])
|
||||
# Прежние оригиналы остаются источником; worker создаст отсутствующий thumbnail.
|
||||
op.execute("INSERT INTO attachment_jobs (id, attachment_id, staging_key) SELECT id, id, object_key FROM attachments")
|
||||
op.execute("UPDATE attachments SET status = 'queued', updated_at = clock_timestamp()")
|
||||
op.execute(
|
||||
"INSERT INTO attachment_jobs (id, attachment_id, staging_key) SELECT id, id, object_key FROM attachments"
|
||||
)
|
||||
op.execute(
|
||||
"UPDATE attachments SET status = 'queued', updated_at = clock_timestamp()"
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
connection = op.get_bind()
|
||||
unfinished = connection.scalar(sa.text("SELECT count(*) FROM attachments WHERE status <> 'ready'"))
|
||||
unfinished = connection.scalar(
|
||||
sa.text("SELECT count(*) FROM attachments WHERE status <> 'ready'")
|
||||
)
|
||||
if unfinished:
|
||||
raise RuntimeError("Перед downgrade нужно завершить или вручную разобрать все queued/processing/failed вложения")
|
||||
raise RuntimeError(
|
||||
"Перед downgrade нужно завершить или вручную разобрать все queued/processing/failed вложения"
|
||||
)
|
||||
op.drop_index("ix_attachment_jobs_lease", table_name="attachment_jobs")
|
||||
op.drop_index("ix_attachment_jobs_due", table_name="attachment_jobs")
|
||||
op.drop_table("attachment_jobs")
|
||||
@@ -58,5 +107,7 @@ def downgrade() -> None:
|
||||
op.drop_column("attachments", "thumbnail_key")
|
||||
op.drop_column("attachments", "error_code")
|
||||
op.drop_constraint(op.f("ck_attachments_status"), "attachments", type_="check")
|
||||
op.create_check_constraint(op.f("ck_attachments_status"), "attachments", "status = 'ready'")
|
||||
op.create_check_constraint(
|
||||
op.f("ck_attachments_status"), "attachments", "status = 'ready'"
|
||||
)
|
||||
op.alter_column("attachments", "status", server_default="ready")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Уровень 4: ключи crop/WebP и дообработка старых ready-вложений."""
|
||||
"""Ключи crop/WebP и дообработка старых ready-вложений."""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
@@ -11,7 +11,9 @@ depends_on = None
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("attachments", sa.Column("crop_key", sa.String(128), nullable=True))
|
||||
op.add_column("attachments", sa.Column("optimized_key", sa.String(128), nullable=True))
|
||||
op.add_column(
|
||||
"attachments", sa.Column("optimized_key", sa.String(128), nullable=True)
|
||||
)
|
||||
# Старый staging сменяется надёжным ready-оригиналом, но не теряется из журнала cleanup.
|
||||
op.execute("""
|
||||
INSERT INTO upload_intents (id, object_key)
|
||||
@@ -37,7 +39,11 @@ def upgrade() -> None:
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
active = op.get_bind().scalar(sa.text("SELECT count(*) FROM attachments WHERE status IN ('queued', 'processing')"))
|
||||
active = op.get_bind().scalar(
|
||||
sa.text(
|
||||
"SELECT count(*) FROM attachments WHERE status IN ('queued', 'processing')"
|
||||
)
|
||||
)
|
||||
if active:
|
||||
raise RuntimeError("Перед downgrade необходимо завершить активные задания")
|
||||
op.execute("""
|
||||
|
||||
@@ -10,19 +10,36 @@ depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("attachment_jobs", sa.Column("cycle_start_attempt", sa.Integer(), nullable=False, server_default="0"))
|
||||
op.add_column("attachment_jobs", sa.Column("attempt_limit", sa.Integer(), nullable=True))
|
||||
op.add_column("attachment_jobs", sa.Column("last_error_permanent", sa.Boolean(), nullable=True))
|
||||
op.add_column(
|
||||
"attachment_jobs",
|
||||
sa.Column(
|
||||
"cycle_start_attempt", sa.Integer(), nullable=False, server_default="0"
|
||||
),
|
||||
)
|
||||
op.add_column(
|
||||
"attachment_jobs", sa.Column("attempt_limit", sa.Integer(), nullable=True)
|
||||
)
|
||||
op.add_column(
|
||||
"attachment_jobs",
|
||||
sa.Column("last_error_permanent", sa.Boolean(), nullable=True),
|
||||
)
|
||||
op.create_table(
|
||||
"job_replays",
|
||||
sa.Column("id", sa.Uuid(), primary_key=True),
|
||||
sa.Column("job_id", sa.Uuid(), sa.ForeignKey("attachment_jobs.id"), nullable=False),
|
||||
sa.Column(
|
||||
"job_id", sa.Uuid(), sa.ForeignKey("attachment_jobs.id"), nullable=False
|
||||
),
|
||||
sa.Column("actor", sa.String(64), nullable=False),
|
||||
sa.Column("reason", sa.String(32), nullable=False),
|
||||
sa.Column("previous_attempt", sa.Integer(), nullable=False),
|
||||
sa.Column("attempt_limit", sa.Integer(), nullable=False),
|
||||
sa.Column("previous_error_code", sa.String(64), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.clock_timestamp()),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
nullable=False,
|
||||
server_default=sa.func.clock_timestamp(),
|
||||
),
|
||||
)
|
||||
op.create_index("ix_job_replays_job_id", "job_replays", ["job_id"])
|
||||
|
||||
|
||||
+56
-32
@@ -1,5 +1,6 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline structural checks; full schema validation is a separate target."""
|
||||
|
||||
import ast
|
||||
import json
|
||||
from pathlib import Path
|
||||
@@ -7,48 +8,71 @@ import re
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
lab = json.loads((ROOT/'lab.json').read_text())['number']
|
||||
spec = json.loads((ROOT/'contracts/openapi.json').read_text())
|
||||
assert spec['openapi']=='3.1.0'
|
||||
assert spec['info']['version']=='1.%d.0'%lab
|
||||
lab = json.loads((ROOT / "lab.json").read_text())["number"]
|
||||
spec = json.loads((ROOT / "contracts/openapi.json").read_text())
|
||||
assert spec["openapi"] == "3.1.0"
|
||||
assert spec["info"]["version"] == "1.%d.0" % lab
|
||||
operation_ids = set()
|
||||
|
||||
def walk(value):
|
||||
if isinstance(value,dict):
|
||||
if '$ref' in value:
|
||||
pointer = value['$ref']
|
||||
assert pointer.startswith('#/'), 'unexpected external reference'
|
||||
if isinstance(value, dict):
|
||||
if "$ref" in value:
|
||||
pointer = value["$ref"]
|
||||
assert pointer.startswith("#/"), "unexpected external reference"
|
||||
target = spec
|
||||
for part in pointer[2:].split('/'):
|
||||
target = target[part.replace('~1','/').replace('~0','~')]
|
||||
for part in pointer[2:].split("/"):
|
||||
target = target[part.replace("~1", "/").replace("~0", "~")]
|
||||
for v in value.values():
|
||||
walk(v)
|
||||
elif isinstance(value,list):
|
||||
elif isinstance(value, list):
|
||||
for v in value:
|
||||
walk(v)
|
||||
|
||||
walk(spec)
|
||||
for route,methods in spec['paths'].items():
|
||||
placeholders = set(re.findall(r'\{([^}]+)\}',route))
|
||||
for method,op in methods.items():
|
||||
assert op['operationId'] not in operation_ids, 'duplicate operationId'
|
||||
operation_ids.add(op['operationId'])
|
||||
params = {p['name'] for p in op.get('parameters',[]) if p['in']=='path' and p.get('required')}
|
||||
assert placeholders==params, 'path parameter mismatch: '+route
|
||||
for response in op['responses'].values():
|
||||
assert 'X-Request-Id' in response['headers']
|
||||
if lab>=3:
|
||||
assert 'X-Instance-Id' in response['headers']
|
||||
assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2)
|
||||
assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4)
|
||||
for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')):
|
||||
ast.parse(file.read_text(),filename=str(file))
|
||||
for file in ROOT.rglob('*.json'):
|
||||
if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts):
|
||||
for route, methods in spec["paths"].items():
|
||||
placeholders = set(re.findall(r"\{([^}]+)\}", route))
|
||||
for method, op in methods.items():
|
||||
assert op["operationId"] not in operation_ids, "duplicate operationId"
|
||||
operation_ids.add(op["operationId"])
|
||||
params = {
|
||||
p["name"]
|
||||
for p in op.get("parameters", [])
|
||||
if p["in"] == "path" and p.get("required")
|
||||
}
|
||||
assert placeholders == params, "path parameter mismatch: " + route
|
||||
for response in op["responses"].values():
|
||||
assert "X-Request-Id" in response["headers"]
|
||||
if lab >= 3:
|
||||
assert "X-Instance-Id" in response["headers"]
|
||||
assert ("/api/v1/auth/sessions" in spec["paths"]) == (lab >= 2)
|
||||
assert ("/api/v1/attachments/{attachment_id}" in spec["paths"]) == (lab >= 4)
|
||||
for file in list((ROOT / "tests").glob("*.py")) + list(
|
||||
(ROOT / "scripts").glob("*.py")
|
||||
):
|
||||
ast.parse(file.read_text(), filename=str(file))
|
||||
for file in ROOT.rglob("*.json"):
|
||||
if any(
|
||||
part in {".git", ".venv", "node_modules", "vendor", "output"}
|
||||
for part in file.parts
|
||||
):
|
||||
continue
|
||||
json.loads(file.read_text())
|
||||
for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'):
|
||||
assert (ROOT/required).is_file(), 'missing '+required
|
||||
print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.')
|
||||
for required in (
|
||||
"README.md",
|
||||
"COURSE.md",
|
||||
"CONTRIBUTING.md",
|
||||
"REPORT.md",
|
||||
"contracts/README.md",
|
||||
"tests/smoke.py",
|
||||
"tests/README.md",
|
||||
):
|
||||
assert (ROOT / required).is_file(), "missing " + required
|
||||
print(
|
||||
"PASS: offline skeleton structure, local refs and Python syntax; application NOT tested."
|
||||
)
|
||||
|
||||
if __name__=='__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,355 +0,0 @@
|
||||
"""Проверяет инфраструктуру, SIGTERM и обновление реального стенда."""
|
||||
|
||||
import asyncio
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from threading import Event
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
import asyncpg
|
||||
|
||||
from scripts.deployment import ComposeProject, ROOT, deployment_lock
|
||||
from scripts.failover_all import exercise, failure_kind, history
|
||||
from scripts.rolling_update import update
|
||||
from tests.client import Client, Failure, arguments, check, run
|
||||
|
||||
PROBE = """import json, sys, urllib.request, urllib.error
|
||||
payload = json.load(sys.stdin)
|
||||
results = []
|
||||
for item in payload:
|
||||
data = json.dumps(item['body']).encode() if 'body' in item else None
|
||||
request = urllib.request.Request(item['url'], data=data, headers=item.get('headers', {}), method=item.get('method', 'GET'))
|
||||
try:
|
||||
response = urllib.request.urlopen(request, timeout=7)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
results.append({'status': response.status, 'body': json.loads(response.read())})
|
||||
print(json.dumps(results))
|
||||
"""
|
||||
|
||||
|
||||
def probe(project, runner, requests):
|
||||
"""Обращается к внутреннему API, передавая токен только через stdin."""
|
||||
result = subprocess.run(
|
||||
["docker", "exec", "-i", runner, "python", "-c", PROBE],
|
||||
input=json.dumps(requests),
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=10,
|
||||
)
|
||||
check(result.returncode == 0, "internal HTTP probe failed")
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def audit(project):
|
||||
"""Проверяет фактические лимиты, порты и область доступа к секретам."""
|
||||
allowed = {
|
||||
"postgres": {"db_password"},
|
||||
"redis": {"redis_password"},
|
||||
"migrate": {"db_password"},
|
||||
"api": {"db_password", "redis_password", "s3_access_key_id", "s3_secret_access_key"},
|
||||
"minio": {"minio_root_user", "minio_root_password"},
|
||||
"minio-bootstrap": {"minio_root_user", "minio_root_password", "s3_access_key_id", "s3_secret_access_key"},
|
||||
"cleanup": {"db_password", "s3_access_key_id", "s3_secret_access_key"},
|
||||
"nginx": set(),
|
||||
}
|
||||
ids = project.run("ps", "--all", "--quiet").splitlines()
|
||||
containers = json.loads(project.docker("inspect", *ids))
|
||||
for item in containers:
|
||||
service = item["Config"]["Labels"]["com.docker.compose.service"]
|
||||
check(service in allowed, "unexpected service")
|
||||
host = item["HostConfig"]
|
||||
check(
|
||||
host["Memory"] > 0 and host["NanoCpus"] > 0,
|
||||
service + ": missing CPU/RAM limit",
|
||||
)
|
||||
env_names = {entry.split("=", 1)[0] for entry in item["Config"]["Env"]}
|
||||
check(
|
||||
not env_names
|
||||
& {
|
||||
"DB_PASSWORD",
|
||||
"REDIS_PASSWORD",
|
||||
"POSTGRES_PASSWORD",
|
||||
"REDISCLI_AUTH",
|
||||
"DATABASE_URL",
|
||||
"MINIO_ROOT_USER", "MINIO_ROOT_PASSWORD", "S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY",
|
||||
},
|
||||
service + ": password in environment",
|
||||
)
|
||||
secrets = {
|
||||
Path(mount["Destination"]).name
|
||||
for mount in item["Mounts"]
|
||||
if mount["Destination"].startswith("/run/secrets/")
|
||||
}
|
||||
check(secrets == allowed[service], service + ": incorrect secret scope")
|
||||
if service in {"api", "minio"}:
|
||||
check(not host["PortBindings"], service + " publishes ports")
|
||||
for mount in item["Mounts"]:
|
||||
if mount["Destination"].startswith("/run/secrets/"):
|
||||
check(not mount["RW"], "writable secret mount")
|
||||
check(
|
||||
"container_name" not in project.config["services"][service],
|
||||
"fixed container name",
|
||||
)
|
||||
check(
|
||||
len(containers) == len(allowed) - 1 + len(project.replicas()),
|
||||
"unexpected container count",
|
||||
)
|
||||
print(
|
||||
"PASS infrastructure: CPU/RAM, private API ports, scoped read-only file secrets, no environment passwords",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
async def graceful(project, base_url):
|
||||
"""Удерживает реальный POST в БД и завершает его после SIGTERM."""
|
||||
replicas = project.replicas()
|
||||
target, runner = replicas[:2]
|
||||
client = Client(base_url)
|
||||
actor, _, _, chat = await asyncio.to_thread(client.bootstrap)
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
key = uuid4().hex
|
||||
raw = json.dumps([actor["id"], "POST", path, key]).encode()
|
||||
lock_id = int.from_bytes(hashlib.sha256(raw).digest()[:8], signed=True)
|
||||
database = project.config["services"]["postgres"]
|
||||
env = database["environment"]
|
||||
conn = await asyncpg.connect(
|
||||
host="127.0.0.1",
|
||||
port=int(database["ports"][0]["published"]),
|
||||
database=env["POSTGRES_DB"],
|
||||
user=env["POSTGRES_USER"],
|
||||
password=(ROOT / "secrets/db_password").read_text().strip(),
|
||||
timeout=3,
|
||||
)
|
||||
network = project.config['networks']['default']['name']
|
||||
address_template = '{{with index .NetworkSettings.Networks ' + json.dumps(network) + '}}{{.IPAddress}}{{end}}'
|
||||
address = project.docker(
|
||||
"inspect",
|
||||
"--format",
|
||||
address_template,
|
||||
target.id,
|
||||
)
|
||||
check(bool(address), 'API has no address in the application network')
|
||||
port = project.config["services"]["api"]["environment"]["APP_PORT"]
|
||||
direct = f"http://{address}:{port}"
|
||||
started = time.monotonic()
|
||||
task = None
|
||||
try:
|
||||
async with conn.transaction():
|
||||
await conn.execute("SELECT pg_advisory_xact_lock($1)", lock_id)
|
||||
task = asyncio.create_task(
|
||||
asyncio.to_thread(
|
||||
probe,
|
||||
project,
|
||||
runner.id,
|
||||
[
|
||||
{
|
||||
"url": direct + path,
|
||||
"method": "POST",
|
||||
"body": {"text": "graceful-" + key},
|
||||
"headers": {
|
||||
"Authorization": "Bearer " + actor["token"],
|
||||
"Idempotency-Key": key,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
],
|
||||
)
|
||||
)
|
||||
deadline = time.monotonic() + 3
|
||||
while not await conn.fetchval(
|
||||
"SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE wait_event = 'advisory' AND datname = current_database())"
|
||||
):
|
||||
check(time.monotonic() < deadline, "POST did not reach database lock")
|
||||
await asyncio.sleep(0.02)
|
||||
started = time.monotonic()
|
||||
await asyncio.to_thread(
|
||||
project.docker, "kill", "--signal", "SIGTERM", target.id
|
||||
)
|
||||
results = await asyncio.to_thread(
|
||||
probe,
|
||||
project,
|
||||
runner.id,
|
||||
[
|
||||
{"url": direct + "/health/ready"},
|
||||
{"url": direct + "/health/live"},
|
||||
{"url": direct + "/api/v1/users/me"},
|
||||
],
|
||||
)
|
||||
check(
|
||||
[item["status"] for item in results] == [503, 200, 503],
|
||||
"incorrect drain readiness/liveness/new work",
|
||||
)
|
||||
await asyncio.sleep(max(0, 1.2 - (time.monotonic() - started)))
|
||||
result = (await task)[0]
|
||||
check(result["status"] == 201, "in-flight POST failed during SIGTERM")
|
||||
await asyncio.to_thread(project.docker, "wait", target.id, timeout=10)
|
||||
state = json.loads(
|
||||
project.docker("inspect", "--format", "{{json .State}}", target.id)
|
||||
)
|
||||
check(
|
||||
not state["OOMKilled"] and state["ExitCode"] != 137,
|
||||
"forced shutdown instead of graceful completion",
|
||||
)
|
||||
check(time.monotonic() - started < 8, "shutdown exceeded Docker grace budget")
|
||||
items = await asyncio.to_thread(history, client, actor, chat)
|
||||
check(
|
||||
result["body"]["id"] in {item["id"] for item in items},
|
||||
"acknowledged in-flight message lost",
|
||||
)
|
||||
print(
|
||||
f"PASS SIGTERM: readiness 503, live 200, new work 503, in-flight POST 201; exit in {time.monotonic() - started:.3f}s",
|
||||
flush=True,
|
||||
)
|
||||
finally:
|
||||
await conn.close()
|
||||
if task:
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
if any(item.id == target.id and item.running for item in project.replicas()):
|
||||
await asyncio.to_thread(project.docker, "stop", target.id)
|
||||
await asyncio.to_thread(project.docker, "start", target.id)
|
||||
await asyncio.to_thread(project.wait_healthy, {item.id for item in replicas})
|
||||
await asyncio.to_thread(project.wait_routed, target.instance_id, base_url)
|
||||
|
||||
|
||||
class ObservedProject(ComposeProject):
|
||||
"""Подсчитывает миграции и проверяет готовность перед заменой."""
|
||||
|
||||
def __init__(self):
|
||||
self.migrations = 0
|
||||
self.replacements = 0
|
||||
self.replacement_started = []
|
||||
super().__init__()
|
||||
|
||||
def run(self, *args, **kwargs):
|
||||
if args[:6] == ("run", "--rm", "--no-deps", "--pull", "never", "migrate"):
|
||||
self.migrations += 1
|
||||
return super().run(*args, **kwargs)
|
||||
|
||||
def docker(self, *args, **kwargs):
|
||||
if args[0] == "stop":
|
||||
healthy = [
|
||||
item
|
||||
for item in self.replicas()
|
||||
if item.id != args[1] and item.running and item.health == "healthy"
|
||||
]
|
||||
check(len(healthy) >= 2, "rolling update reduces healthy capacity")
|
||||
self.replacements += 1
|
||||
self.replacement_started.append(time.monotonic())
|
||||
return super().docker(*args, **kwargs)
|
||||
|
||||
|
||||
def rolling(base_url):
|
||||
"""Заменяет образ под постоянной записью с проверкой сохранности."""
|
||||
project = ObservedProject()
|
||||
before = project.replicas()
|
||||
client = Client(base_url)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
stop = Event()
|
||||
results, errors = [], []
|
||||
|
||||
def worker():
|
||||
local = Client(base_url, timeout=2)
|
||||
key = uuid4().hex
|
||||
while not stop.is_set():
|
||||
started = time.monotonic()
|
||||
try:
|
||||
result = local.message(actor, chat, "rolling-" + key, key=key)
|
||||
results.append(
|
||||
(started, time.monotonic(), result["json"]["id"], result["elapsed"])
|
||||
)
|
||||
key = uuid4().hex
|
||||
except Failure as error:
|
||||
errors.append(failure_kind(error))
|
||||
stop.wait(0.08)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
jobs = [pool.submit(worker) for _ in range(2)]
|
||||
try:
|
||||
time.sleep(1)
|
||||
started = time.monotonic()
|
||||
update(project, base_url, revision="verification-" + uuid4().hex[:12])
|
||||
finished = time.monotonic()
|
||||
time.sleep(1)
|
||||
finally:
|
||||
stop.set()
|
||||
for job in jobs:
|
||||
job.result(timeout=5)
|
||||
after = project.replicas()
|
||||
check(
|
||||
project.migrations == 1 and project.replacements == len(before),
|
||||
"migration/replacement count incorrect",
|
||||
)
|
||||
check(
|
||||
{item.image for item in before}.isdisjoint({item.image for item in after}),
|
||||
"new image was not deployed",
|
||||
)
|
||||
check(
|
||||
{item.id for item in before}.isdisjoint({item.id for item in after}),
|
||||
"old containers remain",
|
||||
)
|
||||
writes = [row for row in results if started <= row[0] <= finished]
|
||||
check(bool(writes), "no writes during update")
|
||||
check(
|
||||
any(project.replacement_started[0] <= row[0] <= finished for row in writes),
|
||||
"no writes during container replacement",
|
||||
)
|
||||
items = history(client, actor, chat)
|
||||
check(
|
||||
{row[2] for row in results} <= {item["id"] for item in items},
|
||||
"rolling update lost confirmed messages",
|
||||
)
|
||||
check(
|
||||
len(items) == len({item["text"] for item in items}),
|
||||
"rolling update created duplicate messages",
|
||||
)
|
||||
latencies = sorted(row[3] for row in writes)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"scenario": "rolling update",
|
||||
"replacements": project.replacements,
|
||||
"migration_runs": project.migrations,
|
||||
"successful_writes": len(writes),
|
||||
"failed_attempts": len(errors),
|
||||
"errors_by_kind": dict(Counter(errors)),
|
||||
"elapsed_seconds": round(finished - started, 3),
|
||||
"successful_rps": round(len(writes) / (finished - started), 3),
|
||||
"p95_seconds": round(
|
||||
latencies[min(len(latencies) - 1, int(len(latencies) * 0.95))], 3
|
||||
),
|
||||
}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
"""Выполняет проверки только на отдельном тестовом проекте."""
|
||||
|
||||
def configure(parser):
|
||||
parser.add_argument(
|
||||
"--phase", choices=("all", "update-and-failover"), default="all"
|
||||
)
|
||||
|
||||
args = arguments("Grade 4 integration checks", configure)
|
||||
project = ComposeProject()
|
||||
check(project.name.endswith("-test"), "use isolated test Compose project")
|
||||
with deployment_lock(project):
|
||||
audit(project)
|
||||
if args.phase == "all":
|
||||
asyncio.run(graceful(project, args.base_url))
|
||||
rolling(args.base_url)
|
||||
args.duration, args.concurrency = 10, 2
|
||||
exercise(project, args)
|
||||
audit(project)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -1,39 +0,0 @@
|
||||
"""Проверяет конкурентные повторы через балансировщик."""
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from uuid import uuid4
|
||||
|
||||
from tests.client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Отправляет один ключ параллельно через разные реплики."""
|
||||
args = arguments("Concurrent idempotency through load balancer")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
key = uuid4().hex
|
||||
body = "parallel-" + key
|
||||
|
||||
def send(_):
|
||||
return Client(args.base_url, args.ca_file).message(alice, chat, body, key=key)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
results = list(pool.map(send, range(24)))
|
||||
ids = {result["json"]["id"] for result in results}
|
||||
replicas = {result["headers"]["X-Instance-Id"] for result in results}
|
||||
check(len(ids) == 1, "parallel retries created duplicate messages")
|
||||
check(len(replicas) >= 2, "parallel retries did not reach two API replicas")
|
||||
history = client.call(
|
||||
"GET",
|
||||
f"/api/v1/chats/{chat['id']}/messages?limit=100",
|
||||
actor=alice,
|
||||
schema="MessagePage",
|
||||
)["json"]["items"]
|
||||
check(
|
||||
len(history) == 1 and history[0] == results[0]["json"], "history has duplicates"
|
||||
)
|
||||
print(f"PASS: 24 concurrent replays, {len(replicas)} replicas, one message")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,429 @@
|
||||
"""Fault/recovery очереди на явно выбранном Compose-стенде; только синтетические данные."""
|
||||
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
from io import BytesIO
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from scripts.check_outbox_recovery import COMPOSE, ROOT, compose, require_compose
|
||||
from scripts.deployment import ComposeProject
|
||||
from tests.client import Client, check
|
||||
|
||||
PROBE = """
|
||||
import asyncio, hashlib, json
|
||||
from uuid import UUID
|
||||
from sqlalchemy import select
|
||||
from app.core.config import Settings
|
||||
from app.core.database import create_db_engine, create_session_factory
|
||||
from app.models.job import AttachmentJob
|
||||
from app.models.attachment import Attachment
|
||||
from app.storage.s3 import create_s3_storage
|
||||
async def main():
|
||||
settings=Settings(); engine=create_db_engine(settings); storage=create_s3_storage(settings.s3)
|
||||
try:
|
||||
async with create_session_factory(engine)() as session:
|
||||
job, att=(await session.execute(select(AttachmentJob,Attachment).join(Attachment,Attachment.id==AttachmentJob.attachment_id).where(Attachment.id==UUID(ATTACHMENT_ID)))).one()
|
||||
result=dict(job_id=str(job.id),status=att.status,attempt=job.attempt,published_attempt=job.published_attempt,limit=job.attempt_limit,updated_at=att.updated_at,next_attempt_at=job.next_attempt_at,last_error_code=job.last_error_code,permanent=job.last_error_permanent)
|
||||
objects=[]
|
||||
for prefix in ('originals/'+UUID(ATTACHMENT_ID).hex+'/', 'variants/'+UUID(ATTACHMENT_ID).hex+'/'):
|
||||
entries=await asyncio.to_thread(lambda: list(storage._client.list_objects(storage.settings.bucket,prefix=prefix,recursive=True)))
|
||||
for obj in entries:
|
||||
stream=await storage.open_object(obj.object_name); checksum=hashlib.sha256()
|
||||
try:
|
||||
async for chunk in stream: checksum.update(chunk)
|
||||
finally: await stream.aclose()
|
||||
objects.append(dict(name=obj.object_name.split('/')[-1],size=obj.size,sha256=checksum.hexdigest(),last_modified=obj.last_modified))
|
||||
result['objects']=sorted(objects,key=lambda x:x['name']);print(json.dumps(result,default=str))
|
||||
finally: await storage.aclose();await engine.dispose()
|
||||
asyncio.run(main())
|
||||
"""
|
||||
|
||||
|
||||
def probe(attachment_id):
|
||||
code = "ATTACHMENT_ID = " + repr(str(UUID(attachment_id))) + "\n" + PROBE
|
||||
result = subprocess.run(
|
||||
COMPOSE + ["exec", "-T", "api", "python", "-"],
|
||||
input=code,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
cwd=ROOT,
|
||||
timeout=30,
|
||||
)
|
||||
check(result.returncode == 0, "Probe failed; diagnostic output hidden")
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def admin(*arguments, expected=0):
|
||||
result = compose(
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"worker",
|
||||
"python",
|
||||
"-m",
|
||||
"app.core.job_admin",
|
||||
*arguments
|
||||
)
|
||||
check(result.returncode == expected, "Unexpected operator command exit status")
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def verify_result(client, actor, attachment, original):
|
||||
ready = client.wait_ready(actor, attachment, wait_seconds=180)
|
||||
check(ready["id"] == attachment["id"], "Attachment identity changed")
|
||||
path = "/api/v1/attachments/" + ready["id"] + "/content"
|
||||
check(
|
||||
client.call("GET", path, actor=actor)["bytes"] == original, "Original changed"
|
||||
)
|
||||
check(
|
||||
{v["name"] for v in ready["variants"]} == {"thumbnail", "crop", "optimized"},
|
||||
"Incomplete pipeline",
|
||||
)
|
||||
for variant in ready["variants"]:
|
||||
data = client.call("GET", path + "?variant=" + variant["name"], actor=actor)[
|
||||
"bytes"
|
||||
]
|
||||
check(
|
||||
hashlib.sha256(data).hexdigest() == variant["sha256"], "Checksum mismatch"
|
||||
)
|
||||
with Image.open(BytesIO(data)) as image:
|
||||
check(
|
||||
image.size == (variant["width"], variant["height"]),
|
||||
"Metadata dimensions mismatch",
|
||||
)
|
||||
check(
|
||||
image.format == ("WEBP" if variant["name"] == "optimized" else "JPEG"),
|
||||
"Wrong format",
|
||||
)
|
||||
check(
|
||||
not image.getexif()
|
||||
and not image.info.get("icc_profile")
|
||||
and not image.info.get("xmp"),
|
||||
"Metadata leaked",
|
||||
)
|
||||
if variant["name"] == "crop":
|
||||
check(image.size == (128, 128), "Wrong crop size")
|
||||
snapshot = probe(ready["id"])
|
||||
check(
|
||||
len(snapshot["objects"]) == 4,
|
||||
"Expected exactly one original and three variants",
|
||||
)
|
||||
return snapshot
|
||||
|
||||
|
||||
def crash(client, actor, chat, mode):
|
||||
name = "messenger-worker-fault-" + uuid4().hex
|
||||
try:
|
||||
require_compose("stop", "worker")
|
||||
attachment, original = client.attachment(actor, chat)
|
||||
result = compose(
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"--name",
|
||||
name,
|
||||
"worker",
|
||||
"python",
|
||||
"-m",
|
||||
"app.core.job_worker",
|
||||
"--" + mode,
|
||||
attachment["id"],
|
||||
)
|
||||
phase = (
|
||||
"after_object:optimized" if mode == "crash-after-object" else "before_ack"
|
||||
)
|
||||
marker = json.dumps({"fault": phase, "attachment_id": attachment["id"]})
|
||||
check(
|
||||
result.returncode == 137 and marker in result.stdout,
|
||||
"Targeted crash not observed",
|
||||
)
|
||||
before = probe(attachment["id"])
|
||||
check(
|
||||
before["status"]
|
||||
== ("processing" if mode == "crash-after-object" else "ready"),
|
||||
"Unexpected crash state",
|
||||
)
|
||||
check(len(before["objects"]) == 4, "Crash must occur after all four PUTs")
|
||||
finally:
|
||||
subprocess.run(["docker", "rm", "-f", name], capture_output=True, timeout=30)
|
||||
require_compose("start", "worker")
|
||||
after = verify_result(client, actor, attachment, original)
|
||||
if mode == "crash-before-ack":
|
||||
# Wait for RabbitMQ to deliver and acknowledge the ready duplicate.
|
||||
wait_queue_empty()
|
||||
after = probe(attachment["id"])
|
||||
check(after == before, "Ready duplicate rewrote result")
|
||||
else:
|
||||
check(
|
||||
after["attempt"] == before["attempt"] + 1,
|
||||
"Lease did not recover the interrupted attempt",
|
||||
)
|
||||
check(
|
||||
[(x["name"], x["sha256"]) for x in before["objects"]]
|
||||
== [(x["name"], x["sha256"]) for x in after["objects"]],
|
||||
"Replay changed object content",
|
||||
)
|
||||
return dict(
|
||||
scenario=mode,
|
||||
attachment_id=attachment["id"],
|
||||
exit_code=137,
|
||||
before=before,
|
||||
after=after,
|
||||
)
|
||||
|
||||
|
||||
def retry_replay(client, actor, chat, permanent):
|
||||
name = "messenger-retry-fault-" + uuid4().hex
|
||||
samples = []
|
||||
configuration = ComposeProject().config["services"]["worker"]["environment"]
|
||||
retry_base = float(configuration["JOB_RETRY_SECONDS"])
|
||||
retry_max = float(configuration["JOB_RETRY_MAX_SECONDS"])
|
||||
try:
|
||||
require_compose("stop", "worker")
|
||||
attachment, original = client.attachment(actor, chat)
|
||||
mode = "fail-permanent" if permanent else "fail-transient"
|
||||
require_compose(
|
||||
"run",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"--name",
|
||||
name,
|
||||
"worker",
|
||||
"python",
|
||||
"-m",
|
||||
"app.core.job_worker",
|
||||
"--" + mode,
|
||||
attachment["id"],
|
||||
)
|
||||
deadline = time.monotonic() + 180
|
||||
while time.monotonic() < deadline:
|
||||
sample = probe(attachment["id"])
|
||||
if (
|
||||
sample["attempt"]
|
||||
and sample["status"] in {"queued", "failed"}
|
||||
and (not samples or samples[-1]["attempt"] != sample["attempt"])
|
||||
):
|
||||
samples.append(sample)
|
||||
if sample["status"] == "failed":
|
||||
break
|
||||
time.sleep(0.5)
|
||||
check(sample["status"] == "failed", "Retry never reached failed")
|
||||
check(
|
||||
sample["attempt"] == (1 if permanent else sample["limit"]),
|
||||
"Incorrect attempt budget",
|
||||
)
|
||||
check(sample["permanent"] == permanent, "Incorrect error classification")
|
||||
if not permanent:
|
||||
check(len(samples) == sample["limit"], "Missed retry samples")
|
||||
for entry in samples:
|
||||
delay = (
|
||||
datetime.fromisoformat(entry["next_attempt_at"])
|
||||
- datetime.fromisoformat(entry["updated_at"])
|
||||
).total_seconds()
|
||||
ceiling = min(retry_max, retry_base * 2 ** (entry["attempt"] - 1))
|
||||
check(
|
||||
ceiling / 2 <= delay <= ceiling,
|
||||
"Retry delay outside configured jitter bounds",
|
||||
)
|
||||
client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + attachment["id"] + "/content",
|
||||
actor=actor,
|
||||
expected=409,
|
||||
)
|
||||
job_id = sample["job_id"]
|
||||
request_id = str(uuid4())
|
||||
listing = admin("list-failed")
|
||||
check(
|
||||
any(row["job_id"] == job_id for row in listing),
|
||||
"Job missing from failed registry",
|
||||
)
|
||||
subprocess.run(
|
||||
["docker", "rm", "-f", name], capture_output=True, timeout=30, check=True
|
||||
)
|
||||
first = admin(
|
||||
"replay",
|
||||
job_id,
|
||||
"--request-id",
|
||||
request_id,
|
||||
"--actor",
|
||||
"verification",
|
||||
"--reason",
|
||||
"dependency_restored",
|
||||
)
|
||||
check(first["status"] == "queued", "Replay did not queue job")
|
||||
finally:
|
||||
subprocess.run(["docker", "rm", "-f", name], capture_output=True, timeout=30)
|
||||
require_compose("start", "worker")
|
||||
after = verify_result(client, actor, attachment, original)
|
||||
repeat = admin(
|
||||
"replay",
|
||||
job_id,
|
||||
"--request-id",
|
||||
request_id,
|
||||
"--actor",
|
||||
"verification",
|
||||
"--reason",
|
||||
"dependency_restored",
|
||||
)
|
||||
check(repeat["already_applied"], "Replay request id not idempotent")
|
||||
refused = admin(
|
||||
"replay",
|
||||
job_id,
|
||||
"--request-id",
|
||||
str(uuid4()),
|
||||
"--actor",
|
||||
"verification",
|
||||
"--reason",
|
||||
"manual_review",
|
||||
expected=2,
|
||||
)
|
||||
check(refused["error_code"] == "job_not_failed", "Successful job was replayed")
|
||||
check(probe(attachment["id"]) == after, "Operator replay altered ready job")
|
||||
check(len(admin("history", job_id)) == 1, "Incorrect audit count")
|
||||
return dict(
|
||||
scenario=mode,
|
||||
attachment_id=attachment["id"],
|
||||
samples=samples,
|
||||
after=after,
|
||||
replay_idempotent=True,
|
||||
)
|
||||
|
||||
|
||||
def queue_state():
|
||||
output = require_compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"broker",
|
||||
"rabbitmqctl",
|
||||
"list_queues",
|
||||
"--formatter=json",
|
||||
"name",
|
||||
"messages_ready",
|
||||
"messages_unacknowledged",
|
||||
"consumers",
|
||||
"durable",
|
||||
)
|
||||
return next(row for row in json.loads(output) if row["name"] == "attachment-jobs")
|
||||
|
||||
|
||||
def wait_queue_empty():
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
state = queue_state()
|
||||
if state["messages_ready"] == 0 and state["messages_unacknowledged"] == 0:
|
||||
return state
|
||||
time.sleep(0.5)
|
||||
check(False, "RabbitMQ did not acknowledge all completed deliveries")
|
||||
|
||||
|
||||
def persistence(client, actor, chat):
|
||||
try:
|
||||
require_compose("stop", "worker")
|
||||
attachment, original = client.attachment(actor, chat)
|
||||
client.message(actor, chat, "", attachments=[attachment["id"]])
|
||||
client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + attachment["id"] + "/content",
|
||||
actor=actor,
|
||||
expected=409,
|
||||
)
|
||||
time.sleep(2)
|
||||
queued_before = queue_state()
|
||||
check(
|
||||
queued_before["messages_ready"] >= 1 and queued_before["durable"],
|
||||
"No durable queued message before restart",
|
||||
)
|
||||
result = subprocess.run(
|
||||
[str(ROOT / "scripts/restart.sh")],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
timeout=180,
|
||||
)
|
||||
check(result.returncode == 0, "Restart hook failed")
|
||||
check(
|
||||
"worker"
|
||||
not in require_compose(
|
||||
"ps", "--status", "running", "--services"
|
||||
).splitlines(),
|
||||
"Restart started deliberately stopped worker",
|
||||
)
|
||||
queued_after = queue_state()
|
||||
check(
|
||||
queued_after["messages_ready"] >= 1 and queued_after["durable"],
|
||||
"Broker lost queued delivery across restart",
|
||||
)
|
||||
client.message(actor, chat, "session and chat survived broker/API restart")
|
||||
finally:
|
||||
require_compose("start", "worker")
|
||||
after = verify_result(client, actor, attachment, original)
|
||||
return dict(
|
||||
scenario="worker_stopped_restart_all",
|
||||
attachment_id=attachment["id"],
|
||||
queue_before=queued_before,
|
||||
queue_after=queued_after,
|
||||
after=after,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", required=True)
|
||||
parser.add_argument("--ca-file")
|
||||
parser.add_argument(
|
||||
"--scenario",
|
||||
choices=[
|
||||
"all",
|
||||
"persistence",
|
||||
"crash-after-object",
|
||||
"crash-before-ack",
|
||||
"fail-transient",
|
||||
"fail-permanent",
|
||||
],
|
||||
default="all",
|
||||
)
|
||||
parser.add_argument("--output", default="evidence/jobs.json")
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url, args.ca_file, timeout=40)
|
||||
aliases = {r.instance_id for r in ComposeProject().replicas() if r.running}
|
||||
check(
|
||||
client.call("GET", "/health/live", schema="Health")["headers"].get(
|
||||
"X-Instance-Id"
|
||||
)
|
||||
in aliases,
|
||||
"Wrong Compose project for BASE_URL",
|
||||
)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
results = []
|
||||
operations = {
|
||||
"persistence": persistence,
|
||||
"crash-after-object": lambda *x: crash(*x, "crash-after-object"),
|
||||
"crash-before-ack": lambda *x: crash(*x, "crash-before-ack"),
|
||||
"fail-transient": lambda *x: retry_replay(*x, False),
|
||||
"fail-permanent": lambda *x: retry_replay(*x, True),
|
||||
}
|
||||
selected = (
|
||||
operations.values() if args.scenario == "all" else [operations[args.scenario]]
|
||||
)
|
||||
for operation in selected:
|
||||
result = operation(client, actor, chat)
|
||||
results.append(result)
|
||||
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.output).write_text(
|
||||
json.dumps(dict(status="in_progress", results=results), indent=2) + "\n"
|
||||
)
|
||||
print("PASS: " + result["scenario"], flush=True)
|
||||
Path(args.output).write_text(
|
||||
json.dumps(dict(status="passed", results=results), indent=2) + "\n"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,210 +0,0 @@
|
||||
"""Fault/recovery lab5 на явно выбранном Compose-стенде; только синтетические данные."""
|
||||
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
from io import BytesIO
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from scripts.check_outbox_recovery import COMPOSE, ROOT, compose, require_compose
|
||||
from scripts.deployment import ComposeProject
|
||||
from tests.client import Client, check
|
||||
|
||||
PROBE = '''
|
||||
import asyncio, hashlib, json
|
||||
from uuid import UUID
|
||||
from sqlalchemy import select
|
||||
from app.core.config import Settings
|
||||
from app.core.database import create_db_engine, create_session_factory
|
||||
from app.models.job import AttachmentJob
|
||||
from app.models.attachment import Attachment
|
||||
from app.storage.s3 import create_s3_storage
|
||||
async def main():
|
||||
settings=Settings(); engine=create_db_engine(settings); storage=create_s3_storage(settings.s3)
|
||||
try:
|
||||
async with create_session_factory(engine)() as session:
|
||||
job, att=(await session.execute(select(AttachmentJob,Attachment).join(Attachment,Attachment.id==AttachmentJob.attachment_id).where(Attachment.id==UUID(ATTACHMENT_ID)))).one()
|
||||
result=dict(job_id=str(job.id),status=att.status,attempt=job.attempt,published_attempt=job.published_attempt,limit=job.attempt_limit,updated_at=att.updated_at,next_attempt_at=job.next_attempt_at,last_error_code=job.last_error_code,permanent=job.last_error_permanent)
|
||||
objects=[]
|
||||
for prefix in ('originals/'+UUID(ATTACHMENT_ID).hex+'/', 'variants/'+UUID(ATTACHMENT_ID).hex+'/'):
|
||||
entries=await asyncio.to_thread(lambda: list(storage._client.list_objects(storage.settings.bucket,prefix=prefix,recursive=True)))
|
||||
for obj in entries:
|
||||
stream=await storage.open_object(obj.object_name); checksum=hashlib.sha256()
|
||||
try:
|
||||
async for chunk in stream: checksum.update(chunk)
|
||||
finally: await stream.aclose()
|
||||
objects.append(dict(name=obj.object_name.split('/')[-1],size=obj.size,sha256=checksum.hexdigest(),last_modified=obj.last_modified))
|
||||
result['objects']=sorted(objects,key=lambda x:x['name']);print(json.dumps(result,default=str))
|
||||
finally: await storage.aclose();await engine.dispose()
|
||||
asyncio.run(main())
|
||||
'''
|
||||
|
||||
|
||||
def probe(attachment_id):
|
||||
code = 'ATTACHMENT_ID = ' + repr(str(UUID(attachment_id))) + '\n' + PROBE
|
||||
result = subprocess.run(COMPOSE + ['exec', '-T', 'api', 'python', '-'], input=code, text=True, capture_output=True, cwd=ROOT, timeout=30)
|
||||
check(result.returncode == 0, 'Probe failed; diagnostic output hidden')
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def admin(*arguments, expected=0):
|
||||
result = compose('run', '--rm', '--no-deps', 'worker', 'python', '-m', 'app.core.job_admin', *arguments)
|
||||
check(result.returncode == expected, 'Unexpected operator command exit status')
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def verify_result(client, actor, attachment, original):
|
||||
ready = client.wait_ready(actor, attachment, wait_seconds=180)
|
||||
check(ready['id'] == attachment['id'], 'Attachment identity changed')
|
||||
path = '/api/v1/attachments/' + ready['id'] + '/content'
|
||||
check(client.call('GET', path, actor=actor)['bytes'] == original, 'Original changed')
|
||||
check({v['name'] for v in ready['variants']} == {'thumbnail','crop','optimized'}, 'Incomplete pipeline')
|
||||
for variant in ready['variants']:
|
||||
data = client.call('GET', path+'?variant='+variant['name'], actor=actor)['bytes']
|
||||
check(hashlib.sha256(data).hexdigest() == variant['sha256'], 'Checksum mismatch')
|
||||
with Image.open(BytesIO(data)) as image:
|
||||
check(image.size == (variant['width'],variant['height']), 'Metadata dimensions mismatch')
|
||||
check(image.format == ('WEBP' if variant['name']=='optimized' else 'JPEG'), 'Wrong format')
|
||||
check(not image.getexif() and not image.info.get('icc_profile') and not image.info.get('xmp'), 'Metadata leaked')
|
||||
if variant['name']=='crop':check(image.size==(128,128),'Wrong crop size')
|
||||
snapshot=probe(ready['id'])
|
||||
check(len(snapshot['objects']) == 4, 'Expected exactly one original and three variants')
|
||||
return snapshot
|
||||
|
||||
|
||||
def crash(client, actor, chat, mode):
|
||||
name='lab5-worker-fault-'+uuid4().hex
|
||||
try:
|
||||
require_compose('stop','worker')
|
||||
attachment,original=client.attachment(actor,chat)
|
||||
result=compose('run','--rm','--no-deps','--name',name,'worker','python','-m','app.core.job_worker','--'+mode,attachment['id'])
|
||||
phase='after_object:optimized' if mode=='crash-after-object' else 'before_ack'
|
||||
marker=json.dumps({'fault':phase,'attachment_id':attachment['id']})
|
||||
check(result.returncode==137 and marker in result.stdout,'Targeted crash not observed')
|
||||
before=probe(attachment['id'])
|
||||
check(before['status']==('processing' if mode=='crash-after-object' else 'ready'),'Unexpected crash state')
|
||||
check(len(before['objects'])==4,'Crash must occur after all four PUTs')
|
||||
finally:
|
||||
subprocess.run(['docker','rm','-f',name],capture_output=True,timeout=30)
|
||||
require_compose('start','worker')
|
||||
after=verify_result(client,actor,attachment,original)
|
||||
if mode=='crash-before-ack':
|
||||
# Wait for RabbitMQ to deliver and acknowledge the ready duplicate.
|
||||
wait_queue_empty()
|
||||
after=probe(attachment['id'])
|
||||
check(after==before,'Ready duplicate rewrote result')
|
||||
else:
|
||||
check(after['attempt']==before['attempt']+1,'Lease did not recover the interrupted attempt')
|
||||
check([(x['name'],x['sha256']) for x in before['objects']]==[(x['name'],x['sha256']) for x in after['objects']],'Replay changed object content')
|
||||
return dict(scenario=mode,attachment_id=attachment['id'],exit_code=137,before=before,after=after)
|
||||
|
||||
|
||||
def retry_replay(client,actor,chat,permanent):
|
||||
name='lab5-retry-fault-'+uuid4().hex
|
||||
samples=[]
|
||||
configuration=ComposeProject().config['services']['worker']['environment']
|
||||
retry_base=float(configuration['JOB_RETRY_SECONDS'])
|
||||
retry_max=float(configuration['JOB_RETRY_MAX_SECONDS'])
|
||||
try:
|
||||
require_compose('stop','worker')
|
||||
attachment,original=client.attachment(actor,chat)
|
||||
mode='fail-permanent' if permanent else 'fail-transient'
|
||||
require_compose('run','-d','--no-deps','--name',name,'worker','python','-m','app.core.job_worker','--'+mode,attachment['id'])
|
||||
deadline=time.monotonic()+180
|
||||
while time.monotonic()<deadline:
|
||||
sample=probe(attachment['id'])
|
||||
if sample['attempt'] and sample['status'] in {'queued', 'failed'} and (not samples or samples[-1]['attempt']!=sample['attempt']):samples.append(sample)
|
||||
if sample['status']=='failed':break
|
||||
time.sleep(.5)
|
||||
check(sample['status']=='failed','Retry never reached failed')
|
||||
check(sample['attempt']==(1 if permanent else sample['limit']),'Incorrect attempt budget')
|
||||
check(sample['permanent']==permanent,'Incorrect error classification')
|
||||
if not permanent:
|
||||
check(len(samples)==sample['limit'],'Missed retry samples')
|
||||
for entry in samples:
|
||||
delay=(datetime.fromisoformat(entry['next_attempt_at'])-datetime.fromisoformat(entry['updated_at'])).total_seconds()
|
||||
ceiling=min(retry_max,retry_base*2**(entry['attempt']-1))
|
||||
check(ceiling/2<=delay<=ceiling,'Retry delay outside configured jitter bounds')
|
||||
client.call('GET','/api/v1/attachments/'+attachment['id']+'/content',actor=actor,expected=409)
|
||||
job_id=sample['job_id'];request_id=str(uuid4())
|
||||
listing=admin('list-failed')
|
||||
check(any(row['job_id']==job_id for row in listing),'Job missing from failed registry')
|
||||
subprocess.run(['docker','rm','-f',name],capture_output=True,timeout=30,check=True)
|
||||
first=admin('replay',job_id,'--request-id',request_id,'--actor','verification','--reason','dependency_restored')
|
||||
check(first['status']=='queued','Replay did not queue job')
|
||||
finally:
|
||||
subprocess.run(['docker','rm','-f',name],capture_output=True,timeout=30)
|
||||
require_compose('start','worker')
|
||||
after=verify_result(client,actor,attachment,original)
|
||||
repeat=admin('replay',job_id,'--request-id',request_id,'--actor','verification','--reason','dependency_restored')
|
||||
check(repeat['already_applied'],'Replay request id not idempotent')
|
||||
refused=admin('replay',job_id,'--request-id',str(uuid4()),'--actor','verification','--reason','manual_review',expected=2)
|
||||
check(refused['error_code']=='job_not_failed','Successful job was replayed')
|
||||
check(probe(attachment['id'])==after,'Operator replay altered ready job')
|
||||
check(len(admin('history',job_id))==1,'Incorrect audit count')
|
||||
return dict(scenario=mode,attachment_id=attachment['id'],samples=samples,after=after,replay_idempotent=True)
|
||||
|
||||
|
||||
def queue_state():
|
||||
output=require_compose('exec','-T','broker','rabbitmqctl','list_queues','--formatter=json','name','messages_ready','messages_unacknowledged','consumers','durable')
|
||||
return next(row for row in json.loads(output) if row['name']=='attachment-jobs')
|
||||
|
||||
|
||||
def wait_queue_empty():
|
||||
deadline=time.monotonic()+20
|
||||
while time.monotonic()<deadline:
|
||||
state=queue_state()
|
||||
if state['messages_ready']==0 and state['messages_unacknowledged']==0:
|
||||
return state
|
||||
time.sleep(.5)
|
||||
check(False,'RabbitMQ did not acknowledge all completed deliveries')
|
||||
|
||||
|
||||
def persistence(client,actor,chat):
|
||||
try:
|
||||
require_compose('stop','worker')
|
||||
attachment,original=client.attachment(actor,chat)
|
||||
client.message(actor,chat,'',attachments=[attachment['id']])
|
||||
client.call('GET','/api/v1/attachments/'+attachment['id']+'/content',actor=actor,expected=409)
|
||||
time.sleep(2)
|
||||
queued_before=queue_state()
|
||||
check(queued_before['messages_ready']>=1 and queued_before['durable'], 'No durable queued message before restart')
|
||||
result=subprocess.run([str(ROOT/'scripts/restart.sh')],cwd=ROOT,capture_output=True,timeout=180)
|
||||
check(result.returncode==0,'Restart hook failed')
|
||||
check('worker' not in require_compose('ps','--status','running','--services').splitlines(),'Restart started deliberately stopped worker')
|
||||
queued_after=queue_state()
|
||||
check(queued_after['messages_ready']>=1 and queued_after['durable'], 'Broker lost queued delivery across restart')
|
||||
client.message(actor,chat,'session and chat survived broker/API restart')
|
||||
finally:require_compose('start','worker')
|
||||
after=verify_result(client,actor,attachment,original)
|
||||
return dict(scenario='worker_stopped_restart_all',attachment_id=attachment['id'],queue_before=queued_before,queue_after=queued_after,after=after)
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser()
|
||||
parser.add_argument('--base-url',required=True)
|
||||
parser.add_argument('--scenario',choices=['all','persistence','crash-after-object','crash-before-ack','fail-transient','fail-permanent'],default='all')
|
||||
parser.add_argument('--output',default='evidence/lab5-jobs.json')
|
||||
args=parser.parse_args()
|
||||
client=Client(args.base_url,timeout=40)
|
||||
aliases={r.instance_id for r in ComposeProject().replicas() if r.running}
|
||||
check(client.call('GET','/health/live',schema='Health')['headers'].get('X-Instance-Id') in aliases,'Wrong Compose project for BASE_URL')
|
||||
actor,_,_,chat=client.bootstrap()
|
||||
results=[]
|
||||
operations={'persistence':persistence,'crash-after-object':lambda *x:crash(*x,'crash-after-object'),'crash-before-ack':lambda *x:crash(*x,'crash-before-ack'),'fail-transient':lambda *x:retry_replay(*x,False),'fail-permanent':lambda *x:retry_replay(*x,True)}
|
||||
selected=operations.values() if args.scenario=='all' else [operations[args.scenario]]
|
||||
for operation in selected:
|
||||
result=operation(client,actor,chat);results.append(result)
|
||||
Path(args.output).parent.mkdir(parents=True,exist_ok=True)
|
||||
Path(args.output).write_text(json.dumps(dict(status='in_progress',results=results),indent=2)+'\n')
|
||||
print('PASS: '+result['scenario'],flush=True)
|
||||
Path(args.output).write_text(json.dumps(dict(status='passed',results=results),indent=2)+'\n')
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -25,7 +25,7 @@ def check(condition: bool, message: str) -> None:
|
||||
class Stand:
|
||||
def __init__(self, directory: str) -> None:
|
||||
self.directory = Path(directory)
|
||||
self.project = "mtusi-lab3-nginx-check-" + uuid4().hex[:12]
|
||||
self.project = "messenger-nginx-check-" + uuid4().hex[:12]
|
||||
self.base_url = ""
|
||||
backend = self.directory / "backend.conf"
|
||||
backend.write_text(
|
||||
@@ -246,7 +246,7 @@ def run_checks(stand: Stand) -> None:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
with tempfile.TemporaryDirectory(prefix="mtusi-lab3-nginx-check-") as directory:
|
||||
with tempfile.TemporaryDirectory(prefix="messenger-nginx-check-") as directory:
|
||||
stand = Stand(directory)
|
||||
try:
|
||||
run_checks(stand)
|
||||
@@ -254,7 +254,7 @@ def main() -> None:
|
||||
print(stand.compose("logs", "--no-color", "--tail", "20"), flush=True)
|
||||
raise
|
||||
finally:
|
||||
stand.compose("down", "--remove-orphans", "--timeout", "1")
|
||||
stand.compose("down", "--volumes", "--remove-orphans", "--timeout", "1")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -19,7 +19,13 @@ COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
||||
|
||||
|
||||
def compose(*arguments: str, timeout: int = 90) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(COMPOSE + list(arguments), cwd=ROOT, text=True, capture_output=True, timeout=timeout)
|
||||
return subprocess.run(
|
||||
COMPOSE + list(arguments),
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
def require_compose(*arguments: str) -> str:
|
||||
@@ -29,54 +35,112 @@ def require_compose(*arguments: str) -> str:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Отказ publisher после COMMIT перед RabbitMQ publish")
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Отказ publisher после COMMIT перед RabbitMQ publish"
|
||||
)
|
||||
parser.add_argument("--base-url", required=True)
|
||||
parser.add_argument("--ca-file")
|
||||
args = parser.parse_args()
|
||||
running = set(require_compose("ps", "--status", "running", "--services").splitlines())
|
||||
check({"api", "postgres", "minio", "broker", "publisher", "worker"} <= running, "Start the lab5 stack before this scenario")
|
||||
running = set(
|
||||
require_compose("ps", "--status", "running", "--services").splitlines()
|
||||
)
|
||||
check(
|
||||
{"api", "postgres", "minio", "broker", "publisher", "worker"} <= running,
|
||||
"Start the application stack before this scenario",
|
||||
)
|
||||
client = Client(args.base_url, args.ca_file, timeout=40)
|
||||
project = ComposeProject()
|
||||
aliases = {replica.instance_id for replica in project.replicas() if replica.running}
|
||||
live = client.call("GET", "/health/live", schema="Health")
|
||||
check(live["headers"].get("X-Instance-Id") in aliases, "BASE_URL does not belong to the selected Compose project")
|
||||
check(
|
||||
live["headers"].get("X-Instance-Id") in aliases,
|
||||
"BASE_URL does not belong to the selected Compose project",
|
||||
)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
attachment = None
|
||||
fault_container = "lab5-outbox-fault-" + uuid4().hex
|
||||
fault_container = "messenger-outbox-fault-" + uuid4().hex
|
||||
try:
|
||||
require_compose("stop", "publisher")
|
||||
attachment, original = client.attachment(alice, chat)
|
||||
message = client.message(alice, chat, "", attachments=[attachment["id"]])["json"]
|
||||
client.call("GET", f"/api/v1/attachments/{attachment['id']}/content", expected=409, actor=alice)
|
||||
killed = compose(
|
||||
"run", "--rm", "--no-deps", "--name", fault_container, "publisher", "python", "-m",
|
||||
"app.core.outbox_publisher", "--crash-before-publish", attachment["id"],
|
||||
message = client.message(alice, chat, "", attachments=[attachment["id"]])[
|
||||
"json"
|
||||
]
|
||||
client.call(
|
||||
"GET",
|
||||
f"/api/v1/attachments/{attachment['id']}/content",
|
||||
expected=409,
|
||||
actor=alice,
|
||||
)
|
||||
marker = json.dumps({"fault": "before_publish", "attachment_id": attachment["id"]})
|
||||
check(killed.returncode == 137 and marker in killed.stdout, "Expected targeted SIGKILL before publish was not observed")
|
||||
pending = client.call("GET", f"/api/v1/attachments/{attachment['id']}", actor=alice, schema="Attachment")["json"]
|
||||
killed = compose(
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"--name",
|
||||
fault_container,
|
||||
"publisher",
|
||||
"python",
|
||||
"-m",
|
||||
"app.core.outbox_publisher",
|
||||
"--crash-before-publish",
|
||||
attachment["id"],
|
||||
)
|
||||
marker = json.dumps(
|
||||
{"fault": "before_publish", "attachment_id": attachment["id"]}
|
||||
)
|
||||
check(
|
||||
killed.returncode == 137 and marker in killed.stdout,
|
||||
"Expected targeted SIGKILL before publish was not observed",
|
||||
)
|
||||
pending = client.call(
|
||||
"GET",
|
||||
f"/api/v1/attachments/{attachment['id']}",
|
||||
actor=alice,
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
check(pending["status"] == "queued", "Crash must leave accepted job queued")
|
||||
finally:
|
||||
# Если docker compose run оборвался по timeout, одноразовый контейнер тоже удаляется.
|
||||
try:
|
||||
subprocess.run(["docker", "rm", "-f", fault_container], capture_output=True, timeout=30)
|
||||
subprocess.run(
|
||||
["docker", "rm", "-f", fault_container], capture_output=True, timeout=30
|
||||
)
|
||||
finally:
|
||||
require_compose("start", "publisher")
|
||||
ready = client.wait_ready(alice, attachment, wait_seconds=60)
|
||||
check(ready["id"] == attachment["id"], "Recovered a different attachment")
|
||||
check({variant["name"] for variant in ready["variants"]} == {"thumbnail", "crop", "optimized"}, "Missing required variants")
|
||||
check(
|
||||
{variant["name"] for variant in ready["variants"]}
|
||||
== {"thumbnail", "crop", "optimized"},
|
||||
"Missing required variants",
|
||||
)
|
||||
path = f"/api/v1/attachments/{attachment['id']}/content"
|
||||
check(client.call("GET", path, actor=alice)["bytes"] == original, "Original changed after recovery")
|
||||
check(
|
||||
client.call("GET", path, actor=alice)["bytes"] == original,
|
||||
"Original changed after recovery",
|
||||
)
|
||||
for variant in ready["variants"]:
|
||||
downloaded = client.call("GET", path + "?variant=" + variant["name"], actor=alice)["bytes"]
|
||||
check(len(downloaded) == variant["size_bytes"] and hashlib.sha256(downloaded).hexdigest() == variant["sha256"], "Recovered variant checksum mismatch")
|
||||
print(json.dumps({
|
||||
"scenario": "commit_before_publish", "attachment_id": ready["id"],
|
||||
"message_id": message["id"], "publisher_exit_code": killed.returncode,
|
||||
"status_after_crash": pending["status"], "status_after_restart": ready["status"],
|
||||
"variants": [variant["name"] for variant in ready["variants"]],
|
||||
"reuploaded": False,
|
||||
}))
|
||||
downloaded = client.call(
|
||||
"GET", path + "?variant=" + variant["name"], actor=alice
|
||||
)["bytes"]
|
||||
check(
|
||||
len(downloaded) == variant["size_bytes"]
|
||||
and hashlib.sha256(downloaded).hexdigest() == variant["sha256"],
|
||||
"Recovered variant checksum mismatch",
|
||||
)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"scenario": "commit_before_publish",
|
||||
"attachment_id": ready["id"],
|
||||
"message_id": message["id"],
|
||||
"publisher_exit_code": killed.returncode,
|
||||
"status_after_crash": pending["status"],
|
||||
"status_after_restart": ready["status"],
|
||||
"variants": [variant["name"] for variant in ready["variants"]],
|
||||
"reuploaded": False,
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+63
-48
@@ -1,15 +1,13 @@
|
||||
"""Реальный MinIO: повтор bootstrap, private bucket, ограниченные права и отказ."""
|
||||
|
||||
import json
|
||||
import base64
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from scripts.deployment import ComposeProject
|
||||
from tests.client import Client, arguments, check, run
|
||||
|
||||
PROBE = r'''
|
||||
PROBE = r"""
|
||||
import asyncio, json, sys
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
@@ -64,74 +62,91 @@ async def main():
|
||||
await storage.aclose()
|
||||
await engine.dispose()
|
||||
asyncio.run(main())
|
||||
'''
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--with-outage', action='store_true', help='временно остановить MinIO выбранного проекта')
|
||||
parser.add_argument('--with-faults', action='store_true', help='проверить компенсацию и очистку на реальных S3/БД')
|
||||
args = arguments('MinIO private bucket and failure checks', configure)
|
||||
parser.add_argument(
|
||||
"--with-outage",
|
||||
action="store_true",
|
||||
help="временно остановить MinIO выбранного проекта",
|
||||
)
|
||||
|
||||
args = arguments("MinIO private bucket and failure checks", configure)
|
||||
project = ComposeProject()
|
||||
client = Client(args.base_url, args.ca_file, timeout=40)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
aliases = {replica.instance_id for replica in project.replicas() if replica.running}
|
||||
live = client.call("GET", "/health/live", schema="Health")
|
||||
check(
|
||||
live["headers"].get("X-Instance-Id") in aliases,
|
||||
"BASE_URL does not belong to the selected Compose project",
|
||||
)
|
||||
attachment, original = client.attachment(alice, chat)
|
||||
attachment = client.wait_ready(alice, attachment)
|
||||
# Повторный bootstrap не должен очистить bucket или сменить используемые credentials.
|
||||
for _ in range(2):
|
||||
project.run('run', '--rm', '--no-deps', 'minio-bootstrap', timeout=100)
|
||||
project.run("run", "--rm", "--no-deps", "minio-bootstrap", timeout=100)
|
||||
replicas = project.replicas()
|
||||
check(bool(replicas), 'API not running')
|
||||
result = subprocess.run(['docker', 'exec', '-i', replicas[0].id, 'python', '-c', PROBE],
|
||||
input=json.dumps({'attachment_id': attachment['id']}),
|
||||
text=True, capture_output=True, timeout=20)
|
||||
check(result.returncode == 0, 'private bucket probe failed (details hidden)')
|
||||
check(bool(replicas), "API not running")
|
||||
result = subprocess.run(
|
||||
["docker", "exec", "-i", replicas[0].id, "python", "-c", PROBE],
|
||||
input=json.dumps({"attachment_id": attachment["id"]}),
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=20,
|
||||
)
|
||||
check(result.returncode == 0, "private bucket probe failed (details hidden)")
|
||||
statuses = json.loads(result.stdout)
|
||||
check(statuses['GET'] == statuses['PUT'] == 403, 'anonymous S3 access allowed')
|
||||
check(statuses['admin_denied'] and statuses['other_buckets_denied'] and statuses['root_files_absent'], 'API has excessive access')
|
||||
check(statuses['console_unreachable'], 'console reachable from API network')
|
||||
check(statuses['temp_originals_absent'], 'API retained temporary originals')
|
||||
check(not project.config['services']['minio'].get('ports'), 'MinIO publishes host ports')
|
||||
env = project.config['services']['minio']['environment']
|
||||
check(env['MINIO_BROWSER'] == 'off', 'browser enabled')
|
||||
check('127.0.0.1:9001' in project.config['services']['minio']['command'], 'console is not bound to loopback')
|
||||
path = '/api/v1/attachments/' + attachment['id'] + '/content'
|
||||
check(client.call('GET', path, actor=alice)['bytes'] == original, 'bootstrap changed original')
|
||||
if args.with_faults:
|
||||
project.run('stop', 'cleanup')
|
||||
try:
|
||||
fault_script = Path(__file__).with_name('s3_faults.py').read_text()
|
||||
result = subprocess.run(
|
||||
['docker', 'exec', '-i', replicas[0].id, 'python', '-c', fault_script],
|
||||
input=json.dumps({'user': alice['user'], 'chat_id': chat['id'],
|
||||
'image': base64.b64encode(original).decode()}),
|
||||
text=True, capture_output=True, timeout=60,
|
||||
)
|
||||
check(result.returncode == 0, 'real S3/database compensation probe failed (details hidden)')
|
||||
check(all(json.loads(result.stdout).values()), 'real S3/database invariants failed')
|
||||
finally:
|
||||
project.run('start', 'cleanup')
|
||||
check(client.call('GET', path, actor=alice)['bytes'] == original, 'cleanup damaged confirmed original')
|
||||
check(statuses["GET"] == statuses["PUT"] == 403, "anonymous S3 access allowed")
|
||||
check(
|
||||
statuses["admin_denied"]
|
||||
and statuses["other_buckets_denied"]
|
||||
and statuses["root_files_absent"],
|
||||
"API has excessive access",
|
||||
)
|
||||
check(statuses["console_unreachable"], "console reachable from API network")
|
||||
check(statuses["temp_originals_absent"], "API retained temporary originals")
|
||||
check(
|
||||
not project.config["services"]["minio"].get("ports"),
|
||||
"MinIO publishes host ports",
|
||||
)
|
||||
env = project.config["services"]["minio"]["environment"]
|
||||
check(env["MINIO_BROWSER"] == "off", "browser enabled")
|
||||
check(
|
||||
"127.0.0.1:9001" in project.config["services"]["minio"]["command"],
|
||||
"console is not bound to loopback",
|
||||
)
|
||||
path = "/api/v1/attachments/" + attachment["id"] + "/content"
|
||||
check(
|
||||
client.call("GET", path, actor=alice)["bytes"] == original,
|
||||
"bootstrap changed original",
|
||||
)
|
||||
if args.with_outage:
|
||||
try:
|
||||
project.run('stop', 'minio')
|
||||
client.call('GET', path, expected=503, actor=alice)
|
||||
project.run("stop", "minio")
|
||||
client.call("GET", path, expected=503, actor=alice)
|
||||
finally:
|
||||
project.run('start', 'minio')
|
||||
project.run("start", "minio")
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
client.call('GET', '/health/ready', schema='Health')
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
break
|
||||
except Exception:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.5)
|
||||
check(client.call('GET', path, actor=alice)['bytes'] == original, 'original lost after MinIO restart')
|
||||
print('PASS: idempotent bootstrap, anonymous GET/PUT denied, restricted API credentials, private console'
|
||||
+ (', MinIO outage/recovery' if args.with_outage else ''))
|
||||
if args.with_faults:
|
||||
print('PASS: real S3 PUT/database failure, compensation, durable journal, grace period, dry-run, repeated cleanup')
|
||||
check(
|
||||
client.call("GET", path, actor=alice)["bytes"] == original,
|
||||
"original lost after MinIO restart",
|
||||
)
|
||||
print(
|
||||
"PASS: idempotent bootstrap, anonymous GET/PUT denied, restricted API credentials, private console"
|
||||
+ (", MinIO outage/recovery" if args.with_outage else "")
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
|
||||
@@ -1,204 +0,0 @@
|
||||
"""Повторяемый прогон lab4; публикует только успешные обезличенные evidence."""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
from importlib.metadata import version
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
from tempfile import TemporaryDirectory
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PROJECT = 'mtusi-messenger-lab5-test'
|
||||
EVIDENCE = ROOT / 'evidence'
|
||||
ENVIRONMENT = {
|
||||
**os.environ,
|
||||
'COMPOSE_PROJECT_NAME': PROJECT,
|
||||
'COMPOSE_FILE': 'compose.yaml:compose.test.yaml',
|
||||
'LB_HOST_PORT': '28080',
|
||||
}
|
||||
COMPOSE = ['docker', 'compose', '--env-file', '.env']
|
||||
NONSECRET_SETTINGS = {
|
||||
'APP_PORT', 'API_REPLICAS', 'MAX_MESSAGES', 'MAX_IN_FLIGHT',
|
||||
'DB_POOL_SIZE', 'DB_MAX_OVERFLOW', 'SESSION_TTL_SECONDS',
|
||||
'IDEMPOTENCY_TTL_SECONDS', 'SHUTDOWN_DRAIN_SECONDS',
|
||||
'GRACEFUL_SHUTDOWN_TIMEOUT_SECONDS', 'READINESS_TIMEOUT_SECONDS',
|
||||
'S3_ENDPOINT', 'S3_BUCKET', 'S3_REGION', 'S3_CONNECT_TIMEOUT_SECONDS',
|
||||
'S3_READ_TIMEOUT_SECONDS', 'S3_UPLOAD_TIMEOUT_SECONDS',
|
||||
'S3_DOWNLOAD_TIMEOUT_SECONDS', 'S3_IMAGE_TIMEOUT_SECONDS',
|
||||
'S3_MAX_UPLOAD_BYTES', 'S3_MAX_IMAGE_PIXELS', 'S3_CHUNK_BYTES',
|
||||
'S3_MAX_CONCURRENT_UPLOADS', 'S3_CLEANUP_GRACE_SECONDS',
|
||||
'S3_CLEANUP_INTERVAL_SECONDS',
|
||||
}
|
||||
SNAPSHOT_FORMAT = '{"id":{{json .Id}},"name":{{json .Name}},"service":{{json (index .Config.Labels "com.docker.compose.service")}},"image_id":{{json .Image}},"status":{{json .State.Status}},"started_at":{{json .State.StartedAt}},"pid":{{json .State.Pid}},"exit_code":{{json .State.ExitCode}},"oom_killed":{{json .State.OOMKilled}}}'
|
||||
IMAGE_FORMAT = '{"id":{{json .Id}},"repo_digests":{{json .RepoDigests}},"architecture":{{json .Architecture}},"os":{{json .Os}}}'
|
||||
|
||||
|
||||
def timestamp():
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def invoke(command):
|
||||
return subprocess.run(command, cwd=ROOT, env=ENVIRONMENT, text=True,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
||||
|
||||
|
||||
def read_command(command):
|
||||
result = invoke(command)
|
||||
if result.returncode:
|
||||
raise RuntimeError('Не выполнена команда: ' + shlex.join(command))
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def source_manifest():
|
||||
names = {
|
||||
'.dockerignore', '.env.example',
|
||||
'Dockerfile', 'Makefile', 'alembic.ini', 'compose.yaml',
|
||||
'compose.test.yaml', 'pytest.ini', 'requirements.txt', 'requirements-dev.txt', 'lab.json',
|
||||
}
|
||||
for directory in ('app', 'migrations', 'student-tests', 'scripts', 'infra', 'contracts', 'tests'):
|
||||
names.update(str(path.relative_to(ROOT)) for path in (ROOT / directory).rglob('*')
|
||||
if path.is_file() and '__pycache__' not in path.parts
|
||||
and path.suffix != '.md' and not path.name.startswith('.'))
|
||||
return ''.join(f'{hashlib.sha256((ROOT / name).read_bytes()).hexdigest()} {name}\n' for name in sorted(names))
|
||||
|
||||
|
||||
def sanitize(text, secrets, staging):
|
||||
clean = text.replace(str(ROOT), '.').replace(str(staging), '<temporary>')
|
||||
for secret in secrets:
|
||||
clean = clean.replace(secret, '<redacted>')
|
||||
clean = re.sub(r'(?i)\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+', r'\1 <redacted>', clean)
|
||||
clean = re.sub(r"(?i)([\"'](?:token|password|secret_access_key)[\"']\s*:\s*[\"'])[^\"']*", r'\1<redacted>', clean)
|
||||
return clean
|
||||
|
||||
|
||||
def container_snapshot(images):
|
||||
ids = read_command(['docker', 'ps', '-aq', '--filter', f'label=com.docker.compose.project={PROJECT}']).splitlines()
|
||||
rows = []
|
||||
if ids:
|
||||
output = read_command(['docker', 'inspect', '--format', SNAPSHOT_FORMAT, *ids])
|
||||
rows = [json.loads(line) for line in output.splitlines()]
|
||||
for row in rows:
|
||||
image = row['image_id']
|
||||
if image not in images:
|
||||
images[image] = json.loads(read_command(['docker', 'image', 'inspect', '--format', IMAGE_FORMAT, image]))
|
||||
return rows
|
||||
|
||||
|
||||
def remaining_resources():
|
||||
return {resource: read_command(['docker', resource, 'ls', '-aq' if resource == 'container' else '-q', '--filter',
|
||||
f'label=com.docker.compose.project={PROJECT}']).splitlines()
|
||||
for resource in ('container', 'network', 'volume')}
|
||||
|
||||
|
||||
def extract_metrics(output, upload_file):
|
||||
rows = [json.loads(line) for line in output.splitlines() if line.startswith('{') and line.endswith('}')]
|
||||
pytest = re.search(r'(\d+) passed(?:, [^\n]*?)? in ([\d.]+)s', output)
|
||||
if pytest is None:
|
||||
raise RuntimeError('В выводе нет успешного итогового результата pytest')
|
||||
return {
|
||||
'pytest': {'passed': int(pytest[1]), 'elapsed_seconds': float(pytest[2])},
|
||||
'uploads': json.loads(upload_file.read_text()),
|
||||
'public_failover': [row for row in rows if 'observed_instances_before' in row],
|
||||
'rolling_update': [row for row in rows if row.get('scenario') == 'rolling update'],
|
||||
'replica_failures': [row for row in rows if 'first_recovery_seconds' in row and 'instance' in row],
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
if any(remaining_resources().values()):
|
||||
raise RuntimeError('Тестовый проект уже существует; сначала завершите его отдельно')
|
||||
started = timestamp()
|
||||
manifest = source_manifest()
|
||||
secrets = [path.read_text().strip() for path in (ROOT / 'secrets').iterdir() if path.is_file()]
|
||||
secrets = [value for value in secrets if value]
|
||||
snapshots, images, commands, combined, nginx_output = {}, {}, [], [], ''
|
||||
info = json.loads(read_command(['docker', 'info', '--format', '{{json .}}']))
|
||||
config = json.loads(read_command([*COMPOSE, 'config', '--format', 'json']))
|
||||
services = {name: {
|
||||
'image': service.get('image'),
|
||||
'limits': service.get('deploy', {}).get('resources', {}).get('limits', {}),
|
||||
'settings': {key: value for key, value in service.get('environment', {}).items() if key in NONSECRET_SETTINGS},
|
||||
'ports': service.get('ports', []), 'networks': list(service.get('networks', {})),
|
||||
'secret_names': [entry['source'] for entry in service.get('secrets', [])],
|
||||
'tmpfs': service.get('tmpfs', []),
|
||||
} for name, service in config['services'].items()}
|
||||
with TemporaryDirectory(prefix='lab4-evidence-') as folder:
|
||||
staging = Path(folder)
|
||||
upload_file = staging / 'uploads.json'
|
||||
|
||||
def execute(command):
|
||||
begin = timestamp()
|
||||
result = invoke(command)
|
||||
output = sanitize(result.stdout, secrets, staging)
|
||||
display = sanitize(shlex.join(command), secrets, staging)
|
||||
commands.append({'command': display, 'started_at_utc': begin,
|
||||
'finished_at_utc': timestamp(), 'exit_code': result.returncode})
|
||||
print(f'{"PASS" if result.returncode == 0 else "FAIL"}: {display}', flush=True)
|
||||
if result.returncode:
|
||||
print(output[-5000:], flush=True)
|
||||
raise RuntimeError('Прогон остановлен; неуспешные evidence не опубликованы')
|
||||
return f'$ {display}\n{output}\n'
|
||||
|
||||
cleanup_output = ''
|
||||
try:
|
||||
combined.append(execute(['make', 'check', 'validate', 'test-stand-up', f'TEST_PROJECT={PROJECT}']))
|
||||
snapshots['started'] = container_snapshot(images)
|
||||
combined.append(execute(['make', 'test-docker', f'TEST_PROJECT={PROJECT}', 'PYTEST_ARGS=--tb=short']))
|
||||
combined.append(execute(['make', 'test-stand-smoke', 'test-stand-idempotency', f'TEST_PROJECT={PROJECT}']))
|
||||
snapshots['before_restart'] = container_snapshot(images)
|
||||
combined.append(execute(['make', 'test-stand-persistence', f'TEST_PROJECT={PROJECT}']))
|
||||
snapshots['after_restart'] = container_snapshot(images)
|
||||
combined.append(execute(['make', 'test-stand-failover', f'TEST_PROJECT={PROJECT}']))
|
||||
snapshots['after_failover'] = container_snapshot(images)
|
||||
combined.append(execute(['.venv/bin/python', '-m', 'scripts.check_s3', '--base-url', 'http://localhost:28080', '--with-outage', '--with-faults']))
|
||||
combined.append(execute(['.venv/bin/python', '-m', 'scripts.upload_load', '--base-url', 'http://localhost:28080', '--concurrency', '10', '--output', str(upload_file)]))
|
||||
combined.append(execute(['.venv/bin/python', '-m', 'scripts.check_grade4', '--base-url', 'http://localhost:28080']))
|
||||
snapshots['after_update_and_failures'] = container_snapshot(images)
|
||||
nginx_output = execute(['make', 'test-nginx'])
|
||||
finally:
|
||||
cleanup_output = execute([*COMPOSE, 'down', '--volumes', '--remove-orphans'])
|
||||
remaining = remaining_resources()
|
||||
if any(remaining.values()):
|
||||
raise RuntimeError('После очистки остались ресурсы тестового проекта')
|
||||
if source_manifest() != manifest:
|
||||
raise RuntimeError('Во время прогона изменились проверяемые исходники')
|
||||
output = ''.join(combined)
|
||||
metrics = extract_metrics(output, upload_file)
|
||||
run = {
|
||||
'started_at_utc': started, 'finished_at_utc': timestamp(),
|
||||
'started_at_moscow': datetime.fromisoformat(started).astimezone(ZoneInfo('Europe/Moscow')).isoformat(),
|
||||
'base_commit': read_command(['git', 'rev-parse', 'HEAD']),
|
||||
'worktree_dirty': bool(read_command(['git', 'status', '--porcelain'])),
|
||||
'source_manifest_sha256': hashlib.sha256(manifest.encode()).hexdigest(),
|
||||
'project': PROJECT, 'runtime': {'python': platform.python_version(),
|
||||
'packages': {name: version(name) for name in ('fastapi', 'SQLAlchemy', 'pydantic', 'minio', 'Pillow', 'pytest')},
|
||||
'compose': read_command(['docker', 'compose', 'version'])},
|
||||
'docker_host': {key: info[key] for key in ('ServerVersion', 'OperatingSystem', 'Architecture', 'NCPU', 'MemTotal', 'CgroupVersion')},
|
||||
'services': services, 'container_snapshots': snapshots, 'images': images,
|
||||
'commands': commands, 'remaining_test_resources': remaining,
|
||||
'minio_source_release': 'RELEASE.2025-10-15T17-29-55Z',
|
||||
'mc_source_release': 'RELEASE.2025-08-13T08-35-41Z',
|
||||
}
|
||||
artifacts = {
|
||||
'test-output.txt': output, 'nginx-output.txt': nginx_output,
|
||||
'cleanup.txt': cleanup_output, 'source-sha256.txt': manifest,
|
||||
'metrics.json': json.dumps(metrics, ensure_ascii=False, indent=2) + '\n',
|
||||
'run.json': json.dumps(run, ensure_ascii=False, indent=2) + '\n',
|
||||
}
|
||||
for name, content in artifacts.items():
|
||||
if any(secret in content for secret in secrets):
|
||||
raise RuntimeError('Обнаружено значение секрета; evidence не опубликованы')
|
||||
EVIDENCE.mkdir(exist_ok=True)
|
||||
for name, content in artifacts.items():
|
||||
(EVIDENCE / name).write_text(content)
|
||||
print('Evidence опубликованы; тестовые ресурсы удалены.', flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+17
-51
@@ -1,17 +1,10 @@
|
||||
"""Общие операции с репликами текущего Compose-проекта."""
|
||||
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import urlopen
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
@@ -38,8 +31,12 @@ class ComposeProject:
|
||||
def docker(self, *args: str, timeout: int = 90, env=None) -> str:
|
||||
"""Выполняет Docker-команду с ограничением времени."""
|
||||
result = subprocess.run(
|
||||
["docker", *args], cwd=ROOT, text=True, capture_output=True,
|
||||
timeout=timeout, env={**os.environ, **(env or {})},
|
||||
["docker", *args],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
env={**os.environ, **(env or {})},
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError(result.stderr.strip() or result.stdout.strip())
|
||||
@@ -60,48 +57,17 @@ class ComposeProject:
|
||||
'"health":{{if .State.Health}}{{json .State.Health.Status}}{{else}}null{{end}}}'
|
||||
)
|
||||
rows = self.docker("inspect", "--format", template, *ids).splitlines()
|
||||
configured = str(self.config["services"]["api"].get("environment", {}).get("INSTANCE_ID") or "").strip()
|
||||
configured = str(
|
||||
self.config["services"]["api"].get("environment", {}).get("INSTANCE_ID")
|
||||
or ""
|
||||
).strip()
|
||||
return [
|
||||
Replica(row["id"], row["image"], configured or row["hostname"], row["running"], row["health"])
|
||||
Replica(
|
||||
row["id"],
|
||||
row["image"],
|
||||
configured or row["hostname"],
|
||||
row["running"],
|
||||
row["health"],
|
||||
)
|
||||
for row in map(json.loads, rows)
|
||||
]
|
||||
|
||||
def wait_healthy(self, ids: set[str], timeout: float = 40) -> None:
|
||||
"""Ожидает готовность конкретных реплик."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
current = {replica.id: replica for replica in self.replicas()}
|
||||
if not ids <= current.keys():
|
||||
raise RuntimeError("Контейнер API исчез во время развёртывания")
|
||||
if all(current[id].running and current[id].health == "healthy" for id in ids):
|
||||
return
|
||||
if any(not current[id].running for id in ids):
|
||||
raise RuntimeError("Контейнер API завершился до готовности")
|
||||
time.sleep(0.25)
|
||||
raise TimeoutError("API не стал healthy за отведённое время")
|
||||
|
||||
def wait_routed(self, instance_id: str, base_url: str, ca_file=None) -> None:
|
||||
"""Ожидает ответа реплики через балансировщик."""
|
||||
context = ssl.create_default_context(cafile=ca_file)
|
||||
deadline = time.monotonic() + 40
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urlopen(base_url.rstrip("/") + "/health/live", timeout=3, context=context) as response:
|
||||
if response.status == 200 and response.headers.get("X-Instance-Id") == instance_id:
|
||||
return
|
||||
except (HTTPError, URLError, TimeoutError, OSError):
|
||||
pass
|
||||
time.sleep(0.1)
|
||||
raise TimeoutError("Реплика не появилась в ответах балансировщика")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def deployment_lock(project: ComposeProject):
|
||||
"""Исключает параллельные изменения одного стенда."""
|
||||
path = Path(tempfile.gettempdir()) / f"{project.name}-deployment.lock"
|
||||
with path.open("a") as lock:
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
raise RuntimeError("Другой процесс уже изменяет этот Compose-проект") from None
|
||||
yield
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
BASE_URL="${BASE_URL:-http://localhost:8080}"
|
||||
TTL="${TTL:?укажите TTL, с которым запущен API (SESSION_TTL_SECONDS)}"
|
||||
API="$BASE_URL/api/v1"
|
||||
USERNAME="expiry_$(date +%s)"
|
||||
PASSWORD="expiry-password-123"
|
||||
|
||||
code() {
|
||||
curl -s -o /dev/null -w '%{http_code}' "$@"
|
||||
}
|
||||
|
||||
curl -sf -o /dev/null -X POST "$API/users" -H 'Content-Type: application/json' \
|
||||
-d "{\"username\":\"$USERNAME\",\"display_name\":\"Expiry\",\"password\":\"$PASSWORD\"}"
|
||||
SESSION=$(curl -sf -X POST "$API/auth/sessions" -u "$USERNAME:$PASSWORD")
|
||||
TOKEN=$(printf '%s' "$SESSION" | python3 -c 'import json, sys; print(json.load(sys.stdin)["token"])')
|
||||
EXPIRES_AT=$(printf '%s' "$SESSION" | python3 -c 'import json, sys; print(json.load(sys.stdin)["expires_at"])')
|
||||
AUTH="Authorization: Bearer $TOKEN"
|
||||
|
||||
echo "SESSION_TTL_SECONDS=$TTL, login at $(date -u +%H:%M:%S)Z, expires_at=$EXPIRES_AT"
|
||||
echo "GET /users/me right after login -> $(code "$API/users/me" -H "$AUTH")"
|
||||
sleep $((TTL + 1))
|
||||
printf "%-35s -> %s\n" "GET /users/me after $((TTL + 1)) s" "$(code "$API/users/me" -H "$AUTH")"
|
||||
echo "DELETE /auth/sessions/current after -> $(code -X DELETE "$API/auth/sessions/current" -H "$AUTH")"
|
||||
NEW_TOKEN=$(curl -sf -X POST "$API/auth/sessions" -u "$USERNAME:$PASSWORD" \
|
||||
| python3 -c 'import json, sys; print(json.load(sys.stdin)["token"])')
|
||||
echo "GET /users/me with new login token -> $(code "$API/users/me" -H "Authorization: Bearer $NEW_TOKEN")"
|
||||
@@ -1,132 +0,0 @@
|
||||
"""EXPLAIN (ANALYZE, BUFFERS) запроса истории на синтетических данных.
|
||||
|
||||
Данные создаются в одной транзакции и откатываются в конце: база не меняется.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import AsyncConnection
|
||||
|
||||
from app.core.config import Settings
|
||||
from app.core.database import create_db_engine
|
||||
|
||||
TARGET_MESSAGES = 10_000
|
||||
NOISE_MESSAGES = 40_000
|
||||
PAGE = 51
|
||||
|
||||
HISTORY_FIRST_PAGE = """
|
||||
SELECT * FROM messages
|
||||
WHERE chat_id = :chat_id
|
||||
ORDER BY created_at, id
|
||||
LIMIT :page
|
||||
"""
|
||||
|
||||
HISTORY_AFTER_CURSOR = """
|
||||
SELECT * FROM messages
|
||||
WHERE chat_id = :chat_id AND (created_at, id) > (:after_created_at, :after_id)
|
||||
ORDER BY created_at, id
|
||||
LIMIT :page
|
||||
"""
|
||||
|
||||
|
||||
async def seed(connection: AsyncConnection) -> dict[str, object]:
|
||||
user_id, target_id, noise_id = uuid4(), uuid4(), uuid4()
|
||||
await connection.execute(
|
||||
text(
|
||||
"INSERT INTO users (id, username, display_name, password_hash) "
|
||||
"VALUES (:id, :username, 'Explain', 'x')"
|
||||
),
|
||||
{"id": user_id, "username": "explain_" + uuid4().hex[:8]},
|
||||
)
|
||||
await connection.execute(
|
||||
text("INSERT INTO chats (id, title) VALUES (:a, 'target'), (:b, 'noise')"),
|
||||
{"a": target_id, "b": noise_id},
|
||||
)
|
||||
await connection.execute(
|
||||
text("INSERT INTO chat_members (chat_id, user_id) VALUES (:a, :u), (:b, :u)"),
|
||||
{"a": target_id, "b": noise_id, "u": user_id},
|
||||
)
|
||||
for chat_id, count in ((target_id, TARGET_MESSAGES), (noise_id, NOISE_MESSAGES)):
|
||||
await connection.execute(
|
||||
text(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) "
|
||||
"SELECT gen_random_uuid(), :chat_id, :user_id, 'message ' || g, "
|
||||
"now() - make_interval(secs => :count - g) "
|
||||
"FROM generate_series(1, :count) AS g"
|
||||
),
|
||||
{"chat_id": chat_id, "user_id": user_id, "count": count},
|
||||
)
|
||||
await connection.execute(text("ANALYZE messages"))
|
||||
|
||||
middle = (
|
||||
await connection.execute(
|
||||
text(
|
||||
"SELECT created_at, id FROM messages WHERE chat_id = :c "
|
||||
"ORDER BY created_at, id OFFSET :o LIMIT 1"
|
||||
),
|
||||
{"c": target_id, "o": TARGET_MESSAGES // 2},
|
||||
)
|
||||
).one()
|
||||
return {
|
||||
"chat_id": target_id,
|
||||
"after_created_at": middle.created_at,
|
||||
"after_id": middle.id,
|
||||
"page": PAGE,
|
||||
}
|
||||
|
||||
|
||||
async def explain(
|
||||
connection: AsyncConnection, title: str, query: str, params: dict[str, object]
|
||||
) -> None:
|
||||
rows = await connection.execute(
|
||||
text(f"EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING ON) {query}"), params
|
||||
)
|
||||
print(f"== {title}")
|
||||
print(query.strip())
|
||||
print()
|
||||
for row in rows:
|
||||
print(row[0])
|
||||
print()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
engine = create_db_engine(Settings()) # type: ignore[call-arg]
|
||||
async with engine.connect() as connection:
|
||||
transaction = await connection.begin()
|
||||
params = await seed(connection)
|
||||
total = (
|
||||
await connection.execute(text("SELECT count(*) FROM messages"))
|
||||
).scalar_one()
|
||||
print(
|
||||
f"messages in table: {total}; target chat: {TARGET_MESSAGES}; noise chat: {NOISE_MESSAGES}"
|
||||
)
|
||||
print()
|
||||
|
||||
first_page = {"chat_id": params["chat_id"], "page": PAGE}
|
||||
await explain(
|
||||
connection, "first page (limit+1 = 51)", HISTORY_FIRST_PAGE, first_page
|
||||
)
|
||||
await explain(
|
||||
connection,
|
||||
"page after cursor in the middle of history",
|
||||
HISTORY_AFTER_CURSOR,
|
||||
params,
|
||||
)
|
||||
|
||||
await connection.execute(text("SET LOCAL enable_indexscan = off"))
|
||||
await connection.execute(text("SET LOCAL enable_bitmapscan = off"))
|
||||
await explain(
|
||||
connection,
|
||||
"same page with index scans disabled (for comparison)",
|
||||
HISTORY_AFTER_CURSOR,
|
||||
params,
|
||||
)
|
||||
|
||||
await transaction.rollback()
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -1,148 +0,0 @@
|
||||
"""Сценарий поочерёдного отказа всех API-реплик под записью."""
|
||||
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
from threading import Event, Lock
|
||||
import time
|
||||
from urllib.parse import quote
|
||||
from uuid import uuid4
|
||||
|
||||
from scripts.deployment import ComposeProject, ROOT, deployment_lock
|
||||
from tests.client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def failure_kind(error: Failure) -> str:
|
||||
"""Различает HTTP-отказы, ошибки соединения и проверки контракта."""
|
||||
match = re.search(r"received (\d{3})$", str(error))
|
||||
if match:
|
||||
return "http_" + match.group(1)
|
||||
return "connection" if "connection/TLS failure" in str(error) else "contract"
|
||||
|
||||
|
||||
def snapshot(project: ComposeProject, phase: str, target: str) -> list:
|
||||
"""Печатает состояние API без окружения и секретов."""
|
||||
replicas = project.replicas()
|
||||
print(json.dumps({
|
||||
"scenario": "replica_failure", "phase": phase, "target": target,
|
||||
"replicas": [{"instance": item.instance_id, "running": item.running, "health": item.health} for item in replicas],
|
||||
}), flush=True)
|
||||
return replicas
|
||||
|
||||
|
||||
def history(client: Client, actor: dict, chat: dict) -> list[dict]:
|
||||
"""Читает всю историю без повторов курсора."""
|
||||
path = f"/api/v1/chats/{chat['id']}/messages?limit=100"
|
||||
items = []
|
||||
cursors = set()
|
||||
for _ in range(1000):
|
||||
page = client.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
items.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return items
|
||||
check(cursor not in cursors, "cursor cycle")
|
||||
cursors.add(cursor)
|
||||
path = f"/api/v1/chats/{chat['id']}/messages?limit=100&cursor={quote(cursor, safe='')}"
|
||||
raise Failure("history exceeded safety bound")
|
||||
|
||||
|
||||
def exercise(project: ComposeProject, args) -> None:
|
||||
"""Останавливает каждую реплику и восстанавливает её перед следующей."""
|
||||
replicas = project.replicas()
|
||||
check(len(replicas) >= 2, "at least two API replicas are required")
|
||||
project.wait_healthy({item.id for item in replicas})
|
||||
client = Client(args.base_url, args.ca_file, timeout=2)
|
||||
for item in replicas:
|
||||
project.wait_routed(item.instance_id, client.base, args.ca_file)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
confirmed = set()
|
||||
|
||||
for target in replicas:
|
||||
snapshot(project, "before", target.instance_id)
|
||||
stop = Event()
|
||||
lock = Lock()
|
||||
successes = []
|
||||
errors = []
|
||||
|
||||
def worker():
|
||||
local = Client(client.base, args.ca_file, timeout=2)
|
||||
key = uuid4().hex
|
||||
while not stop.is_set():
|
||||
started = time.monotonic()
|
||||
try:
|
||||
result = local.message(actor, chat, "failover-" + key, key=key)
|
||||
with lock:
|
||||
successes.append((started, time.monotonic(), result["json"]["id"]))
|
||||
key = uuid4().hex
|
||||
except Failure as error:
|
||||
with lock:
|
||||
errors.append(failure_kind(error))
|
||||
time.sleep(0.1)
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
jobs = [pool.submit(worker) for _ in range(args.concurrency)]
|
||||
try:
|
||||
time.sleep(2)
|
||||
stop_started = time.monotonic()
|
||||
subprocess.run(
|
||||
[str(ROOT / "scripts/stop-one.sh")], cwd=ROOT,
|
||||
env={**os.environ, "TARGET_INSTANCE_ID": target.instance_id},
|
||||
check=True, timeout=10, capture_output=True,
|
||||
)
|
||||
stop_finished = time.monotonic()
|
||||
stopped = snapshot(project, "stopped", target.instance_id)
|
||||
check(any(item.id == target.id and not item.running for item in stopped), "target API was not stopped")
|
||||
check(any(item.id != target.id and item.running and item.health == "healthy" for item in stopped), "no healthy surviving API")
|
||||
time.sleep(args.duration)
|
||||
finally:
|
||||
stop.set()
|
||||
try:
|
||||
for job in jobs:
|
||||
job.result(timeout=5)
|
||||
finally:
|
||||
project.docker("start", target.id)
|
||||
project.wait_healthy({item.id for item in replicas})
|
||||
project.wait_routed(target.instance_id, client.base, args.ca_file)
|
||||
snapshot(project, "restored", target.instance_id)
|
||||
|
||||
elapsed = max(end for _, end, _ in successes) - started if successes else 0
|
||||
recovered = [end for begin, end, _ in successes if begin >= stop_finished]
|
||||
check(bool(recovered), "no confirmed writes after failure")
|
||||
recovery = min(recovered) - stop_started
|
||||
check(recovery <= 10, "writes did not recover within 10 seconds")
|
||||
confirmed.update(id for _, _, id in successes)
|
||||
items = history(client, actor, chat)
|
||||
check(confirmed <= {item["id"] for item in items}, "confirmed messages were lost")
|
||||
texts = [item["text"] for item in items]
|
||||
check(len(texts) == len(set(texts)), "uncertain retry created duplicates")
|
||||
print(json.dumps({
|
||||
"instance": target.instance_id,
|
||||
"successful_writes": len(successes),
|
||||
"failed_attempts": len(errors),
|
||||
"errors_by_kind": dict(Counter(errors)),
|
||||
"elapsed_seconds": round(elapsed, 3),
|
||||
"successful_rps": round(len(successes) / elapsed, 3) if elapsed else 0,
|
||||
"first_recovery_seconds": round(recovery, 3),
|
||||
}), flush=True)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Готовит параметры эксперимента отказа реплик."""
|
||||
def configure(parser):
|
||||
parser.add_argument("--duration", type=float, default=15)
|
||||
parser.add_argument("--concurrency", type=int, default=2)
|
||||
|
||||
args = arguments("Fail each API replica under write load", configure)
|
||||
check(1 <= args.duration <= 120 and 1 <= args.concurrency <= 8, "invalid workload")
|
||||
project = ComposeProject()
|
||||
with deployment_lock(project):
|
||||
exercise(project, args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -1,64 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
BASE_URL="${BASE_URL:-http://localhost:8080}"
|
||||
API="$BASE_URL/api/v1"
|
||||
USERNAME="demo_$(date +%s)"
|
||||
PASSWORD="demo-password-123"
|
||||
|
||||
compose() {
|
||||
docker compose --env-file .env "$@"
|
||||
}
|
||||
|
||||
code() {
|
||||
curl -s -o /dev/null -w '%{http_code} (%{time_total}s)' "$@"
|
||||
}
|
||||
|
||||
wait_healthy() {
|
||||
attempts=0
|
||||
until [ "$(compose ps --format '{{.Health}}' "$1")" = "healthy" ]; do
|
||||
attempts=$((attempts + 1))
|
||||
[ "$attempts" -lt 60 ] || { echo "$1 не стал healthy" >&2; exit 1; }
|
||||
sleep 1
|
||||
done
|
||||
}
|
||||
|
||||
curl -sf -o /dev/null -X POST "$API/users" -H 'Content-Type: application/json' \
|
||||
-d "{\"username\":\"$USERNAME\",\"display_name\":\"Demo\",\"password\":\"$PASSWORD\"}"
|
||||
TOKEN=$(curl -sf -X POST "$API/auth/sessions" -u "$USERNAME:$PASSWORD" \
|
||||
| python3 -c 'import json, sys; print(json.load(sys.stdin)["token"])')
|
||||
AUTH="Authorization: Bearer $TOKEN"
|
||||
|
||||
echo "== baseline"
|
||||
echo "GET /users/me (Bearer) -> $(code "$API/users/me" -H "$AUTH")"
|
||||
|
||||
echo
|
||||
echo "== redis stopped"
|
||||
compose stop redis >/dev/null 2>&1
|
||||
echo "GET /users/me (Bearer) -> $(code "$API/users/me" -H "$AUTH")"
|
||||
echo "POST /auth/sessions (Basic) -> $(code -X POST "$API/auth/sessions" -u "$USERNAME:$PASSWORD")"
|
||||
echo "GET /users/me (no token) -> $(code "$API/users/me")"
|
||||
echo "GET /health/ready -> $(code "$BASE_URL/health/ready")"
|
||||
echo "GET /health/live -> $(code "$BASE_URL/health/live")"
|
||||
compose start redis >/dev/null 2>&1
|
||||
wait_healthy redis
|
||||
echo "-- redis started again (AOF restored)"
|
||||
echo "GET /users/me (same token) -> $(code "$API/users/me" -H "$AUTH")"
|
||||
|
||||
echo
|
||||
echo "== postgres stopped"
|
||||
compose stop postgres >/dev/null 2>&1
|
||||
echo "GET /users/me (Bearer) -> $(code "$API/users/me" -H "$AUTH")"
|
||||
echo "GET /api/v1/chats (Bearer) -> $(code "$API/chats" -H "$AUTH")"
|
||||
echo "GET /health/ready -> $(code "$BASE_URL/health/ready")"
|
||||
echo "GET /health/live -> $(code "$BASE_URL/health/live")"
|
||||
compose start postgres >/dev/null 2>&1
|
||||
wait_healthy postgres
|
||||
echo "-- postgres started again"
|
||||
echo "GET /users/me (same token) -> $(code "$API/users/me" -H "$AUTH")"
|
||||
|
||||
echo
|
||||
echo "== logout"
|
||||
echo "DELETE /auth/sessions/current -> $(code -X DELETE "$API/auth/sessions/current" -H "$AUTH")"
|
||||
echo "GET /users/me (same token) -> $(code "$API/users/me" -H "$AUTH")"
|
||||
@@ -14,7 +14,15 @@ def main() -> None:
|
||||
destination.chmod(0o600)
|
||||
directory = root / "secrets"
|
||||
directory.mkdir(mode=0o700, exist_ok=True)
|
||||
for name in ("db_password", "redis_password", "broker_password", "minio_root_user", "minio_root_password", "s3_access_key_id", "s3_secret_access_key"):
|
||||
for name in (
|
||||
"db_password",
|
||||
"redis_password",
|
||||
"broker_password",
|
||||
"minio_root_user",
|
||||
"minio_root_password",
|
||||
"s3_access_key_id",
|
||||
"s3_secret_access_key",
|
||||
):
|
||||
path = directory / name
|
||||
try:
|
||||
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o444)
|
||||
|
||||
@@ -3,7 +3,7 @@ set -eu
|
||||
# TODO: copy to restart.sh and implement using YOUR compose/stack services.
|
||||
# Restart API and ALL used state stores (DB, sessions, S3, broker as applicable).
|
||||
# Preserve persistent volumes and schema/data; never down -v / flush / re-seed.
|
||||
# Allow operator unseal if required in lab7; do not print credentials.
|
||||
# Do not print credentials.
|
||||
# Exit 0 only after the intended action; test waits for API readiness separately.
|
||||
printf '%s
|
||||
' 'TODO: implement restart.sh for your infrastructure' >&2
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
"""Поочерёдно заменяет API с одной дополнительной репликой."""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from scripts.deployment import ComposeProject, deployment_lock
|
||||
|
||||
|
||||
def update(project: ComposeProject, base_url: str, ca_file=None, revision: str | None = None) -> None:
|
||||
"""Собирает образ, применяет миграции и заменяет реплики."""
|
||||
original = project.replicas()
|
||||
if len(original) < 2 or any(not item.running or item.health != "healthy" for item in original):
|
||||
raise RuntimeError("До обновления нужны минимум две здоровые API-реплики")
|
||||
old_images = {item.image for item in original}
|
||||
if len(old_images) != 1:
|
||||
raise RuntimeError("Сначала восстановите единый образ работающих реплик")
|
||||
old_image = old_images.pop()
|
||||
profile = project.docker(
|
||||
"image", "inspect", old_image,
|
||||
"--format", '{{index .Config.Labels "io.mtusi.messenger.secrets"}}',
|
||||
)
|
||||
if profile != "file-v1":
|
||||
raise RuntimeError("Сначала выполните первоначальный переход на файловые секреты через make up")
|
||||
count = len(original)
|
||||
print("Сборка нового образа API", flush=True)
|
||||
build_args = ("--build-arg", f"API_BUILD_REVISION={revision}") if revision else ()
|
||||
project.run("build", *build_args, "api", timeout=300)
|
||||
tag = project.config["services"]["api"]["image"]
|
||||
new_image = project.docker("image", "inspect", tag, "--format", "{{.Id}}")
|
||||
print("Однократное применение совместимых миграций", flush=True)
|
||||
project.run("run", "--rm", "--no-deps", "--pull", "never", "migrate")
|
||||
if old_image == new_image:
|
||||
print("Образ не изменился; замена контейнеров не требуется")
|
||||
return
|
||||
|
||||
try:
|
||||
for old in original:
|
||||
project.run(
|
||||
"up", "-d", "--no-deps", "--no-build", "--pull", "never",
|
||||
"--no-recreate", "--scale", f"api={count + 1}", "api",
|
||||
)
|
||||
current = project.replicas()
|
||||
additions = [item for item in current if item.id not in {replica.id for replica in original} and item.image == new_image]
|
||||
if not additions:
|
||||
raise RuntimeError("Новая реплика не создана")
|
||||
project.wait_healthy({item.id for item in additions})
|
||||
for added in additions:
|
||||
project.wait_routed(added.instance_id, base_url, ca_file)
|
||||
survivors = {item.id for item in project.replicas() if item.id != old.id}
|
||||
project.wait_healthy(survivors)
|
||||
project.docker("stop", old.id)
|
||||
project.docker("rm", old.id)
|
||||
print(f"Заменена реплика {old.instance_id}", flush=True)
|
||||
final = project.replicas()
|
||||
if len(final) != count or any(item.image != new_image for item in final):
|
||||
raise RuntimeError("Состав реплик после обновления не соответствует плану")
|
||||
project.wait_healthy({item.id for item in final})
|
||||
except Exception:
|
||||
print("Обновление прервано; восстанавливается прежний образ без отката БД", file=sys.stderr)
|
||||
project.run(
|
||||
"up", "-d", "--no-deps", "--no-build", "--pull", "never",
|
||||
"--force-recreate", "--scale", f"api={count}", "api",
|
||||
env={"API_IMAGE": old_image},
|
||||
)
|
||||
project.wait_healthy({item.id for item in project.replicas()})
|
||||
raise
|
||||
|
||||
dangling = project.docker("image", "ls", "--quiet", "--no-trunc", "--filter", "dangling=true").splitlines()
|
||||
if old_image in dangling:
|
||||
references = project.docker("ps", "--all", "--quiet", "--filter", f"ancestor={old_image}")
|
||||
if not references:
|
||||
try:
|
||||
project.docker("image", "rm", old_image)
|
||||
except RuntimeError:
|
||||
print("Прежний образ не удалён: состояние Docker изменилось", file=sys.stderr)
|
||||
print(f"Готово: {count} здоровых реплик нового образа")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Запускает обновление с блокировкой проекта."""
|
||||
parser = argparse.ArgumentParser(description="Rolling update of API replicas")
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--ca-file", default=None)
|
||||
parser.add_argument("--revision", default=None)
|
||||
args = parser.parse_args()
|
||||
project = ComposeProject()
|
||||
with deployment_lock(project):
|
||||
update(project, args.base_url or "http://localhost:8080", args.ca_file, args.revision)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,108 +0,0 @@
|
||||
"""Исполняется внутри API-контейнера: реальные S3/БД и управляемые отказы."""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
import sys
|
||||
from uuid import UUID
|
||||
|
||||
from minio.error import S3Error
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
from app.core.config import Settings
|
||||
from app.core.database import create_db_engine, create_session_factory
|
||||
from app.domain import attachments as domain
|
||||
from app.errors.exceptions import unavailable
|
||||
from app.models.attachment import UploadIntent
|
||||
from app.schemas.user import User
|
||||
from app.storage import attachments as repository
|
||||
from app.storage.s3 import create_s3_storage
|
||||
|
||||
|
||||
async def object_exists(storage, key):
|
||||
exists = True
|
||||
try:
|
||||
await storage.stat_object(key)
|
||||
except S3Error as error:
|
||||
if error.code not in {'NoSuchKey', 'NoSuchObject'}:
|
||||
raise
|
||||
exists = False
|
||||
return exists
|
||||
|
||||
|
||||
async def main():
|
||||
payload = json.load(sys.stdin)
|
||||
settings = Settings()
|
||||
engine = create_db_engine(settings)
|
||||
factory = create_session_factory(engine)
|
||||
storage = create_s3_storage(settings.s3)
|
||||
user = User.model_validate(payload['user'])
|
||||
chat_id = UUID(payload['chat_id'])
|
||||
original = base64.b64decode(payload['image'])
|
||||
keys = []
|
||||
create_record = repository.create_attachment
|
||||
put_file, delete_object = storage.put_file, storage.delete_object
|
||||
|
||||
async def capture_put(key, path, **metadata):
|
||||
keys.append(key)
|
||||
await put_file(key, path, **metadata)
|
||||
|
||||
async def fail_metadata(*args, **kwargs):
|
||||
raise OperationalError('injected metadata failure after real S3 PUT', {}, None)
|
||||
|
||||
async def fail_delete(*args):
|
||||
raise unavailable('injected compensation failure')
|
||||
|
||||
async def chunks():
|
||||
yield original
|
||||
|
||||
async def attempt():
|
||||
raised = False
|
||||
async with factory() as session:
|
||||
try:
|
||||
await domain.upload_attachment(session, storage, user, chat_id,
|
||||
filename='fault.png', content_type='image/png', chunks=chunks())
|
||||
except OperationalError:
|
||||
raised = True
|
||||
assert raised, 'injected database failure was not raised'
|
||||
|
||||
storage.put_file = capture_put
|
||||
repository.create_attachment = fail_metadata
|
||||
try:
|
||||
await attempt()
|
||||
assert not await object_exists(storage, keys[-1]), 'compensation left original'
|
||||
async with factory() as session:
|
||||
intent = await session.scalar(select(UploadIntent).where(UploadIntent.object_key == keys[-1]))
|
||||
assert intent is None, 'compensated upload left intent'
|
||||
storage.delete_object = fail_delete
|
||||
await attempt()
|
||||
key = keys[-1]
|
||||
assert await object_exists(storage, key), 'fault did not leave real S3 object'
|
||||
storage.delete_object = delete_object
|
||||
async with factory() as session:
|
||||
result = await domain.reconcile_attachments(session, storage, dry_run=False)
|
||||
assert result.deleted == 0, 'fresh object deleted before grace period'
|
||||
intent = await session.scalar(select(UploadIntent).where(UploadIntent.object_key == key))
|
||||
assert intent is not None, 'durable intent missing'
|
||||
intent.created_at = datetime.now(timezone.utc) - timedelta(days=2)
|
||||
await session.commit()
|
||||
dry_run = await domain.reconcile_attachments(session, storage)
|
||||
assert dry_run.candidates == 1 and dry_run.deleted == 0
|
||||
assert await object_exists(storage, key), 'dry-run removed original'
|
||||
applied = await domain.reconcile_attachments(session, storage, dry_run=False)
|
||||
assert applied.deleted == 1 and not await object_exists(storage, key)
|
||||
repeated = await domain.reconcile_attachments(session, storage, dry_run=False)
|
||||
assert repeated.examined == repeated.deleted == 0
|
||||
print(json.dumps({'compensation': True, 'durable_intent': True, 'grace_period': True,
|
||||
'dry_run': True, 'cleanup': True, 'idempotent_cleanup': True}))
|
||||
finally:
|
||||
repository.create_attachment = create_record
|
||||
storage.put_file, storage.delete_object = put_file, delete_object
|
||||
await storage.aclose()
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -1,113 +0,0 @@
|
||||
"""Повторяемые параллельные upload и память cgroup API, без записи токенов."""
|
||||
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
from io import BytesIO
|
||||
import json
|
||||
from pathlib import Path
|
||||
import random
|
||||
import subprocess
|
||||
from threading import Barrier
|
||||
import time
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from scripts.deployment import ComposeProject
|
||||
from tests.client import Client, Failure, arguments, check, run
|
||||
|
||||
MONITOR = r'''
|
||||
import json, pathlib, sys, threading
|
||||
root = pathlib.Path('/sys/fs/cgroup')
|
||||
def current():
|
||||
return int((root / 'memory.current').read_text())
|
||||
def peak():
|
||||
path = root / 'memory.peak'
|
||||
return int(path.read_text()) if path.exists() else None
|
||||
stop = threading.Event()
|
||||
threading.Thread(target=lambda: (sys.stdin.read(), stop.set()), daemon=True).start()
|
||||
initial, before = current(), peak()
|
||||
sampled = initial
|
||||
print('ready', flush=True)
|
||||
while not stop.wait(0.02):
|
||||
sampled = max(sampled, current())
|
||||
print(json.dumps({'initial_bytes': initial, 'sampled_peak_bytes': sampled,
|
||||
'cgroup_peak_before_bytes': before, 'cgroup_peak_after_bytes': peak(), 'interval_ms': 20}), flush=True)
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--concurrency', type=int, default=10)
|
||||
parser.add_argument('--rounds', type=int, default=3)
|
||||
parser.add_argument('--output', type=Path)
|
||||
args = arguments('Concurrent attachment uploads and API memory', configure)
|
||||
check(10 <= args.concurrency <= 32 and 1 <= args.rounds <= 10, 'use concurrency 10..32 and rounds 1..10')
|
||||
project = ComposeProject()
|
||||
client = Client(args.base_url, args.ca_file, timeout=65)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
random_bytes = random.Random(42).randbytes(1500 * 1500 * 3)
|
||||
image = Image.frombytes('RGB', (1500, 1500), random_bytes)
|
||||
buffer = BytesIO()
|
||||
image.save(buffer, format='PNG')
|
||||
data = buffer.getvalue()
|
||||
check(len(data) <= 10485760, 'fixture exceeds upload limit')
|
||||
monitors = []
|
||||
measurements = {}
|
||||
rows = []
|
||||
started = time.monotonic()
|
||||
try:
|
||||
for replica in project.replicas():
|
||||
process = subprocess.Popen(['docker', 'exec', '-i', replica.id, 'python', '-c', MONITOR],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
monitors.append((replica.instance_id, process))
|
||||
check(process.stdout.readline().strip() == 'ready', 'memory monitor failed')
|
||||
check(bool(monitors), 'API not running')
|
||||
for _ in range(args.rounds):
|
||||
barrier = Barrier(args.concurrency)
|
||||
def upload(index):
|
||||
local = Client(args.base_url, args.ca_file, timeout=65)
|
||||
barrier.wait(timeout=15)
|
||||
request_started = time.monotonic()
|
||||
try:
|
||||
return local.call('POST', f"/api/v1/chats/{chat['id']}/attachments?filename=load.png",
|
||||
expected=[201, 400, 401, 404, 409, 413, 415, 429, 500, 502, 503, 504], actor=alice, raw=data,
|
||||
headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
except Failure:
|
||||
# При раннем отказе сервер может закрыть ещё отправляемое тело.
|
||||
return {'status': 'failed_request', 'elapsed': time.monotonic() - request_started}
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
rows.extend(pool.map(upload, range(args.concurrency)))
|
||||
finally:
|
||||
elapsed = time.monotonic() - started
|
||||
for alias, process in monitors:
|
||||
output, _ = process.communicate(input='', timeout=10)
|
||||
check(process.returncode == 0, 'memory monitor failed')
|
||||
measurements[alias] = json.loads(output)
|
||||
succeeded = [row for row in rows if row['status'] == 201]
|
||||
check(bool(succeeded), 'all uploads were rejected')
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
for row in succeeded:
|
||||
check(row['json']['sha256'] == digest, 'upload checksum differs')
|
||||
original = client.call('GET', '/api/v1/attachments/' + row['json']['id'] + '/content', actor=alice)['bytes']
|
||||
check(hashlib.sha256(original).hexdigest() == digest, 'download checksum differs')
|
||||
latencies = sorted(row['elapsed'] for row in rows)
|
||||
result = {
|
||||
'concurrency': args.concurrency, 'rounds': args.rounds, 'attempts': len(rows),
|
||||
'fixture': {'format': 'PNG', 'width': 1500, 'height': 1500, 'size_bytes': len(data), 'sha256': digest},
|
||||
'statuses': dict(Counter(str(row['status']) for row in rows)),
|
||||
'elapsed_seconds': round(elapsed, 3), 'successful_uploads': len(succeeded),
|
||||
'p95_seconds': round(latencies[min(len(latencies) - 1, int(len(latencies) * .95))], 3),
|
||||
'memory': measurements, 'api_memory_limit': project.config['services']['api']['deploy']['resources']['limits']['memory'],
|
||||
'notes': '20 ms samples include monitor and decoder processes; cgroup peak is cumulative since container creation; 429 and failed requests counted separately; no upload retries',
|
||||
}
|
||||
encoded = json.dumps(result, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(encoded + '\n')
|
||||
print(encoded)
|
||||
check(all(row['status'] in {201, 429} for row in rows), 'unexpected HTTP/transport errors during upload experiment; inspect status counts')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -1,23 +1,27 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Full OpenAPI and JSON Schema checks; install requirements-dev.txt first."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from openapi_spec_validator import validate
|
||||
from jsonschema import Draft202012Validator
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
spec = json.loads((root/'contracts/openapi.json').read_text())
|
||||
spec = json.loads((root / "contracts/openapi.json").read_text())
|
||||
validate(spec)
|
||||
from referencing import Registry, Resource
|
||||
|
||||
# The base URI resolves local #/components references inside examples.
|
||||
resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'})
|
||||
registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource))
|
||||
for name, example in json.loads((root/'contracts/examples.json').read_text()).items():
|
||||
schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name}
|
||||
resource = dict(spec, **{"$schema": "https://json-schema.org/draft/2020-12/schema"})
|
||||
registry = Registry().with_resource(
|
||||
"urn:messenger:openapi", Resource.from_contents(resource)
|
||||
)
|
||||
for name, example in json.loads((root / "contracts/examples.json").read_text()).items():
|
||||
schema = {"$ref": "urn:messenger:openapi#/components/schemas/" + name}
|
||||
Draft202012Validator(schema, registry=registry).validate(example)
|
||||
for path in (root/'contracts').glob('*.schema.json'):
|
||||
for path in (root / "contracts").glob("*.schema.json"):
|
||||
schema = json.loads(path.read_text())
|
||||
Draft202012Validator.check_schema(schema)
|
||||
for example in schema.get('examples',[]):
|
||||
for example in schema.get("examples", []):
|
||||
Draft202012Validator(schema).validate(example)
|
||||
print('PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.')
|
||||
print("PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.")
|
||||
|
||||
@@ -132,7 +132,7 @@ async def clean_db(db_engine: AsyncEngine, redis_client: Redis) -> None:
|
||||
|
||||
def build_settings(database_url: str, **overrides: object) -> Settings:
|
||||
values: dict[str, object] = {
|
||||
# Регрессия lab3 проверяет PostgreSQL/Redis; MinIO подменяется отдельно.
|
||||
# Регрессия проверяет PostgreSQL/Redis; MinIO подменяется отдельно.
|
||||
"s3_enabled": False,
|
||||
"app_host": "127.0.0.1",
|
||||
"app_port": 8080,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Lab5: API и транзакции с реальной БД; байты S3 подменены управляемым адаптером."""
|
||||
"""API и транзакции с реальной БД; байты S3 подменены управляемым адаптером."""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
@@ -28,7 +28,7 @@ from app.storage import attachments as repository
|
||||
from app.storage.s3 import ObjectInfo
|
||||
from helpers import bearer, create_chat, create_user, idempotency_header
|
||||
|
||||
PNG = Path('tests/fixtures/sample.png').read_bytes()
|
||||
PNG = Path("tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
class MemoryStorage:
|
||||
@@ -55,12 +55,15 @@ class MemoryStorage:
|
||||
info = None
|
||||
if key in self.objects:
|
||||
data, metadata = self.objects[key]
|
||||
info = ObjectInfo(key, len(data), metadata['content_type'], datetime.now(timezone.utc))
|
||||
info = ObjectInfo(
|
||||
key, len(data), metadata["content_type"], datetime.now(timezone.utc)
|
||||
)
|
||||
return info
|
||||
|
||||
async def open_object(self, key):
|
||||
async def chunks():
|
||||
yield self.objects[key][0]
|
||||
|
||||
return chunks()
|
||||
|
||||
async def check_available(self):
|
||||
@@ -76,23 +79,40 @@ async def context(client, app):
|
||||
return storage, alice, bob, eve, chat
|
||||
|
||||
|
||||
async def upload(client, actor, chat, data=PNG, filename='фото.png', content_type='image/png'):
|
||||
async def upload(
|
||||
client, actor, chat, data=PNG, filename="фото.png", content_type="image/png"
|
||||
):
|
||||
return await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments", params={'filename': filename},
|
||||
headers={**bearer(actor), 'Content-Type': content_type}, content=data,
|
||||
f"/api/v1/chats/{chat['id']}/attachments",
|
||||
params={"filename": filename},
|
||||
headers={**bearer(actor), "Content-Type": content_type},
|
||||
content=data,
|
||||
)
|
||||
|
||||
|
||||
async def finish_attachment(client, storage, actor, attachment_id):
|
||||
engine = client._transport.app.state.engine
|
||||
async with AsyncSession(engine) as session:
|
||||
job = await session.scalar(select(AttachmentJob).where(AttachmentJob.attachment_id == UUID(attachment_id)))
|
||||
message = JobMessage(job_id=job.id, attachment_id=job.attachment_id,
|
||||
pipeline_version=job.pipeline_version, attempt=job.attempt + 1, created_at=job.created_at)
|
||||
job = await session.scalar(
|
||||
select(AttachmentJob).where(
|
||||
AttachmentJob.attachment_id == UUID(attachment_id)
|
||||
)
|
||||
)
|
||||
message = JobMessage(
|
||||
job_id=job.id,
|
||||
attachment_id=job.attachment_id,
|
||||
pipeline_version=job.pipeline_version,
|
||||
attempt=job.attempt + 1,
|
||||
created_at=job.created_at,
|
||||
)
|
||||
await session.rollback()
|
||||
assert await process_attachment_job(session, storage, message, JobSettings(_env_file=None))
|
||||
result = await client.get(f'/api/v1/attachments/{attachment_id}', headers=bearer(actor))
|
||||
assert result.json()['status'] == 'ready'
|
||||
assert await process_attachment_job(
|
||||
session, storage, message, JobSettings(_env_file=None)
|
||||
)
|
||||
result = await client.get(
|
||||
f"/api/v1/attachments/{attachment_id}", headers=bearer(actor)
|
||||
)
|
||||
assert result.json()["status"] == "ready"
|
||||
return result.json()
|
||||
|
||||
|
||||
@@ -101,37 +121,52 @@ async def test_upload_download_and_attachment_only_message(client, context):
|
||||
response = await upload(client, alice, chat)
|
||||
assert response.status_code == 202, response.text
|
||||
attachment = response.json()
|
||||
assert attachment['status'] == 'queued'
|
||||
before = await client.get(f"/api/v1/attachments/{attachment['id']}/content", headers=bearer(alice))
|
||||
assert attachment["status"] == "queued"
|
||||
before = await client.get(
|
||||
f"/api/v1/attachments/{attachment['id']}/content", headers=bearer(alice)
|
||||
)
|
||||
assert before.status_code == 409
|
||||
attachment = await finish_attachment(client, storage, alice, attachment['id'])
|
||||
assert attachment['sha256'] == hashlib.sha256(PNG).hexdigest()
|
||||
assert {v['name'] for v in attachment['variants']} == {'thumbnail', 'crop', 'optimized'}
|
||||
assert attachment['error_code'] is None
|
||||
assert 'object_key' not in attachment
|
||||
id = attachment['id']
|
||||
attachment = await finish_attachment(client, storage, alice, attachment["id"])
|
||||
assert attachment["sha256"] == hashlib.sha256(PNG).hexdigest()
|
||||
assert {v["name"] for v in attachment["variants"]} == {
|
||||
"thumbnail",
|
||||
"crop",
|
||||
"optimized",
|
||||
}
|
||||
assert attachment["error_code"] is None
|
||||
assert "object_key" not in attachment
|
||||
id = attachment["id"]
|
||||
for actor in (alice, bob):
|
||||
content = await client.get(f'/api/v1/attachments/{id}/content', headers=bearer(actor))
|
||||
content = await client.get(
|
||||
f"/api/v1/attachments/{id}/content", headers=bearer(actor)
|
||||
)
|
||||
assert content.status_code == 200 and content.content == PNG
|
||||
assert content.headers['content-type'] == 'image/png'
|
||||
assert content.headers["content-type"] == "image/png"
|
||||
key = idempotency_header()
|
||||
body = {'text': '', 'attachment_ids': [id]}
|
||||
body = {"text": "", "attachment_ids": [id]}
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
message = await client.post(path, json=body, headers={**bearer(bob), **key})
|
||||
assert message.status_code == 201, message.text
|
||||
repeat = await client.post(path, json=body, headers={**bearer(bob), **key})
|
||||
assert repeat.json() == message.json()
|
||||
history = await client.get(path, headers=bearer(alice))
|
||||
assert history.json()['items'][0]['attachment_ids'] == [id]
|
||||
for suffix in ('', '/content'):
|
||||
denied = await client.get(f'/api/v1/attachments/{id}{suffix}', headers=bearer(eve))
|
||||
assert history.json()["items"][0]["attachment_ids"] == [id]
|
||||
for suffix in ("", "/content"):
|
||||
denied = await client.get(
|
||||
f"/api/v1/attachments/{id}{suffix}", headers=bearer(eve)
|
||||
)
|
||||
assert denied.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'data,content_type',
|
||||
[(b'not an image', 'image/png'), (PNG[:30], 'image/png'), (PNG, 'image/jpeg'), (PNG, 'application/octet-stream')],
|
||||
ids=['not-image', 'truncated-png', 'mime-spoofing', 'unsupported-type'],
|
||||
"data,content_type",
|
||||
[
|
||||
(b"not an image", "image/png"),
|
||||
(PNG[:30], "image/png"),
|
||||
(PNG, "image/jpeg"),
|
||||
(PNG, "application/octet-stream"),
|
||||
],
|
||||
ids=["not-image", "truncated-png", "mime-spoofing", "unsupported-type"],
|
||||
)
|
||||
async def test_invalid_image_and_mime_are_415(client, context, data, content_type):
|
||||
storage, alice, _, _, chat = context
|
||||
@@ -143,17 +178,21 @@ async def test_invalid_image_and_mime_are_415(client, context, data, content_typ
|
||||
async def test_jpeg_is_stored_without_reencoding(client, context):
|
||||
storage, alice, _, _, chat = context
|
||||
output = BytesIO()
|
||||
Image.new('RGB', (32, 32), 'blue').save(output, format='JPEG')
|
||||
Image.new("RGB", (32, 32), "blue").save(output, format="JPEG")
|
||||
original = output.getvalue()
|
||||
response = await upload(client, alice, chat, original, content_type='image/jpeg')
|
||||
response = await upload(client, alice, chat, original, content_type="image/jpeg")
|
||||
assert response.status_code == 202, response.text
|
||||
id = response.json()['id']
|
||||
id = response.json()["id"]
|
||||
await finish_attachment(client, storage, alice, id)
|
||||
downloaded = await client.get(f'/api/v1/attachments/{id}/content', headers=bearer(alice))
|
||||
downloaded = await client.get(
|
||||
f"/api/v1/attachments/{id}/content", headers=bearer(alice)
|
||||
)
|
||||
assert downloaded.content == original
|
||||
|
||||
|
||||
@pytest.mark.parametrize('filename', ['../a.png', 'a\\b.png', 'a\x00.png', 'a\n.png', 'x' * 256])
|
||||
@pytest.mark.parametrize(
|
||||
"filename", ["../a.png", "a\\b.png", "a\x00.png", "a\n.png", "x" * 256]
|
||||
)
|
||||
async def test_unsafe_filename_is_400(client, context, filename):
|
||||
storage, alice, _, _, chat = context
|
||||
response = await upload(client, alice, chat, filename=filename)
|
||||
@@ -163,9 +202,11 @@ async def test_unsafe_filename_is_400(client, context, filename):
|
||||
|
||||
async def test_oversize_chunked_upload_is_413(client, context):
|
||||
storage, alice, _, _, chat = context
|
||||
|
||||
async def chunks():
|
||||
for _ in range(11):
|
||||
yield b'x' * 1048576
|
||||
yield b"x" * 1048576
|
||||
|
||||
response = await upload(client, alice, chat, chunks())
|
||||
assert response.status_code == 413
|
||||
assert not storage.objects
|
||||
@@ -175,7 +216,12 @@ async def test_oversize_content_length_is_413(client, context):
|
||||
_, alice, _, _, chat = context
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=a.png",
|
||||
headers={**bearer(alice), 'Content-Type': 'image/png', 'Content-Length': '10485761'}, content=PNG,
|
||||
headers={
|
||||
**bearer(alice),
|
||||
"Content-Type": "image/png",
|
||||
"Content-Length": "10485761",
|
||||
},
|
||||
content=PNG,
|
||||
)
|
||||
assert response.status_code == 413
|
||||
|
||||
@@ -185,30 +231,47 @@ async def test_exact_byte_limit_accepts_valid_png(client, context):
|
||||
maximum = 10_485_760
|
||||
# Валидный ancillary chunk вместо данных после IEND.
|
||||
payload = bytes(maximum - len(PNG) - 12)
|
||||
kind = b'npAD'
|
||||
padding = struct.pack('!I', len(payload)) + kind + payload + struct.pack('!I', zlib.crc32(kind + payload))
|
||||
kind = b"npAD"
|
||||
padding = (
|
||||
struct.pack("!I", len(payload))
|
||||
+ kind
|
||||
+ payload
|
||||
+ struct.pack("!I", zlib.crc32(kind + payload))
|
||||
)
|
||||
image = PNG[:-12] + padding + PNG[-12:]
|
||||
response = await upload(client, alice, chat, image)
|
||||
assert response.status_code == 202, response.text
|
||||
assert response.json()['size_bytes'] == maximum
|
||||
assert response.json()['sha256'] == hashlib.sha256(image).hexdigest()
|
||||
assert response.json()["size_bytes"] == maximum
|
||||
assert response.json()["sha256"] == hashlib.sha256(image).hexdigest()
|
||||
|
||||
|
||||
async def test_exact_pixel_limit_accepts_valid_png(client, context):
|
||||
_, alice, _, _, chat = context
|
||||
output = BytesIO()
|
||||
with Image.new('RGB', (8000, 5000), 'blue') as image:
|
||||
image.save(output, format='PNG')
|
||||
with Image.new("RGB", (8000, 5000), "blue") as image:
|
||||
image.save(output, format="PNG")
|
||||
response = await upload(client, alice, chat, output.getvalue())
|
||||
assert response.status_code == 202, response.text
|
||||
|
||||
|
||||
async def test_pixel_limit_before_decoding(client, context):
|
||||
_, alice, _, _, chat = context
|
||||
|
||||
def chunk(kind, data):
|
||||
return struct.pack('!I', len(data)) + kind + data + struct.pack('!I', zlib.crc32(kind + data))
|
||||
header = struct.pack('!IIBBBBB', 8000, 5001, 8, 2, 0, 0, 0)
|
||||
image = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', header) + chunk(b'IDAT', zlib.compress(b'\0')) + chunk(b'IEND', b'')
|
||||
return (
|
||||
struct.pack("!I", len(data))
|
||||
+ kind
|
||||
+ data
|
||||
+ struct.pack("!I", zlib.crc32(kind + data))
|
||||
)
|
||||
|
||||
header = struct.pack("!IIBBBBB", 8000, 5001, 8, 2, 0, 0, 0)
|
||||
image = (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", header)
|
||||
+ chunk(b"IDAT", zlib.compress(b"\0"))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
response = await upload(client, alice, chat, image)
|
||||
assert response.status_code == 413, response.text
|
||||
|
||||
@@ -217,10 +280,10 @@ async def test_unknown_and_other_chat_attachment_are_404(client, context):
|
||||
_, alice, bob, _, chat = context
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
other_chat = await create_chat(client, alice, bob)
|
||||
for id in (attachment['id'], str(uuid4())):
|
||||
for id in (attachment["id"], str(uuid4())):
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{other_chat['id']}/messages",
|
||||
json={'text': '', 'attachment_ids': [id]},
|
||||
json={"text": "", "attachment_ids": [id]},
|
||||
headers={**bearer(alice), **idempotency_header()},
|
||||
)
|
||||
assert response.status_code == 404
|
||||
@@ -228,10 +291,12 @@ async def test_unknown_and_other_chat_attachment_are_404(client, context):
|
||||
|
||||
async def test_duplicate_ids_are_400(client, context):
|
||||
_, alice, _, _, chat = context
|
||||
id = (await upload(client, alice, chat)).json()['id']
|
||||
response = await client.post(f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={'text': '', 'attachment_ids': [id, id]},
|
||||
headers={**bearer(alice), **idempotency_header()})
|
||||
id = (await upload(client, alice, chat)).json()["id"]
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "", "attachment_ids": [id, id]},
|
||||
headers={**bearer(alice), **idempotency_header()},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
@@ -239,20 +304,24 @@ async def test_empty_ids_and_absent_ids_have_same_idempotency(client, context):
|
||||
_, alice, _, _, chat = context
|
||||
headers = {**bearer(alice), **idempotency_header()}
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
first = await client.post(path, json={'text': 'same'}, headers=headers)
|
||||
second = await client.post(path, json={'text': 'same', 'attachment_ids': []}, headers=headers)
|
||||
first = await client.post(path, json={"text": "same"}, headers=headers)
|
||||
second = await client.post(
|
||||
path, json={"text": "same", "attachment_ids": []}, headers=headers
|
||||
)
|
||||
assert first.status_code == second.status_code == 201
|
||||
assert first.json() == second.json()
|
||||
|
||||
|
||||
async def test_s3_outage_is_503(client, context):
|
||||
storage, alice, _, _, chat = context
|
||||
id = (await upload(client, alice, chat)).json()['id']
|
||||
id = (await upload(client, alice, chat)).json()["id"]
|
||||
await finish_attachment(client, storage, alice, id)
|
||||
storage.down = True
|
||||
response = await client.get(f'/api/v1/attachments/{id}/content', headers=bearer(alice))
|
||||
response = await client.get(
|
||||
f"/api/v1/attachments/{id}/content", headers=bearer(alice)
|
||||
)
|
||||
assert response.status_code == 503
|
||||
assert (await client.get('/health/ready')).status_code == 503
|
||||
assert (await client.get("/health/ready")).status_code == 503
|
||||
|
||||
|
||||
async def test_uncertain_put_is_compensated(client, context, db_engine):
|
||||
@@ -267,25 +336,31 @@ async def test_uncertain_put_is_compensated(client, context, db_engine):
|
||||
|
||||
async def test_failure_after_s3_write_compensates(client, context, monkeypatch):
|
||||
storage, alice, _, _, chat = context
|
||||
|
||||
async def fail(*args, **kwargs):
|
||||
raise OperationalError('injected', {}, None)
|
||||
monkeypatch.setattr(repository, 'create_attachment', fail)
|
||||
raise OperationalError("injected", {}, None)
|
||||
|
||||
monkeypatch.setattr(repository, "create_attachment", fail)
|
||||
response = await upload(client, alice, chat)
|
||||
assert response.status_code == 503
|
||||
assert not storage.objects
|
||||
|
||||
|
||||
async def test_ambiguous_successful_commit_keeps_original(client, context, db_engine, monkeypatch):
|
||||
async def test_ambiguous_successful_commit_keeps_original(
|
||||
client, context, db_engine, monkeypatch
|
||||
):
|
||||
storage, alice, _, _, chat = context
|
||||
original = AsyncSession.commit
|
||||
count = 0
|
||||
|
||||
async def uncertain(session):
|
||||
nonlocal count
|
||||
count += 1
|
||||
await original(session)
|
||||
if count == 2:
|
||||
raise OperationalError('lost commit acknowledgement', {}, None)
|
||||
monkeypatch.setattr(AsyncSession, 'commit', uncertain)
|
||||
raise OperationalError("lost commit acknowledgement", {}, None)
|
||||
|
||||
monkeypatch.setattr(AsyncSession, "commit", uncertain)
|
||||
response = await upload(client, alice, chat)
|
||||
assert response.status_code == 503
|
||||
assert len(storage.objects) == 1
|
||||
@@ -318,10 +393,16 @@ async def test_cleanup_keeps_fresh_and_skips_locked_uploads(client, context, db_
|
||||
storage, _, _, _, _ = context
|
||||
old_id, fresh_id = uuid4(), uuid4()
|
||||
async with AsyncSession(db_engine) as session:
|
||||
session.add_all([
|
||||
UploadIntent(id=old_id, object_key='originals/old', created_at=datetime.now(timezone.utc) - timedelta(days=2)),
|
||||
UploadIntent(id=fresh_id, object_key='originals/fresh'),
|
||||
])
|
||||
session.add_all(
|
||||
[
|
||||
UploadIntent(
|
||||
id=old_id,
|
||||
object_key="originals/old",
|
||||
created_at=datetime.now(timezone.utc) - timedelta(days=2),
|
||||
),
|
||||
UploadIntent(id=fresh_id, object_key="originals/fresh"),
|
||||
]
|
||||
)
|
||||
await session.commit()
|
||||
async with AsyncSession(db_engine) as uploader, AsyncSession(db_engine) as cleaner:
|
||||
await repository.lock_upload(uploader, old_id)
|
||||
@@ -335,9 +416,11 @@ async def test_cleanup_keeps_fresh_and_skips_locked_uploads(client, context, db_
|
||||
|
||||
async def test_client_disconnect_before_put_has_no_side_effects(client, context):
|
||||
storage, alice, _, _, chat = context
|
||||
|
||||
async def interrupted():
|
||||
yield PNG[:16]
|
||||
raise ClientDisconnect()
|
||||
|
||||
response = await upload(client, alice, chat, interrupted())
|
||||
assert response.status_code == 400
|
||||
assert not storage.objects
|
||||
@@ -345,10 +428,14 @@ async def test_client_disconnect_before_put_has_no_side_effects(client, context)
|
||||
|
||||
async def test_upload_deadline_cancels_validation(client, context, monkeypatch):
|
||||
storage, alice, _, _, chat = context
|
||||
storage.settings = storage.settings.model_copy(update={'upload_timeout_seconds': 0.02})
|
||||
storage.settings = storage.settings.model_copy(
|
||||
update={"upload_timeout_seconds": 0.02}
|
||||
)
|
||||
|
||||
async def stalled(*args):
|
||||
await asyncio.sleep(10)
|
||||
monkeypatch.setattr(domain, 'validate_image', stalled)
|
||||
|
||||
monkeypatch.setattr(domain, "validate_image", stalled)
|
||||
response = await upload(client, alice, chat)
|
||||
assert response.status_code == 400
|
||||
assert not storage.objects
|
||||
@@ -358,11 +445,13 @@ async def test_cancelled_put_is_compensated(client, context, db_engine, monkeypa
|
||||
storage, alice, _, _, chat = context
|
||||
entered = asyncio.Event()
|
||||
original = storage.put_file
|
||||
|
||||
async def interrupted(*args, **kwargs):
|
||||
await original(*args, **kwargs)
|
||||
entered.set()
|
||||
await asyncio.sleep(10)
|
||||
monkeypatch.setattr(storage, 'put_file', interrupted)
|
||||
|
||||
monkeypatch.setattr(storage, "put_file", interrupted)
|
||||
task = asyncio.create_task(upload(client, alice, chat))
|
||||
await asyncio.wait_for(entered.wait(), timeout=10)
|
||||
task.cancel()
|
||||
@@ -375,14 +464,19 @@ async def test_cancelled_put_is_compensated(client, context, db_engine, monkeypa
|
||||
|
||||
async def test_cleanup_never_deletes_ready_attachment(client, context, db_engine):
|
||||
storage, alice, _, _, chat = context
|
||||
id = (await upload(client, alice, chat)).json()['id']
|
||||
id = (await upload(client, alice, chat)).json()["id"]
|
||||
await finish_attachment(client, storage, alice, id)
|
||||
async with AsyncSession(db_engine) as session:
|
||||
attachment = await session.get(Attachment, UUID(id))
|
||||
key = attachment.object_key
|
||||
# Искусственно оставляем старый журнал у уже подтверждённого объекта.
|
||||
session.add(UploadIntent(id=uuid4(), object_key=key,
|
||||
created_at=datetime.now(timezone.utc) - timedelta(days=2)))
|
||||
session.add(
|
||||
UploadIntent(
|
||||
id=uuid4(),
|
||||
object_key=key,
|
||||
created_at=datetime.now(timezone.utc) - timedelta(days=2),
|
||||
)
|
||||
)
|
||||
await session.commit()
|
||||
result = await domain.reconcile_attachments(session, storage, dry_run=False)
|
||||
assert result.examined == 1 and result.deleted == 0
|
||||
|
||||
@@ -8,7 +8,14 @@ from sqlalchemy import text
|
||||
|
||||
from app.main import create_app
|
||||
from conftest import close_app, make_client
|
||||
from helpers import PASSWORD, basic_header, bearer, create_user, idempotency_header, register
|
||||
from helpers import (
|
||||
PASSWORD,
|
||||
basic_header,
|
||||
bearer,
|
||||
create_user,
|
||||
idempotency_header,
|
||||
register,
|
||||
)
|
||||
|
||||
|
||||
async def test_parallel_registration_of_same_username_creates_exactly_one_user(
|
||||
|
||||
@@ -29,14 +29,12 @@ async def seed_messages(
|
||||
) -> None:
|
||||
async with engine.begin() as connection:
|
||||
await connection.execute(
|
||||
text(
|
||||
"""
|
||||
text("""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(), :chat_id, :sender_id, 'message ' || g,
|
||||
now() - make_interval(secs => :count - g)
|
||||
FROM generate_series(1, :count) AS g
|
||||
"""
|
||||
),
|
||||
"""),
|
||||
{"chat_id": chat_id, "sender_id": sender_id, "count": count},
|
||||
)
|
||||
await connection.execute(text("ANALYZE messages"))
|
||||
|
||||
@@ -16,10 +16,15 @@ from helpers import bearer, create_chat, create_user, idempotency_header, send_m
|
||||
@pytest.fixture
|
||||
async def replicas(request, make_settings):
|
||||
overrides = getattr(request, "param", {})
|
||||
apps = [create_app(make_settings(instance_id=name, **overrides)) for name in ("api-a", "api-b")]
|
||||
apps = [
|
||||
create_app(make_settings(instance_id=name, **overrides))
|
||||
for name in ("api-a", "api-b")
|
||||
]
|
||||
try:
|
||||
async with AsyncExitStack() as stack:
|
||||
clients = [await stack.enter_async_context(make_client(app)) for app in apps]
|
||||
clients = [
|
||||
await stack.enter_async_context(make_client(app)) for app in apps
|
||||
]
|
||||
yield clients
|
||||
finally:
|
||||
for app in apps:
|
||||
@@ -54,7 +59,11 @@ async def test_replay_and_conflict_across_replicas(replicas, db_engine):
|
||||
original = await send_message(first, user, chat, "Привет", "same-key")
|
||||
repeated = await second.post(
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
headers={**bearer(user), **idempotency_header("same-key"), "Content-Type": "application/json"},
|
||||
headers={
|
||||
**bearer(user),
|
||||
**idempotency_header("same-key"),
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
content='{ "text" : "\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442" }',
|
||||
)
|
||||
conflict = await send_message(second, user, chat, "другой текст", "same-key")
|
||||
@@ -63,23 +72,38 @@ async def test_replay_and_conflict_across_replicas(replicas, db_engine):
|
||||
assert original.headers["X-Instance-Id"] != repeated.headers["X-Instance-Id"]
|
||||
assert conflict.status_code == 409
|
||||
async with db_engine.connect() as connection:
|
||||
assert (await connection.execute(text("SELECT count(*) FROM messages"))).scalar_one() == 1
|
||||
assert (await connection.execute(text("SELECT value FROM counters WHERE name='messages'"))).scalar_one() == 1
|
||||
assert (
|
||||
await connection.execute(text("SELECT count(*) FROM messages"))
|
||||
).scalar_one() == 1
|
||||
assert (
|
||||
await connection.execute(
|
||||
text("SELECT value FROM counters WHERE name='messages'")
|
||||
)
|
||||
).scalar_one() == 1
|
||||
|
||||
|
||||
async def test_parallel_replays_create_one_message(replicas, db_engine):
|
||||
user = await create_user(replicas[0])
|
||||
chat = await create_chat(replicas[0], user)
|
||||
responses = await asyncio.gather(*(
|
||||
send_message(replicas[index % 2], user, chat, "parallel", "one-key")
|
||||
for index in range(24)
|
||||
))
|
||||
responses = await asyncio.gather(
|
||||
*(
|
||||
send_message(replicas[index % 2], user, chat, "parallel", "one-key")
|
||||
for index in range(24)
|
||||
)
|
||||
)
|
||||
assert all(response.status_code == 201 for response in responses)
|
||||
assert len({response.json()["id"] for response in responses}) == 1
|
||||
assert {response.headers["X-Instance-Id"] for response in responses} == {"api-a", "api-b"}
|
||||
assert {response.headers["X-Instance-Id"] for response in responses} == {
|
||||
"api-a",
|
||||
"api-b",
|
||||
}
|
||||
async with db_engine.connect() as connection:
|
||||
assert (await connection.execute(text("SELECT count(*) FROM messages"))).scalar_one() == 1
|
||||
assert (await connection.execute(text("SELECT count(*) FROM idempotency_keys"))).scalar_one() == 1
|
||||
assert (
|
||||
await connection.execute(text("SELECT count(*) FROM messages"))
|
||||
).scalar_one() == 1
|
||||
assert (
|
||||
await connection.execute(text("SELECT count(*) FROM idempotency_keys"))
|
||||
).scalar_one() == 1
|
||||
|
||||
|
||||
async def test_key_scope_separates_users_and_chats(client):
|
||||
@@ -101,9 +125,11 @@ async def test_expired_key_can_be_reused_without_removing_message(client, db_eng
|
||||
chat = await create_chat(client, user)
|
||||
first = await send_message(client, user, chat, "old", "expiring-key")
|
||||
async with db_engine.begin() as connection:
|
||||
await connection.execute(text(
|
||||
"UPDATE idempotency_keys SET created_at = clock_timestamp() - interval '25 hours'"
|
||||
))
|
||||
await connection.execute(
|
||||
text(
|
||||
"UPDATE idempotency_keys SET created_at = clock_timestamp() - interval '25 hours'"
|
||||
)
|
||||
)
|
||||
second = await send_message(client, user, chat, "new", "expiring-key")
|
||||
assert first.status_code == second.status_code == 201
|
||||
assert first.json()["id"] != second.json()["id"]
|
||||
@@ -127,7 +153,9 @@ async def test_failed_transaction_does_not_poison_key(client, db_engine, monkeyp
|
||||
assert failed.status_code == 503
|
||||
async with db_engine.connect() as connection:
|
||||
for table in ("messages", "idempotency_keys", "counters"):
|
||||
assert (await connection.execute(text(f"SELECT count(*) FROM {table}"))).scalar_one() == 0
|
||||
assert (
|
||||
await connection.execute(text(f"SELECT count(*) FROM {table}"))
|
||||
).scalar_one() == 0
|
||||
monkeypatch.setattr(key_storage, "save_result", original)
|
||||
recovered = await send_message(client, user, chat, "retry", "retry-key")
|
||||
assert recovered.status_code == 201
|
||||
@@ -148,9 +176,15 @@ async def test_replay_works_when_message_limit_is_full(replicas):
|
||||
async def test_replay_checks_session_and_membership(client, db_engine):
|
||||
user = await create_user(client)
|
||||
chat = await create_chat(client, user)
|
||||
assert (await send_message(client, user, chat, "private", "private-key")).status_code == 201
|
||||
assert (
|
||||
await send_message(client, user, chat, "private", "private-key")
|
||||
).status_code == 201
|
||||
async with db_engine.begin() as connection:
|
||||
await connection.execute(text("DELETE FROM chat_members"))
|
||||
assert (await send_message(client, user, chat, "private", "private-key")).status_code == 404
|
||||
assert (
|
||||
await send_message(client, user, chat, "private", "private-key")
|
||||
).status_code == 404
|
||||
await client.delete("/api/v1/auth/sessions/current", headers=bearer(user))
|
||||
assert (await send_message(client, user, chat, "private", "private-key")).status_code == 401
|
||||
assert (
|
||||
await send_message(client, user, chat, "private", "private-key")
|
||||
).status_code == 401
|
||||
|
||||
@@ -18,54 +18,96 @@ from app.storage.jobs import JobWork
|
||||
from test_attachments import MemoryStorage
|
||||
|
||||
|
||||
@pytest.mark.parametrize('size,transparent', [((1600,800),False),((24,12),True)])
|
||||
async def test_variant_geometry_metadata_and_alpha(tmp_path,size,transparent):
|
||||
source=tmp_path/'source.png'
|
||||
with Image.new('RGBA',size,(255,0,0,0 if transparent else 255)) as image:
|
||||
exif=Image.Exif();exif[270]='private description'
|
||||
image.save(source,format='PNG',exif=exif)
|
||||
result=create_variants(source,tmp_path,'image/png',40_000_000,ImageSettings(_env_file=None))
|
||||
variants={v.name:v for v in result.variants}
|
||||
assert (variants['crop'].width,variants['crop'].height)==(128,128)
|
||||
assert (variants['thumbnail'].width,variants['thumbnail'].height)==((256,128) if size[0]>256 else size)
|
||||
assert (variants['optimized'].width,variants['optimized'].height)==((1280,640) if size[0]>1280 else size)
|
||||
for name in ('thumbnail.jpg','crop.jpg','optimized.webp'):
|
||||
with Image.open(tmp_path/name) as image:
|
||||
assert not image.getexif() and not image.info.get('icc_profile') and not image.info.get('xmp')
|
||||
@pytest.mark.parametrize("size,transparent", [((1600, 800), False), ((24, 12), True)])
|
||||
async def test_variant_geometry_metadata_and_alpha(tmp_path, size, transparent):
|
||||
source = tmp_path / "source.png"
|
||||
with Image.new("RGBA", size, (255, 0, 0, 0 if transparent else 255)) as image:
|
||||
exif = Image.Exif()
|
||||
exif[270] = "private description"
|
||||
image.save(source, format="PNG", exif=exif)
|
||||
result = create_variants(
|
||||
source, tmp_path, "image/png", 40_000_000, ImageSettings(_env_file=None)
|
||||
)
|
||||
variants = {v.name: v for v in result.variants}
|
||||
assert (variants["crop"].width, variants["crop"].height) == (128, 128)
|
||||
assert (variants["thumbnail"].width, variants["thumbnail"].height) == (
|
||||
(256, 128) if size[0] > 256 else size
|
||||
)
|
||||
assert (variants["optimized"].width, variants["optimized"].height) == (
|
||||
(1280, 640) if size[0] > 1280 else size
|
||||
)
|
||||
for name in ("thumbnail.jpg", "crop.jpg", "optimized.webp"):
|
||||
with Image.open(tmp_path / name) as image:
|
||||
assert (
|
||||
not image.getexif()
|
||||
and not image.info.get("icc_profile")
|
||||
and not image.info.get("xmp")
|
||||
)
|
||||
if transparent:
|
||||
if name.endswith('webp'):assert image.getpixel((0,0))[3]==0
|
||||
else:assert min(image.getpixel((0,0)))>=250
|
||||
if name.endswith("webp"):
|
||||
assert image.getpixel((0, 0))[3] == 0
|
||||
else:
|
||||
assert min(image.getpixel((0, 0))) >= 250
|
||||
|
||||
|
||||
async def test_exif_orientation_applied(tmp_path):
|
||||
source=tmp_path/'source.jpg'
|
||||
with Image.new('RGB',(400,200),'blue') as image:
|
||||
exif=Image.Exif();exif[274]=6
|
||||
image.save(source,exif=exif)
|
||||
result=create_variants(source,tmp_path,'image/jpeg',40_000_000,ImageSettings(_env_file=None))
|
||||
assert (result.variants[0].width,result.variants[0].height)==(128,256)
|
||||
source = tmp_path / "source.jpg"
|
||||
with Image.new("RGB", (400, 200), "blue") as image:
|
||||
exif = Image.Exif()
|
||||
exif[274] = 6
|
||||
image.save(source, exif=exif)
|
||||
result = create_variants(
|
||||
source, tmp_path, "image/jpeg", 40_000_000, ImageSettings(_env_file=None)
|
||||
)
|
||||
assert (result.variants[0].width, result.variants[0].height) == (128, 256)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['memory','cpu'])
|
||||
async def test_worker_os_limits(failure,tmp_path):
|
||||
body='return bytearray(2 * 1024 ** 3)' if failure=='memory' else 'while True: pass'
|
||||
code="from app.core import thumbnail_worker as w\ndef fail(*args):\n "+body+"\nw.create_variants=fail\nraise SystemExit(w.main())"
|
||||
result=await asyncio.to_thread(subprocess.run,[sys.executable,'-c',code,'source',str(tmp_path),str(tmp_path/'metadata'),'image/png','40000000'],
|
||||
env={**os.environ,'IMAGE_MEMORY_MIB':'256','IMAGE_CPU_SECONDS':'1'},capture_output=True,timeout=15)
|
||||
assert result.returncode==(3 if failure=='memory' else -9)
|
||||
assert not (tmp_path/'metadata').exists()
|
||||
@pytest.mark.parametrize("failure", ["memory", "cpu"])
|
||||
async def test_worker_os_limits(failure, tmp_path):
|
||||
body = (
|
||||
"return bytearray(2 * 1024 ** 3)" if failure == "memory" else "while True: pass"
|
||||
)
|
||||
code = (
|
||||
"from app.core import thumbnail_worker as w\ndef fail(*args):\n "
|
||||
+ body
|
||||
+ "\nw.create_variants=fail\nraise SystemExit(w.main())"
|
||||
)
|
||||
result = await asyncio.to_thread(
|
||||
subprocess.run,
|
||||
[
|
||||
sys.executable,
|
||||
"-c",
|
||||
code,
|
||||
"source",
|
||||
str(tmp_path),
|
||||
str(tmp_path / "metadata"),
|
||||
"image/png",
|
||||
"40000000",
|
||||
],
|
||||
env={**os.environ, "IMAGE_MEMORY_MIB": "256", "IMAGE_CPU_SECONDS": "1"},
|
||||
capture_output=True,
|
||||
timeout=15,
|
||||
)
|
||||
assert result.returncode == (3 if failure == "memory" else -9)
|
||||
assert not (tmp_path / "metadata").exists()
|
||||
|
||||
|
||||
async def test_render_timeout_kills_child(monkeypatch,tmp_path):
|
||||
create=asyncio.create_subprocess_exec
|
||||
children=[]
|
||||
async def slow_child(*args,**kwargs):
|
||||
child=await create(sys.executable,'-c','import time;time.sleep(60)',**kwargs)
|
||||
async def test_render_timeout_kills_child(monkeypatch, tmp_path):
|
||||
create = asyncio.create_subprocess_exec
|
||||
children = []
|
||||
|
||||
async def slow_child(*args, **kwargs):
|
||||
child = await create(
|
||||
sys.executable, "-c", "import time;time.sleep(60)", **kwargs
|
||||
)
|
||||
children.append(child)
|
||||
return child
|
||||
monkeypatch.setattr(asyncio,'create_subprocess_exec',slow_child)
|
||||
work=JobWork(uuid4(),uuid4(),uuid4(),1,'staging/test','image/png',1,'0'*64)
|
||||
|
||||
monkeypatch.setattr(asyncio, "create_subprocess_exec", slow_child)
|
||||
work = JobWork(
|
||||
uuid4(), uuid4(), uuid4(), 1, "staging/test", "image/png", 1, "0" * 64
|
||||
)
|
||||
with pytest.raises(TimeoutError):
|
||||
async with asyncio.timeout(.2):
|
||||
await render_variants(MemoryStorage(),work,tmp_path/'source',tmp_path)
|
||||
assert len(children)==1 and children[0].returncode is not None
|
||||
async with asyncio.timeout(0.2):
|
||||
await render_variants(MemoryStorage(), work, tmp_path / "source", tmp_path)
|
||||
assert len(children) == 1 and children[0].returncode is not None
|
||||
|
||||
@@ -92,7 +92,9 @@ async def test_instance_header_is_present_on_success_and_errors(
|
||||
assert response.headers["X-Instance-Id"] == "api-test"
|
||||
assert response.headers["X-Request-Id"]
|
||||
if status >= 400:
|
||||
assert response.json()["error"]["request_id"] == response.headers["X-Request-Id"]
|
||||
assert (
|
||||
response.json()["error"]["request_id"] == response.headers["X-Request-Id"]
|
||||
)
|
||||
|
||||
|
||||
async def test_instance_id_is_stable_while_request_ids_are_distinct(instance_client):
|
||||
@@ -100,7 +102,9 @@ async def test_instance_id_is_stable_while_request_ids_are_distinct(instance_cli
|
||||
second = await instance_client.get("/__test__/request-id")
|
||||
|
||||
assert first.status_code == second.status_code == 200
|
||||
assert first.headers["X-Instance-Id"] == second.headers["X-Instance-Id"] == "api-test"
|
||||
assert (
|
||||
first.headers["X-Instance-Id"] == second.headers["X-Instance-Id"] == "api-test"
|
||||
)
|
||||
assert first.headers["X-Request-Id"] != second.headers["X-Request-Id"]
|
||||
for response in (first, second):
|
||||
assert response.json()["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
+138
-49
@@ -1,4 +1,4 @@
|
||||
"""Lab5: retry/replay, fencing, cleanup, limits и транзакции реального PostgreSQL."""
|
||||
"""Retry/replay, fencing, cleanup, limits и транзакции реального PostgreSQL."""
|
||||
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
@@ -13,7 +13,12 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.jobs import JobSettings
|
||||
from app.domain import attachment_jobs
|
||||
from app.domain.attachment_jobs import claim_job, process_attachment_job, cleanup_staging, build_result
|
||||
from app.domain.attachment_jobs import (
|
||||
claim_job,
|
||||
process_attachment_job,
|
||||
cleanup_staging,
|
||||
build_result,
|
||||
)
|
||||
from app.domain.job_admin import replay_failed_job
|
||||
from app.domain.job_retry import classify_failure, retry_delay
|
||||
from app.errors.exceptions import JobOperationError, ProcessingError
|
||||
@@ -26,50 +31,85 @@ from test_attachments import context, upload, finish_attachment
|
||||
|
||||
|
||||
async def envelope(session, attachment_id):
|
||||
job = await session.scalar(select(AttachmentJob).where(AttachmentJob.attachment_id == UUID(attachment_id)))
|
||||
return JobMessage(job_id=job.id, attachment_id=job.attachment_id, pipeline_version=1,
|
||||
attempt=job.attempt + 1, created_at=job.created_at)
|
||||
job = await session.scalar(
|
||||
select(AttachmentJob).where(AttachmentJob.attachment_id == UUID(attachment_id))
|
||||
)
|
||||
return JobMessage(
|
||||
job_id=job.id,
|
||||
attachment_id=job.attachment_id,
|
||||
pipeline_version=1,
|
||||
attempt=job.attempt + 1,
|
||||
created_at=job.created_at,
|
||||
)
|
||||
|
||||
|
||||
async def test_retry_budget_backoff_replay_and_duplicate(client, context, db_engine):
|
||||
storage, alice, _, _, chat = context
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
settings = JobSettings(_env_file=None, job_max_attempts=3)
|
||||
|
||||
def fail(_):
|
||||
raise TimeoutError
|
||||
|
||||
async with AsyncSession(db_engine, expire_on_commit=False) as session:
|
||||
first = await envelope(session, attachment['id'])
|
||||
first = await envelope(session, attachment["id"])
|
||||
for attempt in range(1, 4):
|
||||
message = await envelope(session, attachment['id'])
|
||||
assert await process_attachment_job(session, storage, message, settings, before_processing=fail)
|
||||
message = await envelope(session, attachment["id"])
|
||||
assert await process_attachment_job(
|
||||
session, storage, message, settings, before_processing=fail
|
||||
)
|
||||
job, item = await jobs.lock_job(session, first.job_id)
|
||||
assert job.attempt == attempt
|
||||
delay = (job.next_attempt_at - item.updated_at).total_seconds()
|
||||
assert 5 * 2 ** (attempt - 1) / 2 <= delay <= 5 * 2 ** (attempt - 1)
|
||||
assert item.status == ('failed' if attempt == 3 else 'queued')
|
||||
assert item.status == ("failed" if attempt == 3 else "queued")
|
||||
assert job.last_error_permanent is False
|
||||
job.next_attempt_at = await jobs.database_time(session) - timedelta(seconds=1)
|
||||
job.next_attempt_at = await jobs.database_time(session) - timedelta(
|
||||
seconds=1
|
||||
)
|
||||
await session.commit()
|
||||
assert item.error_code == 'retry_exhausted'
|
||||
assert item.error_code == "retry_exhausted"
|
||||
request_id = uuid4()
|
||||
result = await replay_failed_job(session, storage, settings, first.job_id, request_id=request_id,
|
||||
actor='test', reason='dependency_restored')
|
||||
assert result['attempt_limit'] == 6
|
||||
result = await replay_failed_job(
|
||||
session,
|
||||
storage,
|
||||
settings,
|
||||
first.job_id,
|
||||
request_id=request_id,
|
||||
actor="test",
|
||||
reason="dependency_restored",
|
||||
)
|
||||
assert result["attempt_limit"] == 6
|
||||
# Old envelope cannot consume the fresh replay budget.
|
||||
assert await process_attachment_job(session, storage, first, settings)
|
||||
job, item = await jobs.lock_job(session, first.job_id)
|
||||
assert job.attempt == 3 and item.status == 'queued'
|
||||
assert job.attempt == 3 and item.status == "queued"
|
||||
await session.commit()
|
||||
message = await envelope(session, attachment['id'])
|
||||
message = await envelope(session, attachment["id"])
|
||||
assert await process_attachment_job(session, storage, message, settings)
|
||||
before = dict(storage.objects)
|
||||
assert await process_attachment_job(session, storage, message, settings)
|
||||
assert storage.objects == before
|
||||
repeat = await replay_failed_job(session, storage, settings, first.job_id, request_id=request_id,
|
||||
actor='test', reason='dependency_restored')
|
||||
assert repeat['already_applied']
|
||||
with pytest.raises(JobOperationError, match='job_not_failed'):
|
||||
await replay_failed_job(session, storage, settings, first.job_id, request_id=uuid4(), actor='test', reason='manual_review')
|
||||
repeat = await replay_failed_job(
|
||||
session,
|
||||
storage,
|
||||
settings,
|
||||
first.job_id,
|
||||
request_id=request_id,
|
||||
actor="test",
|
||||
reason="dependency_restored",
|
||||
)
|
||||
assert repeat["already_applied"]
|
||||
with pytest.raises(JobOperationError, match="job_not_failed"):
|
||||
await replay_failed_job(
|
||||
session,
|
||||
storage,
|
||||
settings,
|
||||
first.job_id,
|
||||
request_id=uuid4(),
|
||||
actor="test",
|
||||
reason="manual_review",
|
||||
)
|
||||
await session.rollback()
|
||||
assert len((await session.scalars(select(JobReplay))).all()) == 1
|
||||
|
||||
@@ -77,26 +117,40 @@ async def test_retry_budget_backoff_replay_and_duplicate(client, context, db_eng
|
||||
async def test_permanent_failure_and_missing_source_replay(client, context, db_engine):
|
||||
storage, alice, _, _, chat = context
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
|
||||
def fail(_):
|
||||
raise ProcessingError('image_limits')
|
||||
raise ProcessingError("image_limits")
|
||||
|
||||
settings = JobSettings(_env_file=None)
|
||||
async with AsyncSession(db_engine, expire_on_commit=False) as session:
|
||||
message = await envelope(session, attachment['id'])
|
||||
await process_attachment_job(session, storage, message, settings, before_processing=fail)
|
||||
message = await envelope(session, attachment["id"])
|
||||
await process_attachment_job(
|
||||
session, storage, message, settings, before_processing=fail
|
||||
)
|
||||
job, item = await jobs.lock_job(session, message.job_id)
|
||||
assert item.status == 'failed' and job.attempt == 1 and job.last_error_permanent
|
||||
assert item.status == "failed" and job.attempt == 1 and job.last_error_permanent
|
||||
job.staging_key = None
|
||||
await session.commit()
|
||||
with pytest.raises(JobOperationError, match='source_expired'):
|
||||
await replay_failed_job(session, storage, settings, job.id, request_id=uuid4(), actor='test', reason='manual_review')
|
||||
with pytest.raises(JobOperationError, match="source_expired"):
|
||||
await replay_failed_job(
|
||||
session,
|
||||
storage,
|
||||
settings,
|
||||
job.id,
|
||||
request_id=uuid4(),
|
||||
actor="test",
|
||||
reason="manual_review",
|
||||
)
|
||||
|
||||
|
||||
async def test_stale_worker_cannot_write_and_cleanup_keeps_active(client, context, db_engine):
|
||||
async def test_stale_worker_cannot_write_and_cleanup_keeps_active(
|
||||
client, context, db_engine
|
||||
):
|
||||
storage, alice, _, _, chat = context
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
settings = JobSettings(_env_file=None)
|
||||
async with AsyncSession(db_engine, expire_on_commit=False) as session:
|
||||
message = await envelope(session, attachment['id'])
|
||||
message = await envelope(session, attachment["id"])
|
||||
claim = await claim_job(session, message, settings)
|
||||
job, item = await jobs.lock_job(session, message.job_id)
|
||||
job.lease_token = uuid4()
|
||||
@@ -112,18 +166,33 @@ async def test_stale_worker_cannot_write_and_cleanup_keeps_active(client, contex
|
||||
async def test_cleanup_ready_preserves_final_objects(client, context, db_engine):
|
||||
storage, alice, _, _, chat = context
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
await finish_attachment(client, storage, alice, attachment['id'])
|
||||
await finish_attachment(client, storage, alice, attachment["id"])
|
||||
async with AsyncSession(db_engine, expire_on_commit=False) as session:
|
||||
message = await envelope(session, attachment['id'])
|
||||
message = await envelope(session, attachment["id"])
|
||||
job, item = await jobs.lock_job(session, message.job_id)
|
||||
staging = job.staging_key
|
||||
job.finished_at = await jobs.database_time(session) - timedelta(days=2)
|
||||
await session.commit()
|
||||
assert await cleanup_staging(session, storage, JobSettings(_env_file=None), apply=False) == 1
|
||||
assert (
|
||||
await cleanup_staging(
|
||||
session, storage, JobSettings(_env_file=None), apply=False
|
||||
)
|
||||
== 1
|
||||
)
|
||||
assert staging in storage.objects
|
||||
assert await cleanup_staging(session, storage, JobSettings(_env_file=None), apply=True) == 1
|
||||
assert (
|
||||
await cleanup_staging(
|
||||
session, storage, JobSettings(_env_file=None), apply=True
|
||||
)
|
||||
== 1
|
||||
)
|
||||
assert staging not in storage.objects and len(storage.objects) == 4
|
||||
assert await cleanup_staging(session, storage, JobSettings(_env_file=None), apply=True) == 0
|
||||
assert (
|
||||
await cleanup_staging(
|
||||
session, storage, JobSettings(_env_file=None), apply=True
|
||||
)
|
||||
== 0
|
||||
)
|
||||
|
||||
|
||||
async def test_retry_classification_and_cap():
|
||||
@@ -131,44 +200,64 @@ async def test_retry_classification_and_cap():
|
||||
for attempt in (1, 2, 6, 100):
|
||||
cap = min(120, 5 * 2 ** min(30, attempt - 1))
|
||||
assert all(cap / 2 <= retry_delay(settings, attempt) <= cap for _ in range(100))
|
||||
assert classify_failure(TimeoutError()) == ('processing_timeout', False)
|
||||
assert classify_failure(OSError(errno.EACCES, 'denied'))[1]
|
||||
assert not classify_failure(OSError(errno.ENOSPC, 'full'))[1]
|
||||
assert classify_failure(TimeoutError()) == ("processing_timeout", False)
|
||||
assert classify_failure(OSError(errno.EACCES, "denied"))[1]
|
||||
assert not classify_failure(OSError(errno.ENOSPC, "full"))[1]
|
||||
|
||||
|
||||
async def test_timeout_records_retry_and_clears_lease(client, context, db_engine, monkeypatch):
|
||||
async def test_timeout_records_retry_and_clears_lease(
|
||||
client, context, db_engine, monkeypatch
|
||||
):
|
||||
storage, alice, _, _, chat = context
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
|
||||
async def stalled(*args, **kwargs):
|
||||
await asyncio.sleep(60)
|
||||
monkeypatch.setattr(attachment_jobs, 'build_result', stalled)
|
||||
settings = JobSettings(_env_file=None).model_copy(update={'job_timeout_seconds': .05})
|
||||
|
||||
monkeypatch.setattr(attachment_jobs, "build_result", stalled)
|
||||
settings = JobSettings(_env_file=None).model_copy(
|
||||
update={"job_timeout_seconds": 0.05}
|
||||
)
|
||||
async with AsyncSession(db_engine, expire_on_commit=False) as session:
|
||||
message = await envelope(session, attachment['id'])
|
||||
message = await envelope(session, attachment["id"])
|
||||
assert await process_attachment_job(session, storage, message, settings)
|
||||
job, item = await jobs.lock_job(session, message.job_id)
|
||||
assert item.status == 'queued' and job.last_error_code == 'processing_timeout'
|
||||
assert item.status == "queued" and job.last_error_code == "processing_timeout"
|
||||
assert job.lease_token is None and job.lease_until is None
|
||||
|
||||
|
||||
async def test_failed_retention_and_source_checksum_protect_replay(client, context, db_engine):
|
||||
async def test_failed_retention_and_source_checksum_protect_replay(
|
||||
client, context, db_engine
|
||||
):
|
||||
storage, alice, _, _, chat = context
|
||||
attachment = (await upload(client, alice, chat)).json()
|
||||
|
||||
def fail(_):
|
||||
raise ProcessingError('invalid_image')
|
||||
raise ProcessingError("invalid_image")
|
||||
|
||||
settings = JobSettings(_env_file=None)
|
||||
async with AsyncSession(db_engine, expire_on_commit=False) as session:
|
||||
message = await envelope(session, attachment['id'])
|
||||
await process_attachment_job(session, storage, message, settings, before_processing=fail)
|
||||
message = await envelope(session, attachment["id"])
|
||||
await process_attachment_job(
|
||||
session, storage, message, settings, before_processing=fail
|
||||
)
|
||||
job, item = await jobs.lock_job(session, message.job_id)
|
||||
key = job.staging_key
|
||||
job.finished_at = await jobs.database_time(session) - timedelta(days=2)
|
||||
await session.commit()
|
||||
assert await cleanup_staging(session, storage, settings, apply=True) == 0
|
||||
data, metadata = storage.objects[key]
|
||||
storage.objects[key] = (b'x' * len(data), metadata)
|
||||
with pytest.raises(JobOperationError, match='source_mismatch'):
|
||||
await replay_failed_job(session, storage, settings, message.job_id, request_id=uuid4(), actor='test', reason='manual_review')
|
||||
storage.objects[key] = (b"x" * len(data), metadata)
|
||||
with pytest.raises(JobOperationError, match="source_mismatch"):
|
||||
await replay_failed_job(
|
||||
session,
|
||||
storage,
|
||||
settings,
|
||||
message.job_id,
|
||||
request_id=uuid4(),
|
||||
actor="test",
|
||||
reason="manual_review",
|
||||
)
|
||||
await session.rollback()
|
||||
assert not (await session.scalars(select(JobReplay))).all()
|
||||
job, item = await jobs.lock_job(session, message.job_id)
|
||||
|
||||
@@ -20,9 +20,9 @@ async def test_draining_keeps_liveness_but_rejects_new_work(make_settings):
|
||||
app.state.lifecycle.start_draining()
|
||||
try:
|
||||
async with make_client(app) as client:
|
||||
assert (await client.get('/health/live')).status_code == 200
|
||||
assert (await client.get('/health/ready')).status_code == 503
|
||||
assert (await client.get('/api/v1/users/me')).status_code == 503
|
||||
assert (await client.get("/health/live")).status_code == 200
|
||||
assert (await client.get("/health/ready")).status_code == 503
|
||||
assert (await client.get("/api/v1/users/me")).status_code == 503
|
||||
finally:
|
||||
await close_app(app)
|
||||
|
||||
@@ -36,13 +36,13 @@ async def test_readiness_timeout_cancels_dependency_checks(make_settings, monkey
|
||||
finally:
|
||||
cancelled.append(True)
|
||||
|
||||
monkeypatch.setattr(health, 'check_database', stalled)
|
||||
monkeypatch.setattr(health, 'check_redis', stalled)
|
||||
monkeypatch.setattr(health, "check_database", stalled)
|
||||
monkeypatch.setattr(health, "check_redis", stalled)
|
||||
app = create_app(make_settings(readiness_timeout_seconds=0.03))
|
||||
try:
|
||||
async with make_client(app) as client:
|
||||
started = time.monotonic()
|
||||
response = await client.get('/health/ready')
|
||||
response = await client.get("/health/ready")
|
||||
assert response.status_code == 503
|
||||
assert time.monotonic() - started < 1
|
||||
assert len(cancelled) == 2
|
||||
|
||||
@@ -6,7 +6,13 @@ import httpx
|
||||
|
||||
from app.main import create_app
|
||||
from conftest import close_app, make_client
|
||||
from helpers import assert_request_id, bearer, create_chat, create_user, idempotency_header
|
||||
from helpers import (
|
||||
assert_request_id,
|
||||
bearer,
|
||||
create_chat,
|
||||
create_user,
|
||||
idempotency_header,
|
||||
)
|
||||
|
||||
|
||||
def _assert_error(response: httpx.Response, status: int, code: str) -> None:
|
||||
@@ -25,12 +31,16 @@ async def test_message_limit_rejects_without_deleting_confirmed_messages(make_se
|
||||
|
||||
for index in range(2):
|
||||
ok = await client.post(
|
||||
url, headers={**bearer(user), **idempotency_header()}, json={"text": f"confirmed-{index}"}
|
||||
url,
|
||||
headers={**bearer(user), **idempotency_header()},
|
||||
json={"text": f"confirmed-{index}"},
|
||||
)
|
||||
assert ok.status_code == 201
|
||||
|
||||
rejected = await client.post(
|
||||
url, headers={**bearer(user), **idempotency_header()}, json={"text": "rejected"}
|
||||
url,
|
||||
headers={**bearer(user), **idempotency_header()},
|
||||
json={"text": "rejected"},
|
||||
)
|
||||
_assert_error(rejected, 503, "unavailable")
|
||||
|
||||
@@ -65,12 +75,18 @@ async def test_in_flight_limit_returns_429_and_recovers(make_settings, monkeypat
|
||||
user = await create_user(client)
|
||||
chat = await create_chat(client, user)
|
||||
|
||||
monkeypatch.setattr(message_endpoint, "send_message_idempotent", blocking_send_message)
|
||||
monkeypatch.setattr(
|
||||
message_endpoint, "send_message_idempotent", blocking_send_message
|
||||
)
|
||||
url = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
held = [
|
||||
asyncio.create_task(
|
||||
client.post(url, headers={**bearer(user), **idempotency_header()}, json={"text": f"held-{i}"})
|
||||
client.post(
|
||||
url,
|
||||
headers={**bearer(user), **idempotency_header()},
|
||||
json={"text": f"held-{i}"},
|
||||
)
|
||||
)
|
||||
for i in range(2)
|
||||
]
|
||||
@@ -79,7 +95,11 @@ async def test_in_flight_limit_returns_429_and_recovers(make_settings, monkeypat
|
||||
|
||||
rejected = await asyncio.gather(
|
||||
*(
|
||||
client.post(url, headers={**bearer(user), **idempotency_header()}, json={"text": f"rejected-{i}"})
|
||||
client.post(
|
||||
url,
|
||||
headers={**bearer(user), **idempotency_header()},
|
||||
json={"text": f"rejected-{i}"},
|
||||
)
|
||||
for i in range(4)
|
||||
)
|
||||
)
|
||||
@@ -92,7 +112,11 @@ async def test_in_flight_limit_returns_429_and_recovers(make_settings, monkeypat
|
||||
release.set()
|
||||
assert all(r.status_code == 201 for r in await asyncio.gather(*held))
|
||||
|
||||
recovered = await client.post(url, headers={**bearer(user), **idempotency_header()}, json={"text": "after"})
|
||||
recovered = await client.post(
|
||||
url,
|
||||
headers={**bearer(user), **idempotency_header()},
|
||||
json={"text": "after"},
|
||||
)
|
||||
assert recovered.status_code == 201
|
||||
assert_request_id(recovered)
|
||||
await close_app(app)
|
||||
|
||||
@@ -8,7 +8,19 @@ from sqlalchemy import inspect, text
|
||||
from app.models import Base
|
||||
from conftest import reset_schema, upgrade_head
|
||||
|
||||
EXPECTED_TABLES = {"users", "chats", "chat_members", "messages", "counters", "idempotency_keys", "attachments", "message_attachments", "upload_intents", "attachment_jobs", "job_replays"}
|
||||
EXPECTED_TABLES = {
|
||||
"users",
|
||||
"chats",
|
||||
"chat_members",
|
||||
"messages",
|
||||
"counters",
|
||||
"idempotency_keys",
|
||||
"attachments",
|
||||
"message_attachments",
|
||||
"upload_intents",
|
||||
"attachment_jobs",
|
||||
"job_replays",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -62,6 +74,6 @@ async def test_models_and_migrations_are_in_sync(migrated_engine):
|
||||
async with migrated_engine.connect() as connection:
|
||||
diff = await connection.run_sync(compare)
|
||||
|
||||
assert diff == [], (
|
||||
f"Создайте миграцию: alembic revision --autogenerate. Diff: {diff}"
|
||||
)
|
||||
assert (
|
||||
diff == []
|
||||
), f"Создайте миграцию: alembic revision --autogenerate. Diff: {diff}"
|
||||
|
||||
@@ -10,10 +10,12 @@ from app.storage.s3 import ObjectStream, run_sync
|
||||
|
||||
async def test_sdk_thread_finishes_before_cancellation_returns():
|
||||
entered, release, finished = Event(), Event(), Event()
|
||||
|
||||
def operation():
|
||||
entered.set()
|
||||
release.wait(timeout=3)
|
||||
finished.set()
|
||||
|
||||
task = asyncio.create_task(run_sync(operation))
|
||||
await asyncio.to_thread(entered.wait, 2)
|
||||
task.cancel()
|
||||
@@ -31,10 +33,12 @@ async def test_response_discarded_when_get_is_cancelled():
|
||||
entered, release = Event(), Event()
|
||||
discarded = []
|
||||
response = object()
|
||||
|
||||
def operation():
|
||||
entered.set()
|
||||
release.wait(timeout=3)
|
||||
return response
|
||||
|
||||
task = asyncio.create_task(run_sync(operation, discard_result=discarded.append))
|
||||
await asyncio.to_thread(entered.wait, 2)
|
||||
task.cancel()
|
||||
@@ -48,9 +52,12 @@ async def test_response_discarded_when_get_is_cancelled():
|
||||
|
||||
async def test_stream_closes_even_before_first_iteration():
|
||||
calls = []
|
||||
response = SimpleNamespace(close=lambda: calls.append('close'), release_conn=lambda: calls.append('release'))
|
||||
response = SimpleNamespace(
|
||||
close=lambda: calls.append("close"),
|
||||
release_conn=lambda: calls.append("release"),
|
||||
)
|
||||
storage = SimpleNamespace(settings=S3Settings(_env_file=None))
|
||||
stream = ObjectStream(storage, response)
|
||||
await stream.aclose()
|
||||
await stream.aclose()
|
||||
assert calls == ['close', 'release']
|
||||
assert calls == ["close", "release"]
|
||||
|
||||
+252
-120
@@ -1,4 +1,5 @@
|
||||
"""HTTP helpers for public black-box tests; Python 3.9+, standard library only."""
|
||||
|
||||
import base64
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
@@ -13,205 +14,336 @@ import urllib.request
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LAB = json.loads((ROOT / 'lab.json').read_text())['number']
|
||||
SPEC = json.loads((ROOT / 'contracts/openapi.json').read_text())
|
||||
LAB = json.loads((ROOT / "lab.json").read_text())["number"]
|
||||
SPEC = json.loads((ROOT / "contracts/openapi.json").read_text())
|
||||
|
||||
|
||||
class Failure(AssertionError):
|
||||
pass
|
||||
|
||||
|
||||
def check(condition, message):
|
||||
if not condition:
|
||||
raise Failure(message)
|
||||
|
||||
def timestamp(value):
|
||||
check(isinstance(value, str) and value.endswith('Z'), 'timestamp must be UTC ending in Z')
|
||||
try:
|
||||
return dt.datetime.fromisoformat(value[:-1] + '+00:00')
|
||||
except ValueError as exc:
|
||||
raise Failure('invalid RFC3339 timestamp') from exc
|
||||
|
||||
def validate(value, schema, where='response'):
|
||||
def timestamp(value):
|
||||
check(
|
||||
isinstance(value, str) and value.endswith("Z"),
|
||||
"timestamp must be UTC ending in Z",
|
||||
)
|
||||
try:
|
||||
return dt.datetime.fromisoformat(value[:-1] + "+00:00")
|
||||
except ValueError as exc:
|
||||
raise Failure("invalid RFC3339 timestamp") from exc
|
||||
|
||||
|
||||
def validate(value, schema, where="response"):
|
||||
"""Validate the JSON Schema subset used by the supplied contract, not arbitrary OpenAPI."""
|
||||
if '$ref' in schema:
|
||||
if "$ref" in schema:
|
||||
target = SPEC
|
||||
for part in schema['$ref'].split('/')[1:]:
|
||||
for part in schema["$ref"].split("/")[1:]:
|
||||
target = target[part]
|
||||
return validate(value, target, where)
|
||||
kinds = schema.get('type', [])
|
||||
kinds = schema.get("type", [])
|
||||
if isinstance(kinds, str):
|
||||
kinds = [kinds]
|
||||
matches = {'null':value is None, 'boolean':isinstance(value,bool), 'integer':isinstance(value,int) and not isinstance(value,bool), 'number':isinstance(value,(int,float)) and not isinstance(value,bool), 'string':isinstance(value,str), 'array':isinstance(value,list), 'object':isinstance(value,dict)}
|
||||
matches = {
|
||||
"null": value is None,
|
||||
"boolean": isinstance(value, bool),
|
||||
"integer": isinstance(value, int) and not isinstance(value, bool),
|
||||
"number": isinstance(value, (int, float)) and not isinstance(value, bool),
|
||||
"string": isinstance(value, str),
|
||||
"array": isinstance(value, list),
|
||||
"object": isinstance(value, dict),
|
||||
}
|
||||
if kinds:
|
||||
check(any(matches.get(k,False) for k in kinds), where + ': incorrect type')
|
||||
if 'enum' in schema:
|
||||
check(value in schema['enum'], where + ': invalid enum')
|
||||
if 'const' in schema:
|
||||
check(value == schema['const'], where + ': invalid const')
|
||||
if isinstance(value,dict):
|
||||
props = schema.get('properties',{})
|
||||
check(all(k in value for k in schema.get('required',[])), where + ': missing required fields')
|
||||
if schema.get('additionalProperties') is False:
|
||||
check(not set(value).difference(props), where + ': unexpected fields')
|
||||
check(any(matches.get(k, False) for k in kinds), where + ": incorrect type")
|
||||
if "enum" in schema:
|
||||
check(value in schema["enum"], where + ": invalid enum")
|
||||
if "const" in schema:
|
||||
check(value == schema["const"], where + ": invalid const")
|
||||
if isinstance(value, dict):
|
||||
props = schema.get("properties", {})
|
||||
check(
|
||||
all(k in value for k in schema.get("required", [])),
|
||||
where + ": missing required fields",
|
||||
)
|
||||
if schema.get("additionalProperties") is False:
|
||||
check(not set(value).difference(props), where + ": unexpected fields")
|
||||
for key, sub in props.items():
|
||||
if key in value:
|
||||
validate(value[key], sub, where + '.' + key)
|
||||
if isinstance(value,list):
|
||||
check(len(value) >= schema.get('minItems',0), where + ': too few items')
|
||||
check(len(value) <= schema.get('maxItems',float('inf')), where + ': too many items')
|
||||
if schema.get('uniqueItems'):
|
||||
encoded = [json.dumps(x,sort_keys=True) for x in value]
|
||||
check(len(encoded)==len(set(encoded)), where + ': duplicate items')
|
||||
if 'items' in schema:
|
||||
validate(value[key], sub, where + "." + key)
|
||||
if isinstance(value, list):
|
||||
check(len(value) >= schema.get("minItems", 0), where + ": too few items")
|
||||
check(
|
||||
len(value) <= schema.get("maxItems", float("inf")),
|
||||
where + ": too many items",
|
||||
)
|
||||
if schema.get("uniqueItems"):
|
||||
encoded = [json.dumps(x, sort_keys=True) for x in value]
|
||||
check(len(encoded) == len(set(encoded)), where + ": duplicate items")
|
||||
if "items" in schema:
|
||||
for item in value:
|
||||
validate(item, schema['items'], where + '[]')
|
||||
if isinstance(value,str):
|
||||
check(len(value) >= schema.get('minLength',0), where + ': too short')
|
||||
check(len(value) <= schema.get('maxLength',float('inf')), where + ': too long')
|
||||
if 'pattern' in schema:
|
||||
check(re.search(schema['pattern'], value) is not None, where + ': pattern mismatch')
|
||||
if schema.get('format') == 'uuid':
|
||||
validate(item, schema["items"], where + "[]")
|
||||
if isinstance(value, str):
|
||||
check(len(value) >= schema.get("minLength", 0), where + ": too short")
|
||||
check(len(value) <= schema.get("maxLength", float("inf")), where + ": too long")
|
||||
if "pattern" in schema:
|
||||
check(
|
||||
re.search(schema["pattern"], value) is not None,
|
||||
where + ": pattern mismatch",
|
||||
)
|
||||
if schema.get("format") == "uuid":
|
||||
try:
|
||||
uuid.UUID(value)
|
||||
except ValueError as exc:
|
||||
raise Failure(where + ': invalid UUID') from exc
|
||||
if schema.get('format') == 'date-time':
|
||||
raise Failure(where + ": invalid UUID") from exc
|
||||
if schema.get("format") == "date-time":
|
||||
timestamp(value)
|
||||
if isinstance(value,(int,float)) and not isinstance(value,bool):
|
||||
check(value >= schema.get('minimum',-float('inf')), where + ': below minimum')
|
||||
check(value <= schema.get('maximum',float('inf')), where + ': above maximum')
|
||||
if 'anyOf' in schema:
|
||||
for alternative in schema['anyOf']:
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
check(value >= schema.get("minimum", -float("inf")), where + ": below minimum")
|
||||
check(value <= schema.get("maximum", float("inf")), where + ": above maximum")
|
||||
if "anyOf" in schema:
|
||||
for alternative in schema["anyOf"]:
|
||||
try:
|
||||
validate(value, alternative, where)
|
||||
break
|
||||
except Failure:
|
||||
pass
|
||||
else:
|
||||
raise Failure(where + ': no anyOf branch matches')
|
||||
raise Failure(where + ": no anyOf branch matches")
|
||||
|
||||
|
||||
def shape(value, name):
|
||||
validate(value, SPEC['components']['schemas'][name])
|
||||
validate(value, SPEC["components"]["schemas"][name])
|
||||
return value
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, base_url=None, ca_file=None, timeout=10):
|
||||
self.base = (base_url or os.environ.get('BASE_URL') or ('https://localhost:8443' if LAB==7 else 'http://localhost:8080')).rstrip('/')
|
||||
check(self.base.startswith(('http://','https://')), 'BASE_URL must be HTTP(S)')
|
||||
check(LAB != 7 or self.base.startswith('https://'), 'lab7 requires HTTPS')
|
||||
self.base = (
|
||||
base_url
|
||||
or os.environ.get("BASE_URL")
|
||||
or ("https://localhost:8443" if LAB == 7 else "http://localhost:8080")
|
||||
).rstrip("/")
|
||||
check(self.base.startswith(("http://", "https://")), "BASE_URL must be HTTP(S)")
|
||||
check(LAB != 7 or self.base.startswith("https://"), "lab7 requires HTTPS")
|
||||
self.timeout = timeout
|
||||
context = ssl.create_default_context(cafile=ca_file or os.environ.get('CA_FILE') or None)
|
||||
self.opener = urllib.request.build_opener(NoRedirect(), urllib.request.HTTPSHandler(context=context))
|
||||
context = ssl.create_default_context(
|
||||
cafile=ca_file or os.environ.get("CA_FILE") or None
|
||||
)
|
||||
self.opener = urllib.request.build_opener(
|
||||
NoRedirect(), urllib.request.HTTPSHandler(context=context)
|
||||
)
|
||||
|
||||
def call(self, method, path, expected=200, body=None, actor=None, headers=None, raw=None, schema=None):
|
||||
h = {'Accept':'application/json'}
|
||||
def call(
|
||||
self,
|
||||
method,
|
||||
path,
|
||||
expected=200,
|
||||
body=None,
|
||||
actor=None,
|
||||
headers=None,
|
||||
raw=None,
|
||||
schema=None,
|
||||
):
|
||||
h = {"Accept": "application/json"}
|
||||
if actor:
|
||||
h['X-User-Id' if LAB==1 else 'Authorization'] = actor['id'] if LAB==1 else 'Bearer ' + actor['token']
|
||||
h["X-User-Id" if LAB == 1 else "Authorization"] = (
|
||||
actor["id"] if LAB == 1 else "Bearer " + actor["token"]
|
||||
)
|
||||
if body is not None:
|
||||
raw = json.dumps(body,ensure_ascii=False).encode('utf-8')
|
||||
h['Content-Type'] = 'application/json'
|
||||
raw = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
h["Content-Type"] = "application/json"
|
||||
h.update(headers or {})
|
||||
req = urllib.request.Request(self.base + path, data=raw, headers=h, method=method)
|
||||
req = urllib.request.Request(
|
||||
self.base + path, data=raw, headers=h, method=method
|
||||
)
|
||||
start = time.monotonic()
|
||||
try:
|
||||
response = self.opener.open(req, timeout=self.timeout)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
except (urllib.error.URLError,TimeoutError,OSError) as exc:
|
||||
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
||||
# Do not print URL query, headers, request body, or credentials.
|
||||
raise Failure(method + ' ' + path.split('?')[0] + ': connection/TLS failure (' + type(exc).__name__ + ')') from None
|
||||
raise Failure(
|
||||
method
|
||||
+ " "
|
||||
+ path.split("?")[0]
|
||||
+ ": connection/TLS failure ("
|
||||
+ type(exc).__name__
|
||||
+ ")"
|
||||
) from None
|
||||
with response:
|
||||
status = response.code
|
||||
rh = response.headers
|
||||
data = response.read(16*1024*1024 + 1)
|
||||
check(len(data) <= 16*1024*1024, 'response exceeds test safety limit')
|
||||
allowed = [expected] if isinstance(expected,int) else expected
|
||||
check(status in allowed, method + ' ' + path.split('?')[0] + ': expected ' + str(allowed) + ', received ' + str(status))
|
||||
check(bool(rh.get('X-Request-Id')), 'missing X-Request-Id')
|
||||
if LAB>=3:
|
||||
check(bool(rh.get('X-Instance-Id')), 'missing X-Instance-Id')
|
||||
data = response.read(16 * 1024 * 1024 + 1)
|
||||
check(len(data) <= 16 * 1024 * 1024, "response exceeds test safety limit")
|
||||
allowed = [expected] if isinstance(expected, int) else expected
|
||||
check(
|
||||
status in allowed,
|
||||
method
|
||||
+ " "
|
||||
+ path.split("?")[0]
|
||||
+ ": expected "
|
||||
+ str(allowed)
|
||||
+ ", received "
|
||||
+ str(status),
|
||||
)
|
||||
check(bool(rh.get("X-Request-Id")), "missing X-Request-Id")
|
||||
if LAB >= 3:
|
||||
check(bool(rh.get("X-Instance-Id")), "missing X-Instance-Id")
|
||||
payload = None
|
||||
if schema or status>=400:
|
||||
check(rh.get_content_type()=='application/json', 'expected application/json')
|
||||
if schema or status >= 400:
|
||||
check(
|
||||
rh.get_content_type() == "application/json", "expected application/json"
|
||||
)
|
||||
try:
|
||||
payload = json.loads(data)
|
||||
except (ValueError,UnicodeError):
|
||||
raise Failure('invalid response JSON') from None
|
||||
shape(payload, 'Error' if status>=400 else schema)
|
||||
if status>=400:
|
||||
check(payload['error']['request_id']==rh.get('X-Request-Id'),'error request_id differs from header')
|
||||
if status==401 and LAB>=2:
|
||||
scheme = 'Basic' if path=='/api/v1/auth/sessions' else 'Bearer'
|
||||
check(rh.get('WWW-Authenticate','').lower().startswith(scheme.lower()), 'incorrect WWW-Authenticate challenge')
|
||||
if status==204:
|
||||
check(not data, '204 must not contain body')
|
||||
return {'status':status,'headers':rh,'json':payload,'bytes':data,'elapsed':time.monotonic()-start}
|
||||
except (ValueError, UnicodeError):
|
||||
raise Failure("invalid response JSON") from None
|
||||
shape(payload, "Error" if status >= 400 else schema)
|
||||
if status >= 400:
|
||||
check(
|
||||
payload["error"]["request_id"] == rh.get("X-Request-Id"),
|
||||
"error request_id differs from header",
|
||||
)
|
||||
if status == 401 and LAB >= 2:
|
||||
scheme = "Basic" if path == "/api/v1/auth/sessions" else "Bearer"
|
||||
check(
|
||||
rh.get("WWW-Authenticate", "").lower().startswith(scheme.lower()),
|
||||
"incorrect WWW-Authenticate challenge",
|
||||
)
|
||||
if status == 204:
|
||||
check(not data, "204 must not contain body")
|
||||
return {
|
||||
"status": status,
|
||||
"headers": rh,
|
||||
"json": payload,
|
||||
"bytes": data,
|
||||
"elapsed": time.monotonic() - start,
|
||||
}
|
||||
|
||||
def user(self, label):
|
||||
username = 'u_' + label + '_' + uuid.uuid4().hex[:12]
|
||||
password = 'T3st-' + uuid.uuid4().hex
|
||||
body = {'username':username,'display_name':'Студент ' + label}
|
||||
if LAB>=2:
|
||||
body['password'] = password
|
||||
user = self.call('POST','/api/v1/users',201,body=body,schema='User')['json']
|
||||
check(user['username']==username,'username changed')
|
||||
actor = {'id':user['id'],'user':user,'registration':body}
|
||||
if LAB>=2:
|
||||
credential = base64.b64encode((username+':'+password).encode()).decode()
|
||||
session = self.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+credential},schema='Session')['json']
|
||||
check(session['user']==user,'session user mismatch')
|
||||
check(timestamp(session['expires_at']) > dt.datetime.now(dt.timezone.utc),'session already expired')
|
||||
actor['token'] = session['token']
|
||||
username = "u_" + label + "_" + uuid.uuid4().hex[:12]
|
||||
password = "T3st-" + uuid.uuid4().hex
|
||||
body = {"username": username, "display_name": "Студент " + label}
|
||||
if LAB >= 2:
|
||||
body["password"] = password
|
||||
user = self.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
|
||||
check(user["username"] == username, "username changed")
|
||||
actor = {"id": user["id"], "user": user, "registration": body}
|
||||
if LAB >= 2:
|
||||
credential = base64.b64encode((username + ":" + password).encode()).decode()
|
||||
session = self.call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
201,
|
||||
headers={"Authorization": "Basic " + credential},
|
||||
schema="Session",
|
||||
)["json"]
|
||||
check(session["user"] == user, "session user mismatch")
|
||||
check(
|
||||
timestamp(session["expires_at"]) > dt.datetime.now(dt.timezone.utc),
|
||||
"session already expired",
|
||||
)
|
||||
actor["token"] = session["token"]
|
||||
return actor
|
||||
|
||||
def bootstrap(self):
|
||||
self.call('GET','/health/live',schema='Health')
|
||||
self.call('GET','/health/ready',schema='Health')
|
||||
alice, bob, eve = (self.user(label) for label in ('alice','bob','eve'))
|
||||
chat = self.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Контрактный тест','member_ids':[alice['id'],bob['id']]},schema='Chat')['json']
|
||||
check(set(chat['member_ids'])=={alice['id'],bob['id']},'chat member mismatch')
|
||||
return alice,bob,eve,chat
|
||||
self.call("GET", "/health/live", schema="Health")
|
||||
self.call("GET", "/health/ready", schema="Health")
|
||||
alice, bob, eve = (self.user(label) for label in ("alice", "bob", "eve"))
|
||||
chat = self.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=alice,
|
||||
body={"title": "Контрактный тест", "member_ids": [alice["id"], bob["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
check(
|
||||
set(chat["member_ids"]) == {alice["id"], bob["id"]}, "chat member mismatch"
|
||||
)
|
||||
return alice, bob, eve, chat
|
||||
|
||||
def message(self, actor, chat, text, key=None, attachments=None):
|
||||
body = {'text':text}
|
||||
body = {"text": text}
|
||||
if attachments is not None:
|
||||
body['attachment_ids'] = attachments
|
||||
headers = {'Idempotency-Key':key or uuid.uuid4().hex} if LAB>=3 else {}
|
||||
return self.call('POST','/api/v1/chats/'+chat['id']+'/messages',201,actor=actor,body=body,headers=headers,schema='Message')
|
||||
body["attachment_ids"] = attachments
|
||||
headers = {"Idempotency-Key": key or uuid.uuid4().hex} if LAB >= 3 else {}
|
||||
return self.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
201,
|
||||
actor=actor,
|
||||
body=body,
|
||||
headers=headers,
|
||||
schema="Message",
|
||||
)
|
||||
|
||||
def attachment(self, actor, chat):
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
att = self.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=sample.png',201 if LAB==4 else 202,actor=actor,raw=content,headers={'Content-Type':'image/png'},schema='Attachment')['json']
|
||||
check(att['status']==('ready' if LAB==4 else 'queued'),'incorrect upload status')
|
||||
check(att['chat_id']==chat['id'] and att['owner_id']==actor['id'],'attachment ownership mismatch')
|
||||
check(att['sha256']==hashlib.sha256(content).hexdigest() and att['size_bytes']==len(content),'original checksum/size mismatch')
|
||||
return att,content
|
||||
content = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
att = self.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/attachments?filename=sample.png",
|
||||
201 if LAB == 4 else 202,
|
||||
actor=actor,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
check(
|
||||
att["status"] == ("ready" if LAB == 4 else "queued"),
|
||||
"incorrect upload status",
|
||||
)
|
||||
check(
|
||||
att["chat_id"] == chat["id"] and att["owner_id"] == actor["id"],
|
||||
"attachment ownership mismatch",
|
||||
)
|
||||
check(
|
||||
att["sha256"] == hashlib.sha256(content).hexdigest()
|
||||
and att["size_bytes"] == len(content),
|
||||
"original checksum/size mismatch",
|
||||
)
|
||||
return att, content
|
||||
|
||||
def wait_ready(self, actor, att, wait_seconds=60):
|
||||
deadline = time.monotonic()+wait_seconds
|
||||
while time.monotonic()<deadline:
|
||||
att = self.call('GET','/api/v1/attachments/'+att['id'],actor=actor,schema='Attachment')['json']
|
||||
check(att['status']!='failed','attachment reached failed')
|
||||
if att['status']=='ready':
|
||||
deadline = time.monotonic() + wait_seconds
|
||||
while time.monotonic() < deadline:
|
||||
att = self.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + att["id"],
|
||||
actor=actor,
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
check(att["status"] != "failed", "attachment reached failed")
|
||||
if att["status"] == "ready":
|
||||
return att
|
||||
time.sleep(0.3)
|
||||
raise Failure('attachment did not become ready within test deadline')
|
||||
raise Failure("attachment did not become ready within test deadline")
|
||||
|
||||
|
||||
def arguments(description, configure=None):
|
||||
import argparse
|
||||
|
||||
p = argparse.ArgumentParser(description=description)
|
||||
p.add_argument('--base-url', default=None)
|
||||
p.add_argument('--ca-file', default=None)
|
||||
p.add_argument("--base-url", default=None)
|
||||
p.add_argument("--ca-file", default=None)
|
||||
if configure:
|
||||
configure(p)
|
||||
return p.parse_args()
|
||||
|
||||
|
||||
def run(main):
|
||||
try:
|
||||
main()
|
||||
except (Failure,ValueError,OSError) as exc:
|
||||
print('FAIL:', str(exc))
|
||||
except (Failure, ValueError, OSError) as exc:
|
||||
print("FAIL:", str(exc))
|
||||
raise SystemExit(1)
|
||||
|
||||
+18
-13
@@ -1,26 +1,31 @@
|
||||
"""Read JPEG SOF dimensions without external libraries; not a full image decoder."""
|
||||
|
||||
from client import Failure, check
|
||||
|
||||
|
||||
def jpeg_size(data):
|
||||
check(data[:2]==b'\xff\xd8','thumbnail is not JPEG')
|
||||
check(data[:2] == b"\xff\xd8", "thumbnail is not JPEG")
|
||||
i = 2
|
||||
sof = {0xc0,0xc1,0xc2,0xc3,0xc5,0xc6,0xc7,0xc9,0xca,0xcb,0xcd,0xce,0xcf}
|
||||
sof = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}
|
||||
while i < len(data):
|
||||
check(data[i]==0xff,'invalid JPEG marker')
|
||||
while i<len(data) and data[i]==0xff:
|
||||
check(data[i] == 0xFF, "invalid JPEG marker")
|
||||
while i < len(data) and data[i] == 0xFF:
|
||||
i += 1
|
||||
check(i<len(data),'truncated JPEG marker')
|
||||
check(i < len(data), "truncated JPEG marker")
|
||||
marker = data[i]
|
||||
i += 1
|
||||
if marker in {0xd9,0xda}:
|
||||
if marker in {0xD9, 0xDA}:
|
||||
break
|
||||
if marker in {0x01,0xd8} or 0xd0<=marker<=0xd7:
|
||||
if marker in {0x01, 0xD8} or 0xD0 <= marker <= 0xD7:
|
||||
continue
|
||||
check(i+2<=len(data),'truncated JPEG segment')
|
||||
length = int.from_bytes(data[i:i+2],'big')
|
||||
check(length>=2 and i+length<=len(data),'invalid JPEG segment length')
|
||||
check(i + 2 <= len(data), "truncated JPEG segment")
|
||||
length = int.from_bytes(data[i : i + 2], "big")
|
||||
check(length >= 2 and i + length <= len(data), "invalid JPEG segment length")
|
||||
if marker in sof:
|
||||
check(length>=8,'invalid JPEG SOF')
|
||||
return (int.from_bytes(data[i+5:i+7],'big'),int.from_bytes(data[i+3:i+5],'big'))
|
||||
check(length >= 8, "invalid JPEG SOF")
|
||||
return (
|
||||
int.from_bytes(data[i + 5 : i + 7], "big"),
|
||||
int.from_bytes(data[i + 3 : i + 5], "big"),
|
||||
)
|
||||
i += length
|
||||
raise Failure('JPEG dimensions not found')
|
||||
raise Failure("JPEG dimensions not found")
|
||||
|
||||
+58
-27
@@ -1,5 +1,6 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Small closed-loop HTTP write benchmark; not an open-loop capacity proof."""
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import math
|
||||
@@ -11,48 +12,78 @@ from client import Client, Failure, LAB, arguments, check, run
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--duration',type=float,default=30)
|
||||
p.add_argument('--concurrency',type=int,default=4)
|
||||
p.add_argument('--output',default=None,help='Optional JSON metrics, no session tokens')
|
||||
args = arguments('Synthetic POST message load, closed loop; creates users/messages',configure)
|
||||
check(1<=args.duration<=3600,'duration must be 1..3600 seconds')
|
||||
check(1<=args.concurrency<=128,'concurrency must be 1..128')
|
||||
c = Client(args.base_url,args.ca_file)
|
||||
alice,bob,eve,chat = c.bootstrap()
|
||||
p.add_argument("--duration", type=float, default=30)
|
||||
p.add_argument("--concurrency", type=int, default=4)
|
||||
p.add_argument(
|
||||
"--output", default=None, help="Optional JSON metrics, no session tokens"
|
||||
)
|
||||
|
||||
args = arguments(
|
||||
"Synthetic POST message load, closed loop; creates users/messages", configure
|
||||
)
|
||||
check(1 <= args.duration <= 3600, "duration must be 1..3600 seconds")
|
||||
check(1 <= args.concurrency <= 128, "concurrency must be 1..128")
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
barrier = threading.Barrier(args.concurrency)
|
||||
|
||||
def worker(worker_id):
|
||||
local = Client(args.base_url,args.ca_file,timeout=5)
|
||||
local = Client(args.base_url, args.ca_file, timeout=5)
|
||||
barrier.wait()
|
||||
deadline = time.monotonic()+args.duration
|
||||
latencies,errors = [],0
|
||||
deadline = time.monotonic() + args.duration
|
||||
latencies, errors = [], 0
|
||||
index = 0
|
||||
while time.monotonic()<deadline:
|
||||
while time.monotonic() < deadline:
|
||||
start = time.monotonic()
|
||||
try:
|
||||
local.message(alice,chat,'load-%s-%s' % (worker_id,index))
|
||||
latencies.append(time.monotonic()-start)
|
||||
local.message(alice, chat, "load-%s-%s" % (worker_id, index))
|
||||
latencies.append(time.monotonic() - start)
|
||||
except Failure:
|
||||
errors += 1
|
||||
index += 1
|
||||
return latencies,errors
|
||||
return latencies, errors
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
results = list(pool.map(worker,range(args.concurrency)))
|
||||
elapsed = time.monotonic()-started
|
||||
latencies = sorted(x for values,_ in results for x in values)
|
||||
errors = sum(n for _,n in results)
|
||||
total = len(latencies)+errors
|
||||
results = list(pool.map(worker, range(args.concurrency)))
|
||||
elapsed = time.monotonic() - started
|
||||
latencies = sorted(x for values, _ in results for x in values)
|
||||
errors = sum(n for _, n in results)
|
||||
total = len(latencies) + errors
|
||||
|
||||
def percentile(p):
|
||||
return round(1000*latencies[max(0,math.ceil(p*len(latencies))-1)],3) if latencies else None
|
||||
report = {'lab':LAB,'workload':'closed-loop POST messages; no automatic retries','requested_duration_seconds':args.duration,'elapsed_seconds':round(elapsed,3),'concurrency':args.concurrency,'successful_requests':len(latencies),'failed_requests':errors,'error_ratio':round(errors/total,6) if total else None,'successful_rps':round(len(latencies)/elapsed,3),'successful_latency_ms':{'p50':percentile(.50),'p95':percentile(.95),'p99':percentile(.99)},'note':'Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.'}
|
||||
text = json.dumps(report,ensure_ascii=False,indent=2)
|
||||
return (
|
||||
round(1000 * latencies[max(0, math.ceil(p * len(latencies)) - 1)], 3)
|
||||
if latencies
|
||||
else None
|
||||
)
|
||||
|
||||
report = {
|
||||
"lab": LAB,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": args.duration,
|
||||
"elapsed_seconds": round(elapsed, 3),
|
||||
"concurrency": args.concurrency,
|
||||
"successful_requests": len(latencies),
|
||||
"failed_requests": errors,
|
||||
"error_ratio": round(errors / total, 6) if total else None,
|
||||
"successful_rps": round(len(latencies) / elapsed, 3),
|
||||
"successful_latency_ms": {
|
||||
"p50": percentile(0.50),
|
||||
"p95": percentile(0.95),
|
||||
"p99": percentile(0.99),
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.",
|
||||
}
|
||||
text = json.dumps(report, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
dest = Path(args.output)
|
||||
dest.parent.mkdir(parents=True,exist_ok=True)
|
||||
dest.write_text(text+'\n')
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
dest.write_text(text + "\n")
|
||||
print(text)
|
||||
check(bool(latencies),'no successful writes')
|
||||
check(bool(latencies), "no successful writes")
|
||||
# Errors are reported, not treated as a universal load-test threshold.
|
||||
|
||||
if __name__=='__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
|
||||
+142
-64
@@ -1,5 +1,6 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit operator-authored hook; tokens remain in memory, volumes are never removed by this test."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -11,111 +12,187 @@ from client import Client, Failure, LAB, arguments, check, run
|
||||
|
||||
|
||||
def history(c, actor, chat):
|
||||
path = '/api/v1/chats/'+chat['id']+'/messages?limit=100'
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
|
||||
result = []
|
||||
seen = set()
|
||||
for _ in range(1000):
|
||||
page = c.call('GET',path,actor=actor,schema='MessagePage')['json']
|
||||
result.extend(page['items'])
|
||||
cursor = page['next_cursor']
|
||||
page = c.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
result.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return result
|
||||
check(cursor not in seen,'cursor cycle')
|
||||
check(cursor not in seen, "cursor cycle")
|
||||
seen.add(cursor)
|
||||
path = '/api/v1/chats/'+chat['id']+'/messages?limit=100&cursor='+quote(cursor,safe='')
|
||||
raise Failure('history pagination exceeded safety bound')
|
||||
path = (
|
||||
"/api/v1/chats/"
|
||||
+ chat["id"]
|
||||
+ "/messages?limit=100&cursor="
|
||||
+ quote(cursor, safe="")
|
||||
)
|
||||
raise Failure("history pagination exceeded safety bound")
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--mode', choices=['persistence','failover'], required=True)
|
||||
p.add_argument('--action-script',required=True,help='Executable script authored by student; restarts stack or stops ONE API replica')
|
||||
args = arguments('Explicit restart/failover scenario; modifies only synthetic API data',configure)
|
||||
check(LAB>=2,'persistence requires lab2+')
|
||||
check(args.mode!='failover' or LAB>=3,'failover requires lab3+')
|
||||
p.add_argument("--mode", choices=["persistence", "failover"], required=True)
|
||||
p.add_argument(
|
||||
"--action-script",
|
||||
required=True,
|
||||
help="Executable script authored by student; restarts stack or stops ONE API replica",
|
||||
)
|
||||
|
||||
args = arguments(
|
||||
"Explicit restart/failover scenario; modifies only synthetic API data",
|
||||
configure,
|
||||
)
|
||||
check(LAB >= 2, "persistence requires lab2+")
|
||||
check(args.mode != "failover" or LAB >= 3, "failover requires lab3+")
|
||||
script = Path(args.action_script).expanduser().resolve()
|
||||
check(script.is_file() and os.access(script,os.X_OK),'action script must exist and be executable (chmod +x)')
|
||||
check('.example.' not in script.name,'copy and implement the example hook first')
|
||||
c = Client(args.base_url,args.ca_file,timeout=2)
|
||||
alice,bob,eve,chat = c.bootstrap()
|
||||
sent = c.message(alice,chat,'Сохранить при отказе')
|
||||
original = sent['json']
|
||||
target = sent['headers'].get('X-Instance-Id','')
|
||||
check(
|
||||
script.is_file() and os.access(script, os.X_OK),
|
||||
"action script must exist and be executable (chmod +x)",
|
||||
)
|
||||
check(".example." not in script.name, "copy and implement the example hook first")
|
||||
c = Client(args.base_url, args.ca_file, timeout=2)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
sent = c.message(alice, chat, "Сохранить при отказе")
|
||||
original = sent["json"]
|
||||
target = sent["headers"].get("X-Instance-Id", "")
|
||||
attachment = content = None
|
||||
if LAB>=4:
|
||||
attachment,content = c.attachment(alice,chat)
|
||||
if LAB>=5:
|
||||
attachment = c.wait_ready(alice,attachment)
|
||||
if LAB >= 4:
|
||||
attachment, content = c.attachment(alice, chat)
|
||||
if LAB >= 5:
|
||||
attachment = c.wait_ready(alice, attachment)
|
||||
env = dict(os.environ)
|
||||
env['TARGET_INSTANCE_ID'] = target
|
||||
env["TARGET_INSTANCE_ID"] = target
|
||||
observed = set()
|
||||
if args.mode=='failover':
|
||||
if args.mode == "failover":
|
||||
for _ in range(40):
|
||||
observed.add(c.call('GET','/api/v1/users/me',actor=alice,schema='User')['headers']['X-Instance-Id'])
|
||||
check(len(observed)>=2,'less than two API instances observed before failure; verify LB/session affinity')
|
||||
print('Executing explicit '+args.mode+' hook; hook output suppressed to avoid leaking secrets.')
|
||||
observed.add(
|
||||
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")[
|
||||
"headers"
|
||||
]["X-Instance-Id"]
|
||||
)
|
||||
check(
|
||||
len(observed) >= 2,
|
||||
"less than two API instances observed before failure; verify LB/session affinity",
|
||||
)
|
||||
print(
|
||||
"Executing explicit "
|
||||
+ args.mode
|
||||
+ " hook; hook output suppressed to avoid leaking secrets."
|
||||
)
|
||||
# No shell interpolation and no Docker commands in this test.
|
||||
proc = subprocess.Popen([str(script)],env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
proc = subprocess.Popen(
|
||||
[str(script)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
|
||||
)
|
||||
started = time.monotonic()
|
||||
successes,failures,after_instances = [],0,[]
|
||||
successes, failures, after_instances = [], 0, []
|
||||
try:
|
||||
if args.mode=='persistence':
|
||||
if args.mode == "persistence":
|
||||
try:
|
||||
code = proc.wait(timeout=90)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise Failure('restart hook exceeded 90 seconds') from None
|
||||
check(code==0,'restart hook failed (inspect your script locally)')
|
||||
deadline = time.monotonic()+90
|
||||
raise Failure("restart hook exceeded 90 seconds") from None
|
||||
check(code == 0, "restart hook failed (inspect your script locally)")
|
||||
deadline = time.monotonic() + 90
|
||||
while True:
|
||||
try:
|
||||
c.call('GET','/health/ready',schema='Health')
|
||||
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
||||
c.call("GET", "/health/ready", schema="Health")
|
||||
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
break
|
||||
except Failure:
|
||||
check(time.monotonic()<deadline,'stack/session did not recover within 90 seconds')
|
||||
check(
|
||||
time.monotonic() < deadline,
|
||||
"stack/session did not recover within 90 seconds",
|
||||
)
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
first_recovery = None
|
||||
key = uuid.uuid4().hex
|
||||
text = 'Запись во время отказа ' + key
|
||||
while time.monotonic()-started < 15:
|
||||
text = "Запись во время отказа " + key
|
||||
while time.monotonic() - started < 15:
|
||||
code = proc.poll()
|
||||
check(code is None or code==0,'stop-one hook failed (inspect your script locally)')
|
||||
check(code is not None or time.monotonic()-started<10,'stop-one hook must return within 10 seconds')
|
||||
check(
|
||||
code is None or code == 0,
|
||||
"stop-one hook failed (inspect your script locally)",
|
||||
)
|
||||
check(
|
||||
code is not None or time.monotonic() - started < 10,
|
||||
"stop-one hook must return within 10 seconds",
|
||||
)
|
||||
try:
|
||||
response = c.message(alice,chat,text,key=key)
|
||||
msg = response['json']
|
||||
if code==0:
|
||||
response = c.message(alice, chat, text, key=key)
|
||||
msg = response["json"]
|
||||
if code == 0:
|
||||
if first_recovery is None:
|
||||
first_recovery = time.monotonic()-started
|
||||
after_instances.append(response['headers']['X-Instance-Id'])
|
||||
first_recovery = time.monotonic() - started
|
||||
after_instances.append(response["headers"]["X-Instance-Id"])
|
||||
successes.append(msg)
|
||||
key = uuid.uuid4().hex
|
||||
text = 'Запись во время отказа ' + key
|
||||
text = "Запись во время отказа " + key
|
||||
except Failure:
|
||||
failures += 1
|
||||
# Keep SAME key/body after an uncertain POST result.
|
||||
time.sleep(0.1)
|
||||
check(proc.poll()==0,'stop-one hook did not finish successfully')
|
||||
check(first_recovery is not None and first_recovery<=10,'writes did not recover within 10 seconds from hook start')
|
||||
check(len(after_instances)>=5,'too few successful writes after stop')
|
||||
check(target not in after_instances[-5:],'target replica still serves requests; hook must leave it stopped')
|
||||
print(json.dumps({'observed_instances_before':len(observed),'successful_writes':len(successes),'failed_attempts':failures,'first_recovery_seconds':round(first_recovery,3)},ensure_ascii=False))
|
||||
check(proc.poll() == 0, "stop-one hook did not finish successfully")
|
||||
check(
|
||||
first_recovery is not None and first_recovery <= 10,
|
||||
"writes did not recover within 10 seconds from hook start",
|
||||
)
|
||||
check(len(after_instances) >= 5, "too few successful writes after stop")
|
||||
check(
|
||||
target not in after_instances[-5:],
|
||||
"target replica still serves requests; hook must leave it stopped",
|
||||
)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"observed_instances_before": len(observed),
|
||||
"successful_writes": len(successes),
|
||||
"failed_attempts": failures,
|
||||
"first_recovery_seconds": round(first_recovery, 3),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
# Existing token, no re-login. Read all confirmations and reject duplicates.
|
||||
messages = history(c,bob,chat)
|
||||
ids = [m['id'] for m in messages]
|
||||
check(len(ids)==len(set(ids)),'duplicated message IDs in history')
|
||||
check(any(m==original for m in messages),'confirmed pre-failure message lost or altered')
|
||||
messages = history(c, bob, chat)
|
||||
ids = [m["id"] for m in messages]
|
||||
check(len(ids) == len(set(ids)), "duplicated message IDs in history")
|
||||
check(
|
||||
any(m == original for m in messages),
|
||||
"confirmed pre-failure message lost or altered",
|
||||
)
|
||||
for msg in successes:
|
||||
check(any(m==msg for m in messages),'confirmed in-flight message lost or altered')
|
||||
check(
|
||||
any(m == msg for m in messages),
|
||||
"confirmed in-flight message lost or altered",
|
||||
)
|
||||
# Bodies are unique in this scenario: an uncertain request may exist once, never twice.
|
||||
texts = [m['text'] for m in messages]
|
||||
check(len(texts)==len(set(texts)),'uncertain retry created duplicate message')
|
||||
texts = [m["text"] for m in messages]
|
||||
check(
|
||||
len(texts) == len(set(texts)), "uncertain retry created duplicate message"
|
||||
)
|
||||
if attachment:
|
||||
c.call('GET','/api/v1/attachments/'+attachment['id'],actor=bob,schema='Attachment')
|
||||
downloaded = c.call('GET','/api/v1/attachments/'+attachment['id']+'/content',actor=bob)
|
||||
check(downloaded['bytes']==content,'attachment lost or changed across failure')
|
||||
print('PASS: '+args.mode+' preserved confirmed data and existing session. Hook scope needs operator evidence.')
|
||||
c.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + attachment["id"],
|
||||
actor=bob,
|
||||
schema="Attachment",
|
||||
)
|
||||
downloaded = c.call(
|
||||
"GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=bob
|
||||
)
|
||||
check(
|
||||
downloaded["bytes"] == content,
|
||||
"attachment lost or changed across failure",
|
||||
)
|
||||
print(
|
||||
"PASS: "
|
||||
+ args.mode
|
||||
+ " preserved confirmed data and existing session. Hook scope needs operator evidence."
|
||||
)
|
||||
finally:
|
||||
if proc.poll() is None:
|
||||
proc.terminate()
|
||||
@@ -125,5 +202,6 @@ def main():
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
|
||||
if __name__=='__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
|
||||
+159
-69
@@ -1,5 +1,6 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One complete public acceptance scenario, cumulative by lab number."""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import uuid
|
||||
@@ -7,76 +8,165 @@ from client import Client, LAB, arguments, check, run, timestamp
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Messenger public smoke; creates synthetic users and messages')
|
||||
c = Client(args.base_url,args.ca_file)
|
||||
alice,bob,eve,chat = c.bootstrap()
|
||||
path = '/api/v1/chats/'+chat['id']
|
||||
c.call('POST','/api/v1/users',409,body=alice['registration'])
|
||||
c.call('GET','/api/v1/users/me',401)
|
||||
c.call('GET',path,404,actor=eve)
|
||||
me = c.call('GET','/api/v1/users/me',actor=alice,schema='User')['json']
|
||||
check(me==alice['user'],'current user mismatch')
|
||||
listed = c.call('GET','/api/v1/chats?limit=100',actor=bob,schema='ChatPage')['json']
|
||||
check(any(x['id']==chat['id'] for x in listed['items']),'member cannot list chat')
|
||||
hidden = c.call('GET','/api/v1/chats?limit=100',actor=eve,schema='ChatPage')['json']
|
||||
check(all(x['id']!=chat['id'] for x in hidden['items']),'chat leaks to outsider')
|
||||
args = arguments("Messenger public smoke; creates synthetic users and messages")
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"]
|
||||
c.call("POST", "/api/v1/users", 409, body=alice["registration"])
|
||||
c.call("GET", "/api/v1/users/me", 401)
|
||||
c.call("GET", path, 404, actor=eve)
|
||||
me = c.call("GET", "/api/v1/users/me", actor=alice, schema="User")["json"]
|
||||
check(me == alice["user"], "current user mismatch")
|
||||
listed = c.call("GET", "/api/v1/chats?limit=100", actor=bob, schema="ChatPage")[
|
||||
"json"
|
||||
]
|
||||
check(
|
||||
any(x["id"] == chat["id"] for x in listed["items"]), "member cannot list chat"
|
||||
)
|
||||
hidden = c.call("GET", "/api/v1/chats?limit=100", actor=eve, schema="ChatPage")[
|
||||
"json"
|
||||
]
|
||||
check(all(x["id"] != chat["id"] for x in hidden["items"]), "chat leaks to outsider")
|
||||
key = uuid.uuid4().hex
|
||||
first = c.message(alice,chat,'Привет, мир 👋',key=key)['json']
|
||||
second = c.message(bob,chat,'Сообщение Боба')['json']
|
||||
check(first['sender_id']==alice['id'] and second['sender_id']==bob['id'],'sender was not derived from actor')
|
||||
check(first['chat_id']==second['chat_id']==chat['id'],'wrong chat in message')
|
||||
check(first['text']=='Привет, мир 👋' and second['text']=='Сообщение Боба','message text changed')
|
||||
page1 = c.call('GET',path+'/messages?limit=1',actor=bob,schema='MessagePage')['json']
|
||||
check(len(page1['items'])==1 and page1['next_cursor'],'first page must have one item and cursor')
|
||||
first = c.message(alice, chat, "Привет, мир 👋", key=key)["json"]
|
||||
second = c.message(bob, chat, "Сообщение Боба")["json"]
|
||||
check(
|
||||
first["sender_id"] == alice["id"] and second["sender_id"] == bob["id"],
|
||||
"sender was not derived from actor",
|
||||
)
|
||||
check(first["chat_id"] == second["chat_id"] == chat["id"], "wrong chat in message")
|
||||
check(
|
||||
first["text"] == "Привет, мир 👋" and second["text"] == "Сообщение Боба",
|
||||
"message text changed",
|
||||
)
|
||||
page1 = c.call("GET", path + "/messages?limit=1", actor=bob, schema="MessagePage")[
|
||||
"json"
|
||||
]
|
||||
check(
|
||||
len(page1["items"]) == 1 and page1["next_cursor"],
|
||||
"first page must have one item and cursor",
|
||||
)
|
||||
from urllib.parse import quote
|
||||
page2 = c.call('GET',path+'/messages?limit=1&cursor='+quote(page1['next_cursor'],safe=''),actor=alice,schema='MessagePage')['json']
|
||||
check(len(page2['items'])==1 and page2['next_cursor'] is None,'second page must finish history')
|
||||
ordered = sorted([first,second],key=lambda x:(timestamp(x['created_at']),uuid.UUID(x['id']).int))
|
||||
check(page1['items']+page2['items']==ordered,'pagination lost, duplicated or reordered a message')
|
||||
h = {'Idempotency-Key':uuid.uuid4().hex} if LAB>=3 else {}
|
||||
c.call('POST',path+'/messages',400,actor=alice,body={'text':''},headers=h)
|
||||
c.call('POST',path+'/messages',404,actor=eve,body={'text':'чужое'},headers=h)
|
||||
c.call('GET',path+'/messages?limit=0',400,actor=alice)
|
||||
if LAB>=2:
|
||||
bad = base64.b64encode((alice['registration']['username']+':wrong-password').encode()).decode()
|
||||
c.call('POST','/api/v1/auth/sessions',401,headers={'Authorization':'Basic '+bad})
|
||||
good = base64.b64encode((alice['registration']['username']+':'+alice['registration']['password']).encode()).decode()
|
||||
c.call('GET','/api/v1/users/me',401,headers={'Authorization':'Basic '+good})
|
||||
c.call('GET','/api/v1/users/me',401,headers={'X-User-Id':alice['id']})
|
||||
me = c.call('GET','/api/v1/users/me',actor=alice,headers={'X-User-Id':eve['id']},schema='User')['json']
|
||||
check(me['id']==alice['id'],'X-User-Id overrode bearer identity')
|
||||
if LAB>=3:
|
||||
replay = c.message(alice,chat,first['text'],key=key)['json']
|
||||
check(replay==first,'idempotency replay differs')
|
||||
c.call('POST',path+'/messages',409,actor=alice,body={'text':'другой body'},headers={'Idempotency-Key':key})
|
||||
c.call('POST',path+'/messages',400,actor=alice,body={'text':'без ключа'})
|
||||
if LAB>=4:
|
||||
att,content = c.attachment(alice,chat)
|
||||
# A queued attachment must already be linkable to its own chat.
|
||||
attached = c.message(alice,chat,'',attachments=[att['id']])['json']
|
||||
check(attached['attachment_ids']==[att['id']],'message lost attachment')
|
||||
ready = c.wait_ready(bob,att) if LAB>=5 else att
|
||||
check(ready['error_code'] is None,'ready attachment has an error')
|
||||
download = c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)
|
||||
check(download['bytes']==content,'download differs from original')
|
||||
check(download['headers'].get_content_type()=='image/png','original content type mismatch')
|
||||
for suffix in ('','/content'):
|
||||
c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=eve)
|
||||
if LAB>=5:
|
||||
variants = [x for x in ready['variants'] if x['name']=='thumbnail']
|
||||
check(len(variants)==1,'expected exactly one thumbnail')
|
||||
v = variants[0]
|
||||
check((v['width'],v['height'])==(256,160),'thumbnail metadata has wrong dimensions')
|
||||
thumb = c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant=thumbnail',actor=bob)
|
||||
check(thumb['headers'].get_content_type()=='image/jpeg','thumbnail content type mismatch')
|
||||
check(len(thumb['bytes'])==v['size_bytes'] and hashlib.sha256(thumb['bytes']).hexdigest()==v['sha256'],'thumbnail checksum mismatch')
|
||||
from image_probe import jpeg_size
|
||||
check(jpeg_size(thumb['bytes'])==(256,160),'actual JPEG dimensions mismatch')
|
||||
if LAB>=2:
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
|
||||
c.call('GET','/api/v1/users/me',401,actor=alice)
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',401,actor=alice)
|
||||
print('PASS: lab%d public API scenario; infrastructure and grading evidence remain separate.' % LAB)
|
||||
|
||||
if __name__=='__main__':
|
||||
page2 = c.call(
|
||||
"GET",
|
||||
path + "/messages?limit=1&cursor=" + quote(page1["next_cursor"], safe=""),
|
||||
actor=alice,
|
||||
schema="MessagePage",
|
||||
)["json"]
|
||||
check(
|
||||
len(page2["items"]) == 1 and page2["next_cursor"] is None,
|
||||
"second page must finish history",
|
||||
)
|
||||
ordered = sorted(
|
||||
[first, second],
|
||||
key=lambda x: (timestamp(x["created_at"]), uuid.UUID(x["id"]).int),
|
||||
)
|
||||
check(
|
||||
page1["items"] + page2["items"] == ordered,
|
||||
"pagination lost, duplicated or reordered a message",
|
||||
)
|
||||
h = {"Idempotency-Key": uuid.uuid4().hex} if LAB >= 3 else {}
|
||||
c.call("POST", path + "/messages", 400, actor=alice, body={"text": ""}, headers=h)
|
||||
c.call(
|
||||
"POST", path + "/messages", 404, actor=eve, body={"text": "чужое"}, headers=h
|
||||
)
|
||||
c.call("GET", path + "/messages?limit=0", 400, actor=alice)
|
||||
if LAB >= 2:
|
||||
bad = base64.b64encode(
|
||||
(alice["registration"]["username"] + ":wrong-password").encode()
|
||||
).decode()
|
||||
c.call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
401,
|
||||
headers={"Authorization": "Basic " + bad},
|
||||
)
|
||||
good = base64.b64encode(
|
||||
(
|
||||
alice["registration"]["username"]
|
||||
+ ":"
|
||||
+ alice["registration"]["password"]
|
||||
).encode()
|
||||
).decode()
|
||||
c.call(
|
||||
"GET", "/api/v1/users/me", 401, headers={"Authorization": "Basic " + good}
|
||||
)
|
||||
c.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": alice["id"]})
|
||||
me = c.call(
|
||||
"GET",
|
||||
"/api/v1/users/me",
|
||||
actor=alice,
|
||||
headers={"X-User-Id": eve["id"]},
|
||||
schema="User",
|
||||
)["json"]
|
||||
check(me["id"] == alice["id"], "X-User-Id overrode bearer identity")
|
||||
if LAB >= 3:
|
||||
replay = c.message(alice, chat, first["text"], key=key)["json"]
|
||||
check(replay == first, "idempotency replay differs")
|
||||
c.call(
|
||||
"POST",
|
||||
path + "/messages",
|
||||
409,
|
||||
actor=alice,
|
||||
body={"text": "другой body"},
|
||||
headers={"Idempotency-Key": key},
|
||||
)
|
||||
c.call("POST", path + "/messages", 400, actor=alice, body={"text": "без ключа"})
|
||||
if LAB >= 4:
|
||||
att, content = c.attachment(alice, chat)
|
||||
# A queued attachment must already be linkable to its own chat.
|
||||
attached = c.message(alice, chat, "", attachments=[att["id"]])["json"]
|
||||
check(attached["attachment_ids"] == [att["id"]], "message lost attachment")
|
||||
ready = c.wait_ready(bob, att) if LAB >= 5 else att
|
||||
check(ready["error_code"] is None, "ready attachment has an error")
|
||||
download = c.call(
|
||||
"GET", "/api/v1/attachments/" + att["id"] + "/content", actor=bob
|
||||
)
|
||||
check(download["bytes"] == content, "download differs from original")
|
||||
check(
|
||||
download["headers"].get_content_type() == "image/png",
|
||||
"original content type mismatch",
|
||||
)
|
||||
for suffix in ("", "/content"):
|
||||
c.call("GET", "/api/v1/attachments/" + att["id"] + suffix, 404, actor=eve)
|
||||
if LAB >= 5:
|
||||
variants = [x for x in ready["variants"] if x["name"] == "thumbnail"]
|
||||
check(len(variants) == 1, "expected exactly one thumbnail")
|
||||
v = variants[0]
|
||||
check(
|
||||
(v["width"], v["height"]) == (256, 160),
|
||||
"thumbnail metadata has wrong dimensions",
|
||||
)
|
||||
thumb = c.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + att["id"] + "/content?variant=thumbnail",
|
||||
actor=bob,
|
||||
)
|
||||
check(
|
||||
thumb["headers"].get_content_type() == "image/jpeg",
|
||||
"thumbnail content type mismatch",
|
||||
)
|
||||
check(
|
||||
len(thumb["bytes"]) == v["size_bytes"]
|
||||
and hashlib.sha256(thumb["bytes"]).hexdigest() == v["sha256"],
|
||||
"thumbnail checksum mismatch",
|
||||
)
|
||||
from image_probe import jpeg_size
|
||||
|
||||
check(
|
||||
jpeg_size(thumb["bytes"]) == (256, 160),
|
||||
"actual JPEG dimensions mismatch",
|
||||
)
|
||||
if LAB >= 2:
|
||||
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
c.call("GET", "/api/v1/users/me", 401, actor=alice)
|
||||
c.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=alice)
|
||||
print(
|
||||
"PASS: lab%d public API scenario; infrastructure and grading evidence remain separate."
|
||||
% LAB
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
|
||||
Reference in New Issue
Block a user