add level 4
This commit is contained in:
@@ -29,9 +29,9 @@ 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)
|
||||
|
||||
.PHONY: test-attachments test-private test-upload-failover test-s3-outage
|
||||
.PHONY: test-attachments test-private test-upload-failover test-s3-outage reconcile reconcile-apply test-reconcile test-upload-memory test-s3-permissions
|
||||
test-attachments:
|
||||
$(PYTHON) student-tests/attachments.py --base-url "$(BASE_URL)"
|
||||
uv run python student-tests/attachments.py --base-url "$(BASE_URL)"
|
||||
|
||||
test-private:
|
||||
$(PYTHON) student-tests/attachment_resilience.py --mode private --base-url "$(BASE_URL)"
|
||||
@@ -41,3 +41,18 @@ test-upload-failover:
|
||||
|
||||
test-s3-outage:
|
||||
$(PYTHON) student-tests/attachment_resilience.py --mode s3-outage --base-url "$(BASE_URL)"
|
||||
|
||||
reconcile:
|
||||
docker compose --profile maintenance run --rm --no-deps reconcile --grace-seconds 3600
|
||||
|
||||
reconcile-apply:
|
||||
docker compose --profile maintenance run --rm --no-deps reconcile --apply --grace-seconds 3600
|
||||
|
||||
test-reconcile:
|
||||
$(PYTHON) student-tests/reconcile.py --base-url "$(BASE_URL)"
|
||||
|
||||
test-upload-memory:
|
||||
uv run python student-tests/upload_memory.py --base-url "$(BASE_URL)"
|
||||
|
||||
test-s3-permissions:
|
||||
$(PYTHON) student-tests/s3_permissions.py --base-url "$(BASE_URL)"
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
# Отчёт — лабораторная 4
|
||||
|
||||
- Автор, группа: Матвей Козырев, БВТ2301.
|
||||
- Целевая оценка: **3 — работающий минимум**.
|
||||
- Целевая оценка: **4 — уровень стажёра/джуна**.
|
||||
- Ветка: `solution/BVT2301-Kozyrev`.
|
||||
- Проверки: 20 октября 2026 года. Базовый commit и SHA-256 исходников проверенного рабочего дерева — [evidence/environment.json](evidence/environment.json).
|
||||
- Проверки: 22 октября 2026 года. Базовый commit и SHA-256 исходников проверенного рабочего дерева — [evidence/environment.json](evidence/environment.json).
|
||||
- Использованные библиотеки: FastAPI, Uvicorn, asyncpg, argon2-cffi, boto3, Pillow. Помощь ИИ: Codex — перенос основы lab3, реализация вложений, тесты и документация.
|
||||
|
||||
## Запуск из чистого clone
|
||||
@@ -45,9 +45,9 @@ docker compose run --rm --no-deps s3-init
|
||||
| S3 / s3 | SeaweedFS 4.17, digest в Compose | master cluster status; bootstrap дополнительно проверяет S3 | s3_data: файлы и LevelDB filer | Внутренний 8333; identity config из secret |
|
||||
| Bootstrap / s3-init | Тот же Python-образ | exit 0 | Нет | Отдельные административные S3 credentials |
|
||||
|
||||
SeaweedFS закреплён digest `sha256:186de7ef977a20343ee9a5544073f081976a29e2d29ecf8379891e7bf177fbe9`. Настройка filer LevelDB в [infra/filer.toml](infra/filer.toml) сохраняет его метаданные в `/data/filer` на том же volume. S3 identity `api` имеет Read/Write/List для одного bucket; anonymous identity отсутствует. Административные credentials доступны bootstrap, но не API. Внутренняя Docker-сеть считается доверенной; это не защита от компрометации контейнера.
|
||||
SeaweedFS закреплён digest `sha256:186de7ef977a20343ee9a5544073f081976a29e2d29ecf8379891e7bf177fbe9`. Настройка filer LevelDB в [infra/filer.toml](infra/filer.toml) сохраняет его метаданные в `/data/filer` на том же volume. S3 identity `api` имеет Read/Write/List только для `messenger-attachments`; anonymous identity отсутствует. Она не может выполнять bucket-admin operations. Административные credentials доступны bootstrap и maintenance-reconciler, но не API. SeaweedFS классифицирует DELETE object как Write, поэтому этот провайдер не разделяет PUT и DELETE внутри одной Write-разрешённой bucket-scoped identity; reconciler вынесен в отдельный maintenance container, а API-код не содержит операции удаления. Внутренняя Docker-сеть считается доверенной; это не защита от компрометации контейнера.
|
||||
|
||||
Лимиты Compose: каждая API — 0,5 CPU / 512 MiB; PostgreSQL — 0,75 CPU / 512 MiB; SeaweedFS — 1 CPU / 512 MiB; HAProxy — 0,25 CPU / 128 MiB. Это учебный стенд на одном Docker-host, без высокой доступности БД, S3, LB и самого host.
|
||||
Лимиты Compose: каждая API — 0,5 CPU / 512 MiB; PostgreSQL — 0,75 CPU / 512 MiB; SeaweedFS — 1 CPU / 512 MiB; HAProxy — 0,25 CPU / 128 MiB. SeaweedFS допускает до 64 локальных data volumes по 128 MiB; это предотвращает исчерпание учебного лимита при повторяемых test uploads. Это учебный стенд на одном Docker-host, без высокой доступности БД, S3, LB и самого host.
|
||||
|
||||
### Перенос lab3 и модель вложений
|
||||
|
||||
@@ -63,10 +63,18 @@ SeaweedFS закреплён digest `sha256:186de7ef977a20343ee9a5544073f081976a
|
||||
|
||||
Лимит **10 MiB = 10 × 1024 × 1024 = 10 485 760 байт** проверяется по Content-Length и повторно при чтении каждого блока, в том числе для chunked upload. До декодирования Pillow определяет фактический формат и размеры; максимум **40 000 000 пикселей**. Проверяются целостность PNG и декодирование пикселей PNG/JPEG. MIME должен совпадать с содержимым. Анимированный PNG не поддерживается: ответ 415.
|
||||
|
||||
Во время приёма используется удаляемый временный файл; он не является хранилищем оригиналов и не используется при скачивании. На одну API-реплику допускается одна одновременная загрузка/проверка изображения, ожидание вместе с загрузкой ограничено 30 секундами. SDK и декодирование выполняются вне event loop. S3 connect timeout — 2 с, read timeout — 5 с, автоматические повторы выключены. Это ограничения отдельного запроса, не доказательство устойчивости при произвольной нагрузке.
|
||||
Во время приёма используется удаляемый временный файл; он не является хранилищем оригиналов и не используется при скачивании. На одну API-реплику допускается одна одновременная загрузка/проверка изображения (`UPLOAD_CONCURRENCY=1`), ожидание вместе с загрузкой ограничено 30 секундами (`UPLOAD_TIMEOUT_SECONDS`). SDK и декодирование выполняются вне event loop. S3 connect timeout — 2 с, read timeout — 5 с, автоматические повторы выключены. Объект и запрос ограничены 10 MiB; следовательно API не накапливает неограниченное тело запроса в памяти. Временный файл ограничивает RAM ценой bounded disk usage до 10 MiB на активную загрузку.
|
||||
|
||||
Порядок фиксации: валидация → S3 PUT → INSERT метаданных PostgreSQL → **201, status=ready, variants=[], error_code=null**. GET метаданных и оригинала снова проверяет членство. Для постороннего — 404; без сессии — 401. GET content читает оригинал из S3, проверяет размер и SHA-256 и возвращает байты через API без redirect. Object key и credentials не входят в публичную модель.
|
||||
|
||||
### Согласованность PostgreSQL и S3
|
||||
|
||||
Атомарной транзакции между PostgreSQL и S3 нет. Если PUT прошёл, но процесс или БД отказали до подтверждённого INSERT, API возвращает 503 и намеренно не удаляет объект синхронно: исход COMMIT мог быть неизвестен. Вместо небезопасного удаления применяется [src.reconcile](src/reconcile.py).
|
||||
|
||||
`make reconcile` запускает inventory в **dry-run**. Он сравнивает только `originals/` S3 с `attachments.object_key`, сообщает orphan, свежие unreferenced и missing objects. `make reconcile-apply` удаляет только orphan старше 3600 секунд; отсутствующие объекты и все referenced записи не удаляются. Grace period защищает объект при задержанном COMMIT/наблюдении. Для ручной аварийной проверки возможно `docker compose --profile maintenance run --rm --no-deps reconcile --apply --grace-seconds N`; значение 0 применяется только в изолированных тестах. Reconciler использует отдельные admin credentials, API не получает эти секреты.
|
||||
|
||||
Missing object считается наблюдаемой ошибкой, а не поводом удалить метаданные: download вернёт 503, а maintenance output содержит attachment ID и object key. Восстановление байтов требует оператора или резервной копии; автоматическое восстановление не заявляется. Это безопаснее удаления используемого сообщения/метаданных без источника оригинала.
|
||||
|
||||
Недоступность S3: upload/download и readiness возвращают 503 в формате Error; liveness остаётся 200. HAProxy исключает unready backend, поэтому при недоступности обеих реплик сам LB может вернуть собственный 503. Проверка формата ошибки API при таком отказе выполняется напрямую внутри Docker-сети.
|
||||
|
||||
## Проверки и доказательства
|
||||
@@ -87,6 +95,10 @@ make test-s3-outage
|
||||
python3 scripts/verify-persistence.py
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
docker compose start api-a api-b
|
||||
make reconcile
|
||||
make test-reconcile
|
||||
make test-upload-memory
|
||||
make test-s3-permissions
|
||||
```
|
||||
|
||||
Сценарии отказов выполняются последовательно на учебном стенде: они временно останавливают контейнеры. Собственные проверки возвращают остановленные сервисы в работу; публичный `test-failover` оставляет реплику остановленной, поэтому последняя команда нужна для восстановления. Все данные синтетические, токены не сохраняются. Тесты добавляют данные; автоматического удаления нет.
|
||||
@@ -99,17 +111,20 @@ docker compose start api-a api-b
|
||||
| Приватность bucket вне API | `make test-private`: anonymous GET существующего объекта → 403 | [PASS](evidence/private-bucket.txt) |
|
||||
| Отказ именно загрузившей API | `make test-upload-failover`: загрузка через api-b, остановка api-b, те же байты через другую реплику | [PASS](evidence/attachment-failover.txt) |
|
||||
| Недоступность S3 | `make test-s3-outage`: 503, восстановление, прежний оригинал | [PASS](evidence/s3-outage.txt) |
|
||||
| Перезапуск всех компонентов, сохранение действующей сессии, метаданных и файла | `python3 scripts/verify-persistence.py`; StartedAt каждого сервиса изменился | [PASS](evidence/persistence.txt) |
|
||||
| Публичный failover, сообщения без дублей и сохранение файла | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | [Результат](evidence/failover.txt) |
|
||||
| Перезапуск всех компонентов, сохранение действующей сессии, метаданных и файла | `python3 scripts/verify-persistence.py`; StartedAt каждого сервиса изменился | [PASS](evidence/persistence-level4.txt) |
|
||||
| Публичный failover, сообщения без дублей и сохранение файла | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | [PASS](evidence/failover-level4.txt) |
|
||||
| Конкурентная идемпотентность и регрессии lab3 | Собственные проверки lab3 | [Результат](evidence/lab3-regressions.txt) |
|
||||
| Повторный bootstrap bucket | `docker compose run --rm --no-deps s3-init` | [Результат](evidence/bootstrap.txt) |
|
||||
| Reconcile: dry-run, grace period, protected object, missing object, post-PUT/pre-DB отказ | `make test-reconcile` | [PASS](evidence/reconcile.txt) |
|
||||
| Ограниченные S3 credentials | `make test-s3-permissions`: API не создаёт bucket; отдельный maintenance principal выполняет admin list | [PASS](evidence/s3-permissions.txt) |
|
||||
| 10 одновременных потоковых upload по 5 MiB | `make test-upload-memory`, cgroup `memory.current` каждые 0,1 с | [PASS](evidence/upload-memory.txt), [raw JSON](evidence/upload-memory.json) |
|
||||
|
||||
Точные границы проверены отдельно: PNG с trailing bytes доведён до 10 485 760 байт и скачан без изменений; PNG 8000 × 5000 = 40 000 000 пикселей принят; заголовок 8001 × 5000 = 40 005 000 пикселей отклонён до декодирования. Это функциональные тесты, не исследование RPS или памяти уровня 4/5.
|
||||
Точные границы проверены отдельно: PNG с trailing bytes доведён до 10 485 760 байт и скачан без изменений; PNG 8000 × 5000 = 40 000 000 пикселей принят; заголовок 8001 × 5000 = 40 005 000 пикселей отклонён до декодирования. В `upload-memory.json` серия из 10 клиентов по 5 242 880 bytes дала длительность 5,529 с; 22 cgroup-пробы показали peak 105 254 912 и 101 470 208 bytes на двух API. Это на 431 616 000 и 435 400 704 bytes ниже лимита 536 870 912 bytes, соответственно: `536870912 − 105254912` и `536870912 − 101470208`. Измерение дискретное, поэтому это наблюдаемый минимум пика, а не строгая верхняя оценка.
|
||||
|
||||
## Ограничения
|
||||
|
||||
- Между S3 PUT и COMMIT PostgreSQL нет общей транзакции. Сбой после PUT может оставить orphan object. Автоматическая сверка/очистка с grace period относится к следующему уровню и здесь не реализована. При неопределённом исходе COMMIT объект намеренно не удаляется, чтобы не повредить возможную подтверждённую запись.
|
||||
- API буферизует скачивание не более 10 MiB, чтобы проверить checksum до ответа. Ограничение общего количества скачиваний и нагрузочный эксперимент для 10 одновременных upload не выполнены; оценка 4 не заявляется.
|
||||
- Между S3 PUT и COMMIT PostgreSQL нет общей транзакции; orphan закрывает reconciler с grace period, но missing-object запись восстанавливается только оператором/backup. Автоматический repair исходного файла не реализован.
|
||||
- API буферизует скачивание не более 10 MiB, чтобы проверить checksum до ответа. Эксперимент 10 upload измеряет cgroup memory.current, но не является capacity benchmark и не покрывает произвольные медленные клиенты, filesystem quota и одновременные скачивания.
|
||||
- Readiness проверяет доступность БД и bucket, но не наличие каждого отдельного объекта. Потеря одного объекта при доступном S3 обнаруживается при скачивании как 503.
|
||||
- Перезапуск с volumes и отказ API подтверждены на одном Docker-host. Потеря volumes/host не покрывается, резервное копирование не реализовано.
|
||||
- HTTP предназначен для локального учебного стенда. Presigned flow, обработка thumbnail и брокер не реализованы.
|
||||
@@ -118,5 +133,6 @@ docker compose start api-a api-b
|
||||
|
||||
- [Контракт API](contracts/README.md), [OpenAPI](contracts/openapi.json), [критерии задания](README.md).
|
||||
- [SeaweedFS исходники и запуск](https://github.com/seaweedfs/seaweedfs), [релиз 4.17](https://github.com/seaweedfs/seaweedfs/releases/tag/4.17). Параметры закреплённого образа дополнительно проверены через `docker run --rm chrislusf/seaweedfs:4.17 server -help`.
|
||||
- [SeaweedFS S3 authorization](https://github.com/seaweedfs/seaweedfs/blob/master/weed/s3api/auth_signature_v4.go): в используемой модели операции, отличные от GET/HEAD, проверяются как `Write`; это источник ограничения на раздельные PUT/DELETE права.
|
||||
- [Pillow Image API](https://pillow.readthedocs.io/en/stable/reference/Image.html): lazy open, размеры, verify/load и decompression bomb limits.
|
||||
- [Boto3 S3 PutObject](https://docs.aws.amazon.com/boto3/latest/reference/services/s3/client/put_object.html): запись оригинала в S3.
|
||||
|
||||
+33
-1
@@ -15,6 +15,9 @@ x-api: &api
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
|
||||
MAX_UPLOAD_BYTES: "10485760"
|
||||
MAX_IMAGE_PIXELS: "40000000"
|
||||
UPLOAD_CONCURRENCY: "1"
|
||||
UPLOAD_TIMEOUT_SECONDS: "30"
|
||||
UPLOAD_FAULT_AFTER_S3_PUT: ${UPLOAD_FAULT_AFTER_S3_PUT:-0}
|
||||
secrets:
|
||||
- database_url
|
||||
- cursor_secret
|
||||
@@ -43,7 +46,7 @@ x-api: &api
|
||||
services:
|
||||
s3:
|
||||
image: chrislusf/seaweedfs:4.17@sha256:186de7ef977a20343ee9a5544073f081976a29e2d29ecf8379891e7bf177fbe9
|
||||
command: ["server", "-dir=/data", "-ip=s3", "-ip.bind=0.0.0.0", "-s3", "-s3.config=/run/secrets/s3_config", "-master.volumeSizeLimitMB=128", "-volume.max=8", "-s3.port.iceberg=0", "-filer.exposeDirectoryData=false"]
|
||||
command: ["server", "-dir=/data", "-ip=s3", "-ip.bind=0.0.0.0", "-s3", "-s3.config=/run/secrets/s3_config", "-master.volumeSizeLimitMB=128", "-volume.max=64", "-s3.port.iceberg=0", "-filer.exposeDirectoryData=false"]
|
||||
secrets:
|
||||
- s3_config
|
||||
volumes:
|
||||
@@ -54,6 +57,7 @@ services:
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 15s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
@@ -119,6 +123,34 @@ services:
|
||||
cpus: "0.25"
|
||||
memory: 128M
|
||||
|
||||
reconcile:
|
||||
build:
|
||||
context: .
|
||||
entrypoint: ["/app/.venv/bin/python", "-m", "src.reconcile"]
|
||||
profiles: ["maintenance"]
|
||||
environment:
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
CURSOR_SECRET_FILE: /run/secrets/cursor_secret
|
||||
S3_ENDPOINT: http://s3:8333
|
||||
S3_BUCKET: messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_admin_key
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_admin_secret
|
||||
secrets:
|
||||
- database_url
|
||||
- cursor_secret
|
||||
- s3_admin_key
|
||||
- s3_admin_secret
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
s3:
|
||||
condition: service_healthy
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.25"
|
||||
memory: 128M
|
||||
|
||||
api-a:
|
||||
<<: *api
|
||||
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
uv run python student-tests/attachments.py --base-url "http://localhost:8080"
|
||||
PASS: PNG/JPEG originals, metadata, attachment-only messages and ACL
|
||||
PASS: filename, MIME, malformed image, byte/pixel and chunked limits
|
||||
PASS: attachment scope, duplicates and idempotency normalization
|
||||
PASS: inclusive 10 MiB and 40 million pixel boundaries
|
||||
+18
-14
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"recorded_at_utc": "2026-10-20T14:23:50.123531+00:00",
|
||||
"base_commit": "3b52b91fb76d8acdeb7cbec010fd5542fd8990f7",
|
||||
"recorded_at_utc": "2026-10-22T08:32:17.051591+00:00",
|
||||
"base_commit": "e9ef559c349cf8b6fc32138fed0ea7a7600ce1ca",
|
||||
"branch": "solution/BVT2301-Kozyrev",
|
||||
"note": "Results apply to this working tree, not only the base commit. Functional tests; no load benchmark.",
|
||||
"host": "macOS-26.1-arm64-arm-64bit-Mach-O",
|
||||
@@ -12,8 +12,8 @@
|
||||
"compose_version": "5.5.1",
|
||||
"sources_sha256": {
|
||||
"Dockerfile": "efede941e2ccf21cd1e70ebbf8af7647209bd030b2962f9446bee497a2ed6a8c",
|
||||
"Makefile": "bdb2dade89d84f516b20097ee8f33db7b85dd6bfa431c41881177a323cea845e",
|
||||
"compose.yaml": "47d7c77d070097cef515279c3e46435bf0925d9b82dd96ef88fa38534e217328",
|
||||
"Makefile": "b417167d9d5baae110b2963a26ec12cea8ad8c96ce3d627a6c9e4fe8f51b74d3",
|
||||
"compose.yaml": "b239915436be84c7b1000346669ae9a10c89e83c55555a5e9eac0e20828f6fb6",
|
||||
"infra/README.md": "0e804fa51debba4c38d3cc84abf4704897665e0335b272060363f03aadd6354f",
|
||||
"infra/filer.toml": "ae3c01bf7708f5d4a319fdb454f753be0f137fe7c31269f1c413cbccc860f5c7",
|
||||
"infra/haproxy.cfg": "23c9b869170633e3c6a8c41bbd3f1102bc97bf213e0d7cfed9d461af91216fd3",
|
||||
@@ -23,34 +23,38 @@
|
||||
"migrations/004_attachments.sql": "d760453ba130c94c403f5b04222649fc131ab4d091edd0267ede901fdf82a79e",
|
||||
"pyproject.toml": "d3962edc7a683a62c915c8edec91e85c647c8ae6fe6432603e30b595bd6c3804",
|
||||
"scripts/check_contract.py": "7c4402c2a6ab80d3b4676e1866d6ecc87b6daea14c080bcb9be9a7e8b959d671",
|
||||
"scripts/init-secrets.py": "fc89fc740da189b65be1b69980ff512e2c233dd09997c8ffb0198d9368118386",
|
||||
"scripts/init-secrets.py": "01232befe48b69933b5c6b7e4f29cb19a777030ffab00accc7999afb6c082cef",
|
||||
"scripts/record-environment.py": "716fa7b8edd05d7ab6781fc346338b2254f82186953c6dbf525785c723eee4a1",
|
||||
"scripts/restart.example.sh": "0328246ba75defbced992104e986fde973f63e3830d83251eced5953263e944b",
|
||||
"scripts/restart.sh": "0a64716273eb5c79011d99e4734b18ed5a3a28f41b8b1d4ea6b24d0a4ffc702f",
|
||||
"scripts/restart.sh": "a2710fc04976b28d0da4a8cd68bf2cc28735d01ec321ec95861f855900f9a42b",
|
||||
"scripts/stop-one.example.sh": "1bcf34394520b89d95b7605ec56675be799eea920e83cfbba306d5dc0a6d9811",
|
||||
"scripts/stop-one.sh": "c69fdb1891e0c49f41d3892f2d108ecd38b2f59d505c8fe991023bb5c9b08a5e",
|
||||
"scripts/validate_openapi.py": "4e981acbfc10dac58817bf922d5896e996798551fedc1b2385130e1cddb13d54",
|
||||
"scripts/verify-persistence.py": "6c366bf4d85802bcffe65ae3d45d00736b184033313dabb60b80e1270d8874f1",
|
||||
"src/__init__.py": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b",
|
||||
"src/attachments.py": "b377227a623bc41585f2eca487356bbd38c59a0ada56f425b8fca11abd93c085",
|
||||
"src/bootstrap_s3.py": "bd0bafad4f5443bd37ab0d14c7b49453ae77fda059076f59cc02e9abc08bbc65",
|
||||
"src/config.py": "6cb85b839e2947c3334c52f24d94ceb5290103e323ba33e6ab59f10f3ae3a53a",
|
||||
"src/attachments.py": "553936936318b8096b5a662ddd85dae4043dffb9b4fb6461e60bfc1962914325",
|
||||
"src/bootstrap_s3.py": "2c43f5540e63f004a88e08961a72293546fbc5210f46bc719b90b9f5c0f3f9bd",
|
||||
"src/config.py": "62e214ceef5fcc24be11d23500de0fdaf6cf5efed1d913cdda0921fd34b088c3",
|
||||
"src/cursor.py": "a9192f2445042b8d4ddac57031718ef558990a52eb2922827074479b7f686775",
|
||||
"src/errors.py": "07f8860b45cadd242d0d9f268c4b806e35353f33b11bbde0ab3d50acda86a80a",
|
||||
"src/main.py": "abb5d7a856bff6d19ada7cf17addd59ef7400a26cf795ec01ea8b7d76f44527a",
|
||||
"src/main.py": "6980cdbb09c3b356ff870ee7fc972d85e835c58228d3c0ea27de8a668dc41ece",
|
||||
"src/migrate.py": "1d164c8921df2b5369e30b1f8936c2b71858c5279070f0fd593f62f66e1f0b7d",
|
||||
"src/models.py": "b94e6b26559afc5fd90f58d34d906c77bf4b4a78c716ac552358795496ad1d1b",
|
||||
"src/reconcile.py": "67682de753e3331a5bb5c884ab6dabaad458c49e27d4a0f2c849d79b63a7c44b",
|
||||
"src/routes.py": "3c21149a30ea7c2f695547c42133dcebcfbacbd6544bcb73c353be46fa35a2e6",
|
||||
"src/storage/__init__.py": "05ef66318c4c436eaafc493072640817219ab37bce464a265a2306233389064a",
|
||||
"src/storage/postgres.py": "2ff296490b06729c8e56eb97dbdc8d1ca91c94e313375ea5a88ffec99b6f838d",
|
||||
"src/storage/s3.py": "433247b86837a9a1212900da9d3241105e191b36d8fcac8a92c50100f5f4b946",
|
||||
"src/storage/postgres.py": "c69fea94937fdf00b077a8f1d301e83f35e120c3a7c5153fe205725be0aa0428",
|
||||
"src/storage/s3.py": "c51c8a804ca1ed869556c80252e119372696110443df30bd84f0836a01a0c305",
|
||||
"student-tests/attachment_resilience.py": "c72c431b355dda919c1b6b854d260f8c7420672ca9f86bf0848692da35dcb0ac",
|
||||
"student-tests/attachments.py": "a948fabfe83b73eb8e494c80fb9d1f2a949e2a95b7a21809a05975d65d68fc15",
|
||||
"student-tests/idempotency_concurrency.py": "db5d139009e4660ac1801af45d10e24665aa81cba737731e527c0f5b4152231e",
|
||||
"student-tests/readiness_failover.py": "0ef8355d85be66597d7d44eb7308dcb58c6c9a174d18f360b2d6d22fdcfbed14",
|
||||
"student-tests/readiness_unavailable.py": "46e3f680a3ff9cb79e95568004d97f1752dbdcd88fd4b5f160a9cc38af65a237",
|
||||
"student-tests/reconcile.py": "298537cda6523631def290e750a651db1eace0647b99c68647c68e0fdb8f34ca",
|
||||
"student-tests/review_regressions.py": "de58f63b2c794c2775247ddd3fccc523870ccbe673ffa404fdd566274d1d41de",
|
||||
"student-tests/s3_permissions.py": "f265a64f900952db79d545e6c058a7605870c2843ed2298f5c68ad4a177663ff",
|
||||
"student-tests/session_expiry.py": "ba8ead4356e4d12c4047ac2b5704d3d3342f71c37b3c13f65a0a9d7c37186ad6",
|
||||
"student-tests/upload_memory.py": "a1493aaa8ce8e898291a14059826c1405d31a3577027ae926f8c80febf25d3dc",
|
||||
"uv.lock": "fdbeb5ba0c5eedced1a6e5b62c6a57b2d22f293cf77b9487a806c6e1a8b992a0"
|
||||
},
|
||||
"services": {
|
||||
@@ -78,7 +82,7 @@
|
||||
},
|
||||
"api-a": {
|
||||
"image": "mtusi2026lab4-api-a",
|
||||
"image_id": "sha256:3a32a3f312aff9b46c6de73815627556af6f7cbee4b22783c1f4185d407f01b3",
|
||||
"image_id": "sha256:679085dc5870799c12f9251cccbd62a1bf4d75e80a9706bc052b57d51d8251e7",
|
||||
"state": "running",
|
||||
"health": "healthy",
|
||||
"memory_limit_bytes": 536870912,
|
||||
@@ -87,7 +91,7 @@
|
||||
},
|
||||
"api-b": {
|
||||
"image": "mtusi2026lab4-api-b",
|
||||
"image_id": "sha256:0e3c794618677c4a6305586bf44165fb1b3dbe668ce77b583df97e9e72721aa1",
|
||||
"image_id": "sha256:0ca4765ed83bf21e802b8b90f2687839d761519271423bc10b2c6d72e29aef48",
|
||||
"state": "running",
|
||||
"health": "healthy",
|
||||
"memory_limit_bytes": 536870912,
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 93, "failed_attempts": 2, "first_recovery_seconds": 2.562}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,5 @@
|
||||
Before: {"api-a": {"container": "fd7ade45cc98", "started_at": "2026-10-22T08:24:41.206791297Z"}, "api-b": {"container": "1bcbfe033cad", "started_at": "2026-10-22T08:24:41.125348256Z"}, "load_balancer": {"container": "3e69e9c37346", "started_at": "2026-10-22T08:24:41.017094297Z"}, "postgres": {"container": "b756a119c924", "started_at": "2026-10-22T08:24:32.576392335Z"}, "s3": {"container": "fe8f16b7a24d", "started_at": "2026-10-22T08:25:56.983675472Z"}}
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
After: {"api-a": {"container": "fd7ade45cc98", "started_at": "2026-10-22T08:29:52.364601219Z"}, "api-b": {"container": "1bcbfe033cad", "started_at": "2026-10-22T08:29:52.274115094Z"}, "load_balancer": {"container": "3e69e9c37346", "started_at": "2026-10-22T08:29:52.231563844Z"}, "postgres": {"container": "b756a119c924", "started_at": "2026-10-22T08:29:42.97697609Z"}, "s3": {"container": "fe8f16b7a24d", "started_at": "2026-10-22T08:29:46.000691966Z"}}
|
||||
PASS: PostgreSQL, S3, both API replicas and LB actually restarted; volumes preserved
|
||||
@@ -0,0 +1,31 @@
|
||||
Container mtusi2026lab4-s3-init-run-a56a6944b69f Creating
|
||||
Container mtusi2026lab4-s3-init-run-a56a6944b69f Created
|
||||
Container mtusi2026lab4-reconcile-run-2f379f07becf Creating
|
||||
Container mtusi2026lab4-reconcile-run-2f379f07becf Created
|
||||
Container mtusi2026lab4-reconcile-run-32de115488fc Creating
|
||||
Container mtusi2026lab4-reconcile-run-32de115488fc Created
|
||||
Container mtusi2026lab4-reconcile-run-8824578f5ed8 Creating
|
||||
Container mtusi2026lab4-reconcile-run-8824578f5ed8 Created
|
||||
Container mtusi2026lab4-s3-init-run-849f50d3d583 Creating
|
||||
Container mtusi2026lab4-s3-init-run-849f50d3d583 Created
|
||||
Container mtusi2026lab4-reconcile-run-cd1eb67e6a5f Creating
|
||||
Container mtusi2026lab4-reconcile-run-cd1eb67e6a5f Created
|
||||
Container mtusi2026lab4-s3-init-run-a50b80f3ae78 Creating
|
||||
Container mtusi2026lab4-s3-init-run-a50b80f3ae78 Created
|
||||
PASS: dry-run, grace period, orphan deletion and missing-object reporting
|
||||
Container mtusi2026lab4-api-a-1 Recreate
|
||||
Container mtusi2026lab4-api-a-1 Recreated
|
||||
Container mtusi2026lab4-api-a-1 Starting
|
||||
Container mtusi2026lab4-api-a-1 Started
|
||||
Container mtusi2026lab4-api-a-1 Running
|
||||
Container mtusi2026lab4-api-a-1 Waiting
|
||||
Container mtusi2026lab4-api-a-1 Healthy
|
||||
Container mtusi2026lab4-reconcile-run-1c72990b1ddc Creating
|
||||
Container mtusi2026lab4-reconcile-run-1c72990b1ddc Created
|
||||
Container mtusi2026lab4-reconcile-run-2e902a56554d Creating
|
||||
Container mtusi2026lab4-reconcile-run-2e902a56554d Created
|
||||
PASS: post-PUT/pre-DB injected failure leaves no permanent orphan
|
||||
Container mtusi2026lab4-api-a-1 Recreate
|
||||
Container mtusi2026lab4-api-a-1 Recreated
|
||||
Container mtusi2026lab4-api-a-1 Starting
|
||||
Container mtusi2026lab4-api-a-1 Started
|
||||
@@ -0,0 +1 @@
|
||||
PASS: API identity cannot create buckets; maintenance identity has separate admin access
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 tests/smoke.py --base-url "http://localhost:8080"
|
||||
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"uploads": 10,
|
||||
"file_bytes": 5242880,
|
||||
"concurrency": 10,
|
||||
"api_upload_concurrency_limit": 1,
|
||||
"elapsed_seconds": 5.529,
|
||||
"baseline_memory_bytes": {
|
||||
"7b09ecf19049": 84668416,
|
||||
"1bcbfe033cad": 86630400
|
||||
},
|
||||
"peak_memory_bytes": {
|
||||
"7b09ecf19049": 105254912,
|
||||
"1bcbfe033cad": 101470208
|
||||
},
|
||||
"peak_growth_bytes": {
|
||||
"7b09ecf19049": 20586496,
|
||||
"1bcbfe033cad": 14839808
|
||||
},
|
||||
"samples": 22,
|
||||
"method": "cgroup memory.current sampled through Docker every 0.1 seconds while clients send chunked 512 KiB blocks every 0.5 seconds; peak is not a continuous profiler."
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
uv run python student-tests/upload_memory.py --base-url "http://localhost:8080"
|
||||
{"uploads": 10, "file_bytes": 5242880, "concurrency": 10, "api_upload_concurrency_limit": 1, "elapsed_seconds": 5.529, "baseline_memory_bytes": {"7b09ecf19049": 84668416, "1bcbfe033cad": 86630400}, "peak_memory_bytes": {"7b09ecf19049": 105254912, "1bcbfe033cad": 101470208}, "peak_growth_bytes": {"7b09ecf19049": 20586496, "1bcbfe033cad": 14839808}, "samples": 22, "method": "cgroup memory.current sampled through Docker every 0.1 seconds while clients send chunked 512 KiB blocks every 0.5 seconds; peak is not a continuous profiler."}
|
||||
@@ -25,10 +25,12 @@ admin_key = write("s3_admin_key", secrets.token_hex(16))
|
||||
admin_secret = write("s3_admin_secret", secrets.token_hex(32))
|
||||
app_key = write("s3_access_key_id", secrets.token_hex(16))
|
||||
app_secret = write("s3_secret_access_key", secrets.token_hex(32))
|
||||
write("s3.json", json.dumps({"identities": [
|
||||
config_path = root / "s3.json"
|
||||
config_path.write_text(json.dumps({"identities": [
|
||||
{"name": "bootstrap", "credentials": [{"accessKey": admin_key, "secretKey": admin_secret}],
|
||||
"actions": ["Admin", "Read", "Write", "List", "Tagging"]},
|
||||
{"name": "api", "credentials": [{"accessKey": app_key, "secretKey": app_secret}],
|
||||
"actions": ["Read:messenger-attachments", "Write:messenger-attachments", "List:messenger-attachments"]},
|
||||
]}, indent=2))
|
||||
]}, indent=2) + "\n")
|
||||
config_path.chmod(0o600)
|
||||
print("Local secrets ready; existing values preserved.")
|
||||
|
||||
@@ -3,5 +3,6 @@ set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose restart postgres s3
|
||||
docker compose up -d --wait postgres s3
|
||||
docker compose run --rm --no-deps s3-init
|
||||
docker compose restart api-a api-b load_balancer
|
||||
docker compose up -d --wait api-a api-b load_balancer
|
||||
|
||||
+9
-1
@@ -1,5 +1,6 @@
|
||||
import asyncio
|
||||
from hashlib import sha256
|
||||
import os
|
||||
from tempfile import TemporaryFile
|
||||
import unicodedata
|
||||
from uuid import UUID, uuid4
|
||||
@@ -62,7 +63,10 @@ async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
|
||||
if length > limit:
|
||||
raise ApiError(413, "payload_too_large", "Файл больше лимита")
|
||||
try:
|
||||
async with asyncio.timeout(30):
|
||||
timeout = int(os.environ.get("UPLOAD_TIMEOUT_SECONDS", "30"))
|
||||
if not 1 <= timeout <= 120:
|
||||
raise ApiError(503, "unavailable", "Некорректный лимит времени загрузки")
|
||||
async with asyncio.timeout(timeout):
|
||||
async with request.app.state.upload_slot:
|
||||
# Temporary scratch space only; deleted on every exit, never used for downloads.
|
||||
with TemporaryFile() as file:
|
||||
@@ -78,6 +82,10 @@ async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
|
||||
attachment_id = uuid4()
|
||||
key = f"originals/{attachment_id}"
|
||||
await s3.put(key, file, size, content_type)
|
||||
# Disabled by default. Used only by the failure-injection test to
|
||||
# model a process crash after S3 accepts the object and before DB.
|
||||
if os.environ.get("UPLOAD_FAULT_AFTER_S3_PUT") == "1":
|
||||
raise ApiError(503, "unavailable", "Инъецирован отказ после S3 PUT")
|
||||
return await store.create_attachment(
|
||||
attachment_id, chat_id, user["id"], filename, content_type,
|
||||
size, digest.hexdigest(), key,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Idempotent private bucket bootstrap; executed with separate admin credentials."""
|
||||
import time
|
||||
from uuid import uuid4
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from .storage.s3 import S3Settings, S3Store
|
||||
|
||||
@@ -29,6 +30,18 @@ def main():
|
||||
except ClientError as error:
|
||||
if error.response["Error"]["Code"] != "NoSuchBucketPolicy":
|
||||
raise
|
||||
# The master health endpoint can become available before a volume accepts
|
||||
# writes after a restart. Verify the actual data path before APIs start.
|
||||
probe_key = f"_bootstrap/write-probe-{uuid4()}"
|
||||
for attempt in range(30):
|
||||
try:
|
||||
store.client.put_object(Bucket=bucket, Key=probe_key, Body=b"ready")
|
||||
store.client.delete_object(Bucket=bucket, Key=probe_key)
|
||||
break
|
||||
except (BotoCoreError, ClientError):
|
||||
if attempt == 29:
|
||||
raise RuntimeError("S3 write path startup timed out") from None
|
||||
time.sleep(1)
|
||||
print("PASS: private S3 bucket ready")
|
||||
finally:
|
||||
store.client.close()
|
||||
|
||||
@@ -19,6 +19,7 @@ _CONFIGURATION_KEYS = {
|
||||
"S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE",
|
||||
"S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE",
|
||||
"MAX_UPLOAD_BYTES", "MAX_IMAGE_PIXELS",
|
||||
"UPLOAD_CONCURRENCY", "UPLOAD_TIMEOUT_SECONDS", "UPLOAD_FAULT_AFTER_S3_PUT",
|
||||
}
|
||||
|
||||
|
||||
|
||||
+5
-1
@@ -1,5 +1,6 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
@@ -45,7 +46,10 @@ async def lifespan(application: FastAPI):
|
||||
application.state.store = store
|
||||
application.state.settings = settings
|
||||
application.state.s3 = S3Store(S3Settings.load())
|
||||
application.state.upload_slot = asyncio.Semaphore(1)
|
||||
concurrency = int(os.environ.get("UPLOAD_CONCURRENCY", "1"))
|
||||
if not 1 <= concurrency <= 8:
|
||||
raise ValueError("UPLOAD_CONCURRENCY must be 1..8")
|
||||
application.state.upload_slot = asyncio.Semaphore(concurrency)
|
||||
application.state.accepting_requests = True
|
||||
try:
|
||||
yield
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Safely reconcile attachment metadata and original S3 objects.
|
||||
|
||||
The command is dry-run by default. It only deletes unreferenced objects older
|
||||
than a configured grace period; missing objects are reported and never cause a
|
||||
metadata delete. That keeps a delayed PostgreSQL commit and active attachment
|
||||
records safe from a maintenance run.
|
||||
"""
|
||||
import argparse
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
|
||||
from .config import load_settings
|
||||
from .storage.postgres import PostgresStore
|
||||
from .storage.s3 import S3Settings, S3Store
|
||||
|
||||
|
||||
async def run(args) -> dict:
|
||||
settings = load_settings()
|
||||
db = PostgresStore(settings.database_url)
|
||||
s3 = S3Store(S3Settings.load())
|
||||
await db.connect()
|
||||
try:
|
||||
objects, metadata = await s3.list("originals/"), await db.attachment_keys()
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=args.grace_seconds)
|
||||
orphan = sorted(key for key, modified in objects.items()
|
||||
if key not in metadata and modified <= cutoff)
|
||||
fresh = sorted(key for key, modified in objects.items()
|
||||
if key not in metadata and modified > cutoff)
|
||||
missing = sorted({str(attachment_id): key for key, attachment_id in metadata.items()
|
||||
if key not in objects}.items())
|
||||
deleted = []
|
||||
if args.apply:
|
||||
for key in orphan:
|
||||
await s3.delete(key)
|
||||
deleted.append(key)
|
||||
return {
|
||||
"mode": "apply" if args.apply else "dry-run",
|
||||
"grace_seconds": args.grace_seconds,
|
||||
"s3_objects": len(objects),
|
||||
"metadata_rows": len(metadata),
|
||||
"orphan_candidates": orphan,
|
||||
"fresh_unreferenced": fresh,
|
||||
"missing_objects": [{"attachment_id": item[0], "object_key": item[1]} for item in missing],
|
||||
"deleted": deleted,
|
||||
}
|
||||
finally:
|
||||
s3.client.close()
|
||||
await db.close()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--apply", action="store_true", help="delete only aged orphan objects")
|
||||
parser.add_argument("--grace-seconds", type=int, default=3600)
|
||||
args = parser.parse_args()
|
||||
if not 0 <= args.grace_seconds <= 7 * 24 * 3600:
|
||||
parser.error("--grace-seconds must be 0..604800")
|
||||
print(json.dumps(asyncio.run(run(args)), ensure_ascii=False, sort_keys=True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -324,3 +324,11 @@ class PostgresStore:
|
||||
if row is None:
|
||||
raise ApiError(404, "not_found", "Вложение не найдено")
|
||||
return dict(row)
|
||||
|
||||
async def attachment_keys(self) -> dict[str, UUID]:
|
||||
"""Inventory used only by the maintenance reconciler."""
|
||||
try:
|
||||
rows = await self.pool.fetch("SELECT object_key, id FROM attachments")
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
return {row["object_key"]: row["id"] for row in rows}
|
||||
|
||||
@@ -69,6 +69,24 @@ class S3Store:
|
||||
await self.call("put_object", Bucket=self.settings.bucket, Key=key,
|
||||
Body=file, ContentLength=size, ContentType=content_type)
|
||||
|
||||
async def list(self, prefix: str) -> dict[str, object]:
|
||||
"""Return every object under a controlled prefix, handling S3 pagination."""
|
||||
result: dict[str, object] = {}
|
||||
token = None
|
||||
while True:
|
||||
args = {"Bucket": self.settings.bucket, "Prefix": prefix}
|
||||
if token:
|
||||
args["ContinuationToken"] = token
|
||||
page = await self.call("list_objects_v2", **args)
|
||||
for item in page.get("Contents", []):
|
||||
result[item["Key"]] = item["LastModified"]
|
||||
if not page.get("IsTruncated"):
|
||||
return result
|
||||
token = page["NextContinuationToken"]
|
||||
|
||||
async def delete(self, key: str) -> None:
|
||||
await self.call("delete_object", Bucket=self.settings.bucket, Key=key)
|
||||
|
||||
async def download(self, attachment):
|
||||
response = await self.call("get_object", Bucket=self.settings.bucket,
|
||||
Key=attachment["object_key"])
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Inject S3/DB disagreement and prove dry-run, grace period and safe repair."""
|
||||
import json
|
||||
import base64
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def compose(*args, input=None, env=None) -> str:
|
||||
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True,
|
||||
input=input, env=env)
|
||||
|
||||
|
||||
def reconcile(*args) -> dict:
|
||||
output = compose("--profile", "maintenance", "run", "--rm", "--no-deps", "reconcile", *args)
|
||||
return json.loads(next(line for line in reversed(output.splitlines()) if line.startswith("{")))
|
||||
|
||||
|
||||
def s3_code(action: str, key: str, data: bytes | None = None) -> None:
|
||||
code = """from src.storage.s3 import S3Settings, S3Store
|
||||
import base64, json, sys
|
||||
s3 = S3Store(S3Settings.load())
|
||||
payload = json.load(sys.stdin)
|
||||
key = payload['key']
|
||||
try:
|
||||
if sys.argv[1] == 'put':
|
||||
s3.client.put_object(Bucket=s3.settings.bucket, Key=key,
|
||||
Body=base64.b64decode(payload.get('data', 'b3JwaGFu')))
|
||||
else:
|
||||
s3.client.delete_object(Bucket=s3.settings.bucket, Key=key)
|
||||
finally:
|
||||
s3.client.close()
|
||||
"""
|
||||
payload = {"key": key}
|
||||
if data is not None:
|
||||
payload["data"] = base64.b64encode(data).decode()
|
||||
compose("run", "--rm", "--no-deps", "s3-init", "/app/.venv/bin/python", "-c", code, action,
|
||||
input=json.dumps(payload))
|
||||
|
||||
|
||||
def wait_ready(client: Client, env=None) -> None:
|
||||
subprocess.run(["docker", "compose", "up", "-d", "--wait", "--no-deps", "api-a"],
|
||||
cwd=ROOT, env=env, check=True, stdout=subprocess.DEVNULL)
|
||||
deadline = time.monotonic() + 15
|
||||
while True:
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, "stack did not recover")
|
||||
time.sleep(.5)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
client = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, bob, _eve, chat = client.bootstrap()
|
||||
image = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/attachments?filename="
|
||||
|
||||
def upload(name, expected=201):
|
||||
return client.call("POST", path + name, expected, actor=alice, raw=image,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment" if expected == 201 else None)
|
||||
|
||||
# A reference object must survive an apply sweep, even with zero grace.
|
||||
protected = upload("protected.png")["json"]
|
||||
orphan = "originals/test-orphan-" + uuid.uuid4().hex
|
||||
s3_code("put", orphan)
|
||||
|
||||
report = reconcile("--grace-seconds", "3600")
|
||||
check(orphan in report["fresh_unreferenced"], "fresh orphan missing from dry-run")
|
||||
check(not report["deleted"], "dry-run deleted an object")
|
||||
report = reconcile("--apply", "--grace-seconds", "3600")
|
||||
check(orphan in report["fresh_unreferenced"] and not report["deleted"], "grace period ignored")
|
||||
report = reconcile("--apply", "--grace-seconds", "0")
|
||||
check(report["deleted"] == [orphan], "aged orphan was not deleted safely")
|
||||
check(client.call("GET", "/api/v1/attachments/" + protected["id"] + "/content", actor=bob)["bytes"] == image,
|
||||
"reconciler deleted a referenced object")
|
||||
|
||||
# This models loss after metadata has committed: report it, do not delete metadata.
|
||||
missing = upload("missing.png")["json"]
|
||||
missing_key = "originals/" + missing["id"]
|
||||
s3_code("delete", missing_key)
|
||||
report = reconcile("--grace-seconds", "0")
|
||||
expected = {"attachment_id": missing["id"], "object_key": missing_key}
|
||||
check(expected in report["missing_objects"], "missing metadata/object pair not reported")
|
||||
client.call("GET", "/api/v1/attachments/" + missing["id"] + "/content", 503, actor=bob)
|
||||
s3_code("put", missing_key, image)
|
||||
check(client.call("GET", "/api/v1/attachments/" + missing["id"] + "/content", actor=bob)["bytes"] == image,
|
||||
"test object was not restored")
|
||||
print("PASS: dry-run, grace period, orphan deletion and missing-object reporting", flush=True)
|
||||
|
||||
# Inject a process-equivalent failure after PUT directly into the configured
|
||||
# replica. The public load balancer may correctly select the healthy peer,
|
||||
# which would not exercise this boundary.
|
||||
environment = dict(__import__("os").environ, UPLOAD_FAULT_AFTER_S3_PUT="1")
|
||||
try:
|
||||
subprocess.run(["docker", "compose", "up", "-d", "--force-recreate", "--no-deps", "api-a"],
|
||||
cwd=ROOT, env=environment, check=True, stdout=subprocess.DEVNULL)
|
||||
wait_ready(client, environment)
|
||||
fault = """import base64, json, sys, urllib.error, urllib.request
|
||||
payload = json.load(sys.stdin)
|
||||
request = urllib.request.Request('http://127.0.0.1:8080/api/v1/chats/' + payload['chat_id'] +
|
||||
'/attachments?filename=fault-after-put.png', data=base64.b64decode(payload['image']),
|
||||
method='POST', headers={'Authorization': 'Bearer ' + payload['token'], 'Content-Type': 'image/png'})
|
||||
try:
|
||||
urllib.request.urlopen(request, timeout=30)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 503, error.code
|
||||
assert json.load(error)['error']['code'] == 'unavailable'
|
||||
else:
|
||||
raise AssertionError('fault injection unexpectedly returned success')
|
||||
"""
|
||||
compose("exec", "-T", "api-a", "/app/.venv/bin/python", "-c", fault,
|
||||
input=json.dumps({"chat_id": chat["id"], "token": alice["token"],
|
||||
"image": base64.b64encode(image).decode()}))
|
||||
report = reconcile("--grace-seconds", "0")
|
||||
injected = [key for key in report["orphan_candidates"] if key.startswith("originals/")]
|
||||
check(injected, "injected post-PUT failure did not create a detectable orphan")
|
||||
report = reconcile("--apply", "--grace-seconds", "0")
|
||||
check(set(injected).issubset(report["deleted"]), "reconciler did not clean injected orphan")
|
||||
print("PASS: post-PUT/pre-DB injected failure leaves no permanent orphan", flush=True)
|
||||
finally:
|
||||
environment["UPLOAD_FAULT_AFTER_S3_PUT"] = "0"
|
||||
subprocess.run(["docker", "compose", "up", "-d", "--force-recreate", "--no-deps", "api-a"],
|
||||
cwd=ROOT, env=environment, check=True, stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prove that the API identity is bucket-scoped and lacks admin operations."""
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def compose(*args, input=None):
|
||||
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True,
|
||||
input=input, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
data = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
client.call("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=permission.png", 201,
|
||||
actor=alice, raw=data, headers={"Content-Type": "image/png"}, schema="Attachment")
|
||||
bucket = "permission-probe-" + uuid.uuid4().hex
|
||||
code = """from botocore.exceptions import ClientError
|
||||
from src.storage.s3 import S3Settings, S3Store
|
||||
import sys
|
||||
s3 = S3Store(S3Settings.load())
|
||||
try:
|
||||
try:
|
||||
s3.client.create_bucket(Bucket=sys.stdin.read().strip())
|
||||
except ClientError as error:
|
||||
assert error.response['Error']['Code'] in {'AccessDenied', 'Unauthorized'}, error.response
|
||||
else:
|
||||
raise AssertionError('API S3 identity unexpectedly has admin bucket creation')
|
||||
finally:
|
||||
s3.client.close()
|
||||
"""
|
||||
compose("exec", "-T", "api-a", "/app/.venv/bin/python", "-c", code, input=bucket)
|
||||
admin = """from src.storage.s3 import S3Settings, S3Store
|
||||
import sys
|
||||
s3 = S3Store(S3Settings.load())
|
||||
try:
|
||||
s3.client.list_buckets()
|
||||
finally:
|
||||
s3.client.close()
|
||||
"""
|
||||
compose("run", "--rm", "--no-deps", "s3-init", "/app/.venv/bin/python", "-c", admin)
|
||||
print("PASS: API identity cannot create buckets; maintenance identity has separate admin access")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Ten concurrent bounded uploads, with API-container peak memory sampling."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import http.client
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import quote
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def api_memory() -> dict[str, int]:
|
||||
ids = subprocess.check_output(["docker", "compose", "ps", "-q", "api-a", "api-b"], cwd=ROOT, text=True).split()
|
||||
return {container[:12]: int(subprocess.check_output(
|
||||
["docker", "exec", container, "cat", "/sys/fs/cgroup/memory.current"], text=True))
|
||||
for container in ids}
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument("--output", default="evidence/upload-memory.json")
|
||||
parser.add_argument("--size-mib", type=int, default=5)
|
||||
args = arguments(__doc__, configure)
|
||||
check(1 <= args.size_mib <= 10, "--size-mib must be 1..10")
|
||||
client = Client(args.base_url, args.ca_file, timeout=60)
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
seed = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
payload = seed + b"\0" * (args.size_mib * 1024 * 1024 - len(seed))
|
||||
baseline, peak, samples, stop = api_memory(), {}, [], threading.Event()
|
||||
|
||||
def sampler():
|
||||
while not stop.is_set():
|
||||
values = api_memory()
|
||||
samples.append(values)
|
||||
for name, value in values.items():
|
||||
peak[name] = max(peak.get(name, 0), value)
|
||||
time.sleep(.1)
|
||||
|
||||
def upload(index):
|
||||
parsed = urlsplit(client.base)
|
||||
connection = http.client.HTTPConnection(parsed.hostname, parsed.port, timeout=60)
|
||||
|
||||
def chunks():
|
||||
for offset in range(0, len(payload), 512 * 1024):
|
||||
yield payload[offset:offset + 512 * 1024]
|
||||
# Keep all ten client streams open long enough for multiple memory samples.
|
||||
time.sleep(.5)
|
||||
|
||||
connection.request("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=" + quote(f"load-{index}.png"),
|
||||
body=chunks(), encode_chunked=True,
|
||||
headers={"Authorization": "Bearer " + alice["token"], "Content-Type": "image/png"})
|
||||
response = connection.getresponse()
|
||||
body = response.read()
|
||||
connection.close()
|
||||
check(response.status == 201, "upload %s returned %s: %s" % (index, response.status, body[:200]))
|
||||
return json.loads(body)
|
||||
|
||||
started = time.monotonic()
|
||||
thread = threading.Thread(target=sampler, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
attachments = list(pool.map(upload, range(10)))
|
||||
finally:
|
||||
stop.set()
|
||||
thread.join(timeout=5)
|
||||
elapsed = time.monotonic() - started
|
||||
check(len({item["id"] for item in attachments}) == 10, "uploads were not distinct")
|
||||
report = {
|
||||
"uploads": 10, "file_bytes": len(payload), "concurrency": 10,
|
||||
"api_upload_concurrency_limit": 1, "elapsed_seconds": round(elapsed, 3),
|
||||
"baseline_memory_bytes": baseline, "peak_memory_bytes": peak,
|
||||
"peak_growth_bytes": {name: peak.get(name, 0) - baseline.get(name, 0) for name in baseline},
|
||||
"samples": len(samples),
|
||||
"method": "cgroup memory.current sampled through Docker every 0.1 seconds while clients send chunked 512 KiB blocks every 0.5 seconds; peak is not a continuous profiler.",
|
||||
}
|
||||
destination = ROOT / args.output
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
print(json.dumps(report, ensure_ascii=False))
|
||||
check(all(value <= 512 * 1024 * 1024 for value in peak.values()), "API exceeded configured memory limit")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user