9 Commits
1174 changed files with 562268 additions and 42 deletions
+1
View File
@@ -18,3 +18,4 @@ __pycache__
node_modules node_modules
evidence evidence
.DS_Store .DS_Store
infra/seaweedfs-s3.json
+61 -16
View File
@@ -1,20 +1,65 @@
# Copy to .env for your LOCAL synthetic test environment; never commit .env. # Copy to .env for your LOCAL synthetic teaching stand: `make env` generates
# These are logical interface suggestions; map actual framework names in REPORT.md. # random local credentials, writes this ignored file and the ignored
APP_HOST=0.0.0.0 # infra/seaweedfs-s3.json, and never prints secret values.
APP_PORT=8080
APP_ENV=lab APP_ENV=lab
SESSION_TTL_SECONDS=3600 LOG_LEVEL=info
# Choose credentials locally. File paths contain no secret values. APP_VERSION=1.0.0
DATABASE_URL_FILE=/run/secrets/database_url COMPOSE_PROJECT_NAME=mtusi-lab4-melnikov
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
SESSION_STORE=postgres # Local credentials. Never commit real values.
CACHE_URL_FILE=/run/secrets/cache_url POSTGRES_USER=messenger
API_REPLICAS=2 POSTGRES_DB=messenger
IDEMPOTENCY_TTL_SECONDS=86400 POSTGRES_PASSWORD=
S3_ENDPOINT=http://s3:9000 VALKEY_PASSWORD=
S3_REGION=us-east-1
# Private S3 store. The API identity is bucket-scoped; the administrative
# identity is used only by the one-shot s3-init container.
S3_BUCKET=messenger-attachments S3_BUCKET=messenger-attachments
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id S3_REGION=us-east-1
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key S3_ADMIN_ACCESS_KEY=
S3_ADMIN_SECRET_KEY=
S3_API_ACCESS_KEY=
S3_API_SECRET_KEY=
S3_TIMEOUT_SECONDS=10
# Public entrypoint: HAProxy on loopback only. API and S3 have no host port.
LB_PORT=8084
# Replica count and per-replica limits. The whole stand must fit the local
# Colima VM: 2 vCPU / 2 GiB (verified actual capacity in REPORT.md).
API_REPLICAS=2
API_CPU_LIMIT=0.5
API_MEM_LIMIT=384M
GOMEMLIMIT=300MiB
POSTGRES_CPU_LIMIT=0.5
POSTGRES_MEM_LIMIT=384M
VALKEY_CPU_LIMIT=0.1
VALKEY_MEM_LIMIT=96M
S3_CPU_LIMIT=0.4
S3_MEM_LIMIT=384M
LB_CPU_LIMIT=0.2
LB_MEM_LIMIT=64M
SESSION_TTL_SECONDS=3600
DB_MAX_CONNS=8
DB_MIN_CONNS=1
DB_CONNECT_TIMEOUT_SECONDS=3
DB_STATEMENT_TIMEOUT_SECONDS=3
DB_QUERY_TIMEOUT_SECONDS=3
CACHE_POOL_SIZE=8
CACHE_TIMEOUT_SECONDS=2
SHUTDOWN_TIMEOUT_SECONDS=6
SHUTDOWN_DRAIN_SECONDS=3
STARTUP_TIMEOUT_SECONDS=30
# Contract limits. The API refuses startup with larger values.
MAX_UPLOAD_BYTES=10485760 MAX_UPLOAD_BYTES=10485760
MAX_IMAGE_PIXELS=40000000 MAX_IMAGE_PIXELS=40000000
UPLOAD_DECODE_CONCURRENCY=1
# Single-node SeaweedFS was verified stable at one concurrent PUT per API
# replica; the API queues further uploads after their bounded temp file is
# complete. The API refuses to start with any other value.
S3_PUT_CONCURRENCY=1
# Build metadata, filled by make if not supplied.
GIT_REVISION=unknown
+3
View File
@@ -30,3 +30,6 @@ coverage/
.vscode/ .vscode/
# Keep small, sanitized evidence summaries in evidence/ under version control. # Keep small, sanitized evidence summaries in evidence/ under version control.
# Inspect git diff --cached: ignore rules are not a secret scanner. # Inspect git diff --cached: ignore rules are not a secret scanner.
# Local SeaweedFS identities generated from .env by make env.
infra/seaweedfs-s3.json
+81
View File
@@ -0,0 +1,81 @@
# syntax=docker/dockerfile:1
# Compile stage. Dependencies are vendored, so the build needs no module proxy
# and the same source tree produces the same binaries from a clean clone.
FROM golang:1.25.1-alpine3.22@sha256:b6ed3fd0452c0e9bcdef5597f29cc1418f61672e9d3a2f55bf02e7222c014abd AS build
WORKDIR /src
ENV CGO_ENABLED=0 \
GOTOOLCHAIN=local \
GOFLAGS=-mod=vendor
COPY go.mod go.sum ./
COPY vendor ./vendor
COPY cmd ./cmd
COPY internal ./internal
ARG VERSION=1.0.0
ARG REVISION=unknown
RUN go build \
-trimpath \
-buildvcs=false \
-ldflags="-s -w -buildid= -X main.version=${VERSION} -X main.revision=${REVISION}" \
-o /out/messenger \
./cmd/messenger \
&& go build \
-trimpath \
-buildvcs=false \
-ldflags="-s -w -buildid= -X main.revision=${REVISION}" \
-o /out/migrate \
./cmd/migrate \
&& go build \
-trimpath \
-buildvcs=false \
-ldflags="-s -w -buildid= -X main.revision=${REVISION}" \
-o /out/s3bootstrap \
./cmd/s3bootstrap \
&& go build \
-trimpath \
-buildvcs=false \
-ldflags="-s -w -buildid= -X main.revision=${REVISION}" \
-o /out/s3ctl \
./cmd/s3ctl \
&& go build \
-trimpath \
-buildvcs=false \
-ldflags="-s -w -buildid= -X main.revision=${REVISION}" \
-o /out/reconciler \
./cmd/reconciler
# Runtime stage: minimal Alpine pinned by digest, no shell tooling and no
# package manager calls. The process runs as the unprivileged uid 10001.
FROM alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1 AS runtime
LABEL org.opencontainers.image.title="mtusi-messenger-lab4" \
org.opencontainers.image.description="MTUSI highload lab 4: HAProxy, replicated API, PostgreSQL, Valkey and a private S3 store" \
org.opencontainers.image.version="1.0.0"
WORKDIR /app
COPY --from=build --chown=10001:10001 /out/messenger /app/messenger
COPY --from=build --chown=10001:10001 /out/migrate /app/migrate
COPY --from=build --chown=10001:10001 /out/s3bootstrap /app/s3bootstrap
COPY --from=build --chown=10001:10001 /out/s3ctl /app/s3ctl
COPY --from=build --chown=10001:10001 /out/reconciler /app/reconciler
USER 10001:10001
EXPOSE 8080
ENV APP_HOST=0.0.0.0 \
APP_PORT=8080 \
APP_ENV=lab \
LOG_LEVEL=info \
SESSION_TTL_SECONDS=3600 \
SHUTDOWN_TIMEOUT_SECONDS=6 \
SHUTDOWN_DRAIN_SECONDS=3
# The same binary implements -healthcheck, so the image needs no curl/wget and
# the probe runs as the unprivileged user.
HEALTHCHECK --interval=3s --timeout=2s --start-period=10s --retries=3 \
CMD ["/app/messenger", "-healthcheck"]
ENTRYPOINT ["/app/messenger"]
+89
View File
@@ -0,0 +1,89 @@
# ЛР 4 — БВТ2301 — Мельников — на 5
- **Fork:** https://gitea.privcloud.tech/MelnikStalker/mtusi2026lab4
- **Source branch:** `solution/bvt2301-melnikov` → **base:** `main`
официального `mtusi2026/mtusi2026lab4`.
## Заголовок MR
`ЛР 4 — БВТ2301 — Мельников — на 5`
## Что реализовано
- Приватный S3-совместимый сервер SeaweedFS 3.98 (образ закреплён digest'ом) в общем Compose-стенде; bucket `messenger-attachments` создаётся идемпотентным one-shot `s3-init`.
- Attachment: метаданные в PostgreSQL, оригинал в приватном bucket, object key назначает сервер (`attachments/<uuid>`), `filename` — только отображение.
- Синхронный binary upload PNG/JPEG через `POST /api/v1/chats/{chat_id}/attachments?filename=…`: 201 `ready` только после S3 PUT и COMMIT; download через авторизованный API без redirect.
- Лимиты 10 MiB / 40 млн пикселей, MIME по содержимому, безопасные filename, потоковая запись в ограниченный tmpfs, decode semaphore, bounded S3 PUT concurrency, таймауты.
- ACL: посторонний получает 404 на metadata и bytes; файл другого чата нельзя привязать к сообщению; идемпотентность сообщений учитывает `attachment_ids`.
- `Idempotency-Key` с lab3, общие сессии в Valkey, 2 API-реплики, HAProxy, graceful shutdown, keyset-пагинация, строгий JSON.
- Track 2: отдельный `cmd/reconciler` с dry-run/apply, grace period, повторной проверкой БД, удалением stale pending/orphan и отчётом `missing_objects` без выдачи их за ready.
- Compose: PostgreSQL 16.4, Valkey 8.0.2, SeaweedFS 3.98, HAProxy 3.0; только `127.0.0.1:8084` опубликован; API/S3/admin — во внутренней сети; named volumes с префиксом `mtusi-lab4-melnikov-`.
## Запуск из чистого clone
```sh
git clone --branch solution/bvt2301-melnikov \
https://gitea.privcloud.tech/MelnikStalker/mtusi2026lab4.git lab4
cd lab4
git switch solution/bvt2301-melnikov
make env
make check
make up
make test
```
Полная инструкция, схема, ограничения и доказательства — в [REPORT.md](REPORT.md). Секреты создаются только локально (`make env`), в Git не попадают.
## Результаты проверок
Выполнено на ревизии `02fc97b78aff9a1890bd2bade40f6cd8654e2000`, 2 vCPU / 2 GiB:
| Команда | Результат |
| --- | --- |
| `make check` | PASS |
| `make validate PYTHON=.venv/bin/python` | PASS |
| `make test` | PASS (lab4 public smoke) |
| `make test-student` | PASS, 149 проверок blackbox + Go tests |
| `make test-student-race` | PASS |
| `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS |
| `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | PASS, 130+ записей, recovery ~3.2 с |
| `make test-attachment` | PASS, 39 assertions |
| `make test-container` | PASS |
| `make test-consistency` | PASS, 68 assertions, cost 11 мс median |
| `make experiment` | PASS, 12 concurrent, 0 errors, peak process HWM 53.6/53.3 МБ при лимите 384 МБ |
| `make py39` | PASS на Python 3.9.6 |
Сырые логи: `evidence/commands/`, метрики: `evidence/experiment/`, `evidence/track2/`, `evidence/resilience/`, инфраструктура: `evidence/container-checks.json`.
## Чеклист
- [x] Весь обязательный минимум lab4 и предыдущих работ сохранён с объявленными переходами.
- [x] Контракт и публичные `tests/` не ослаблены.
- [x] `make check`, `make validate`, `make test` выполнены с реальным выводом.
- [x] Persistence и failover hooks проверены на реальных контейнерах; upload→stop→download даёт тот же SHA-256.
- [x] Негативные и граничные случаи (размер, пиксели, MIME, повреждение, filename, ACL, недоступность S3/БД, прерванный upload) проверены.
- [x] Обязательный эксперимент ≥10 одновременных загрузок с честным RSS/HWM и отдельной cgroup-метрикой.
- [x] Track 2: dry-run/apply/rerun, grace period, защита свежих/активных/используемых, стоимость обхода.
- [x] Bucket bootstrap идемпотентен; API credentials ограничены bucket'ом; anonymous S3 GET/list → 403.
- [x] Секреты и токены не в Git и не в evidence.
- [x] README задания сохранён; REPORT.md описывает именно это решение.
- [x] Чистый clone проверен отдельным прогоном с пустыми volumes.
## Ограничения
Стенд однохостовый; HAProxy/PostgreSQL/Valkey/S3 — единые точки отказа. Reconciler не восстанавливает missing-объекты автоматически: он их обнаруживает и оставляет оператору, чтобы не маскировать потерю данных. Single-node SeaweedFS стабилен при одном PUT на API-реплику; это ограничение стенда. Подробнее — в [REPORT.md](REPORT.md).
## Источники и ИИ
Скелет и контракт lab4 — официальный репозиторий `mtusi2026/mtusi2026lab4` (HEAD `ec540a1a…`). Собственный код lab3 перенесён как источник реализации. Вся работа выполнена одним DeepSeek-агентом в DeepSeek Harness через Orca; отдельного ревьюера не подключали. Внешний код не копировался; публичные зависимости зафиксированы в `go.mod`/`vendor` и Compose digest'ами.
## Публикация
- Fork: https://gitea.privcloud.tech/MelnikStalker/mtusi2026lab4.
- Ветка `solution/bvt2301-melnikov` опубликована из fork в официальный
`mtusi2026/mtusi2026lab4` (base `main`); MR — заявка на проверку, не слияние.
- Принятый коммит решения — `d4529a27e86e40d41daafa2af7e6e45703ff8492`;
публикационные правки этого файла и `REPORT.md` идут отдельным docs-коммитом
поверх него.
- В MR приложены `make check`/`make test`/failover/persistence/track2/
experiment и ссылка на `REPORT.md`.
+85 -5
View File
@@ -1,13 +1,31 @@
PYTHON ?= python3 PYTHON ?= python3
BASE_URL ?= http://localhost:8080 GO ?= go
BASE_URL ?= http://127.0.0.1:8084
CA_FILE ?= CA_FILE ?=
ACTION_SCRIPT ?= ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
COMPOSE ?= ./scripts/compose.sh
COMPOSE_ARGS = --env-file .env
IMAGE ?= mtusi-messenger-lab4-melnikov:local
GIT_REVISION ?= $(shell git rev-parse HEAD 2>/dev/null || echo unknown)
export GIT_REVISION
export API_IMAGE ?= $(IMAGE)
.PHONY: help check validate test load test-persistence test-failover .PHONY: help check validate env up wait build-image docker-config stop down purge logs ps \
test load test-persistence test-failover test-student test-student-race \
test-attachment test-container test-consistency experiment clean-clone py39 collect-evidence
help: help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API"
@echo "env: create ignored .env and infra/seaweedfs-s3.json; up: build+start stack; wait: wait for /health/ready"
@echo "stop: stop containers (data kept); down: remove containers (volumes kept); purge: DELETE volumes and data"
@echo "test-student: Go tests + black-box lab4 suite; test-student-race: Go race detector"
@echo "test-persistence: ACTION_SCRIPT=scripts/restart.sh; test-failover: ACTION_SCRIPT=scripts/stop-one.sh"
@echo "test-attachment: upload limits/ACL/consistency negatives; test-container: infra/S3 privacy checks"
@echo "test-consistency: reconciler dry-run/apply/grace scenario (track 2)"
@echo "experiment: >=10 concurrent uploads with API RSS sampling"
@echo "clean-clone: build and smoke a fresh clone with empty volumes; py39: run suites on Python 3.9"
@echo "collect-evidence: rerun all mandatory/own checks and keep raw stdout in evidence/commands"
check: check:
$(PYTHON) scripts/check_contract.py $(PYTHON) scripts/check_contract.py
@@ -21,10 +39,72 @@ test:
load: load:
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
env:
./scripts/init-env.sh
up:
@test -f .env || (echo "Run make env first" >&2; exit 2)
GIT_REVISION="$(GIT_REVISION)" API_IMAGE="$(IMAGE)" $(COMPOSE) $(COMPOSE_ARGS) up -d --build
./scripts/wait-ready.sh
wait:
./scripts/wait-ready.sh
build-image:
@test -f .env || (echo "Run make env first" >&2; exit 2)
GIT_REVISION="$(GIT_REVISION)" API_IMAGE="$(IMAGE)" $(COMPOSE) $(COMPOSE_ARGS) build api
docker-config:
GIT_REVISION="$(GIT_REVISION)" API_IMAGE="$(IMAGE)" $(COMPOSE) $(COMPOSE_ARGS) config --quiet
stop:
$(COMPOSE) $(COMPOSE_ARGS) stop
down:
$(COMPOSE) $(COMPOSE_ARGS) down
purge:
@echo "PURGE removes containers AND named volumes mtusi-lab4-melnikov-*: all synthetic data is lost."
$(COMPOSE) $(COMPOSE_ARGS) down -v
logs:
$(COMPOSE) $(COMPOSE_ARGS) logs --tail=100 api
ps:
$(COMPOSE) $(COMPOSE_ARGS) ps
test-persistence: test-persistence:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook" >&2; exit 2)
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
test-failover: test-failover:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook" >&2; exit 2)
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
test-student:
$(GO) test -count=1 ./...
$(PYTHON) student-tests/blackbox.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-student-race:
$(GO) test -race -count=1 ./...
test-attachment:
$(PYTHON) student-tests/attachment-checks.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-container:
$(PYTHON) scripts/container-checks.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-consistency:
$(PYTHON) scripts/track2.py --base-url "$(BASE_URL)" $(TLS_ARGS)
experiment:
$(PYTHON) scripts/upload-experiment.py --base-url "$(BASE_URL)" $(TLS_ARGS)
clean-clone:
./scripts/clean-clone-check.sh
py39:
./scripts/py39-tests.sh
collect-evidence:
./scripts/collect-evidence.sh
+176 -21
View File
@@ -1,37 +1,192 @@
# Отчёт — лабораторная 4 # Отчёт — лабораторная 4
- Автор, группа: TODO - Автор, группа: Мельников Иван Дмитриевич, БВТ2301
- Целевая оценка; выбранный трек 5, если нужен: TODO - Целевая оценка: **5**, выбранный трек 5: **Трек 2 «Согласованность двух хранилищ»**
- Commit/PR: TODO после публикации - Исходный репозиторий: <https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4>, ветка `main`, HEAD `ec540a1a725862a8619fcb758daec4ad197f0dd5`
- Использованные источники, библиотеки и помощь ИИ: TODO - Ветка решения: `solution/bvt2301-melnikov`; кодовый commit: `02fc97b78aff9a1890bd2bade40f6cd8654e2000`; принятый финальный commit: `d4529a27e86e40d41daafa2af7e6e45703ff8492`
- Fork/PR: <https://gitea.privcloud.tech/MelnikStalker/mtusi2026lab4>; MR открыт в `mtusi2026/mtusi2026lab4` из этой ветки в `main` как заявка на проверку, не слияние.
- Источники: [README.md](README.md), [COURSE.md](COURSE.md), [CONTRIBUTING.md](CONTRIBUTING.md), [contracts/README.md](contracts/README.md), [contracts/openapi.json](contracts/openapi.json), [tests/README.md](tests/README.md). Собственный код lab3 перенесён как источник реализации, но не как контракт lab4.
- Библиотеки: Go 1.25.1 (`pgx/v5`, `go-redis/v9`, `minio-go/v7`, `golang.org/x/crypto`), стандартный `image/png`, `image/jpeg`; Python 3.9+ только stdlib для проверок и экспериментов.
- ИИ: вся реализация, проверки и текст выполнены одним DeepSeek-агентом в DeepSeek Harness через Orca. Отдельного ревьюера/Astra не подключали; внешний код не копировался, кроме собственной lab3 и публичных зависимостей.
## Запуск из чистого clone ## 1. Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. Требуется Docker с Compose (проверено: Docker 27.4.0, Colima 2 vCPU / 2 054 631 424 байт RAM, macOS arm64), Go 1.25.1 и Python 3.9+. Исходный сервер lab4 не требуется.
## Архитектура и решения ```sh
git clone --branch solution/bvt2301-melnikov \
https://gitea.privcloud.tech/MelnikStalker/mtusi2026lab4.git lab4
cd lab4
git switch solution/bvt2301-melnikov
make env # создаёт .env и infra/seaweedfs-s3.json с локальными случайными секретами (mode 600, оба в .gitignore)
make check
make validate PYTHON=.venv/bin/python # после python3 -m venv .venv && pip install -r requirements-dev.txt
make up # build + migrate + s3-init + 2 API + PostgreSQL + Valkey + SeaweedFS + HAProxy
make test
```
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. `make env` не печатает секреты. Стенд публикует только HAProxy на `127.0.0.1:8084` (`LB_PORT`); API, PostgreSQL, Valkey, SeaweedFS master/filer/volume/S3 и admin-порты не публикуются. Compose-проект и все named volumes имеют префикс `mtusi-lab4-melnikov-`. API-образ — `mtusi-messenger-lab4-melnikov:local`, собирается из vendored-зависимостей; внешние образы закреплены digest'ами:
## Доказательства критериев | Роль | Образ |
| --- | --- |
| PostgreSQL | `postgres:16.4-alpine3.20@sha256:5660c2cb…37e64c` |
| Valkey | `valkey/valkey:8.0.2-alpine@sha256:752ba000…65ebb6d` |
| S3 | `chrislusf/seaweedfs:3.98@sha256:2f7de737bd35c5e2cf93944e8aa66de802a135f068ea285d8d290d0206347d22` |
| LB | `haproxy:3.0-alpine@sha256:457d1c0d…5dbe3` |
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | Остановка и удаление данных разделены:
```sh
make stop # остановить контейнеры; volumes и данные сохраняются
make down # удалить контейнеры; volumes сохраняются
make purge # ЯВНО удалить контейнеры И volumes mtusi-lab4-melnikov-*: учебные данные теряются
```
`make restart`-хук для persistence: `scripts/restart.sh` перезапускает API, PostgreSQL, Valkey и SeaweedFS без удаления volumes. Failover-хук: `scripts/stop-one.sh` останавливает ровно тот API-контейнер, чей hostname совпадает с `TARGET_INSTANCE_ID`, и оставляет его остановленным; восстановление — отдельно (`./scripts/compose.sh --env-file .env up -d --no-deps api`).
Проверено на чистом clone: сборка, миграции с нуля, идемпотентный bucket bootstrap, `make test`, `make test-student`, `make test-persistence`; временные контейнеры/сеть/volumes клона удалены. См. `evidence/clean-clone.txt` (добавляется отдельным docs/evidence commit после прогона).
## 2. Архитектура и решения
```text
Клиент → HAProxy :8084 → API-1 / API-2 (stateless, Go) → PostgreSQL 16.4 (метаданные, пользователи, чаты, сообщения, идемпотентность)
└→ Valkey 8.0.2 (общие серверные сессии)
└→ приватный SeaweedFS 3.98 S3 (байты оригиналов)
```
- **PostgreSQL — источник истины для метаданных.** Таблицы `attachments` и `message_attachments` введены миграцией `0004_attachments.sql`; `0005_message_empty_text.sql` разрешает `text=""` только вместе с вложениями (пустой текст без вложений по-прежнему 400 в handler). Композитные FK `(attachment_id, chat_id) → attachments(id, chat_id)` и `(message_id, chat_id) → messages(id, chat_id)` не позволяют привязать файл другого чата даже при ошибке будущего кода.
- **S3 — источник истины для байтов.** Bucket `messenger-attachments` приватен. Object key назначает сервер: `attachments/<attachment-uuid>`; `filename` — только отображаемое имя, не путь и не ключ. API не хранит оригинал в локальном каталоге и не имеет state-volume; `/tmp` — tmpfs только для ограниченного staging одной загрузки.
- **Две identity S3.** `s3-init` использует административную identity только для создания bucket и probe; API получает отдельную bucket-scoped identity (`Read/Write/List` только этого bucket). В API-контейнере нет `S3_ADMIN_*`, а его ключи не равны административным. Административная консоль/порты SeaweedFS не публикуются.
- **Синхронный upload.** `POST /api/v1/chats/{chat_id}/attachments?filename=…` принимает сырые `image/png`/`image/jpeg` (не multipart). Тело читается потоково в ограниченный временный файл с одновременным SHA-256; до S3/БД проверяются размер, `Content-Type` по первым байтам, декодирование заголовка, число пикселей и полнота изображения. Затем создаётся внутренняя строка `status=pending`, выполняется S3 PUT, и только после успешного `UPDATE … status=ready` клиент получает `201 Attachment` с `status=ready`, `variants=[]`, `error_code=null`. При 201 и метаданные, и байты уже сохранены.
- **Download.** `GET /api/v1/attachments/{id}` и `/content` проверяют членство в чате в SQL; посторонний/неизвестный id — одинаковый 404. `/content` отдаёт байты через API без redirect, с истинным `Content-Type` и `Content-Length`. Отсутствующий объект ready-строки не выдаётся за готовый: metadata/content возвращают 404; `variant` кроме `original` — 404.
- **Сохранение lab3.** Перенесены Argon2id, общие сессии в Valkey, строгий JSON, keyset-пагинация, общий `Idempotency-Key` с атомарным CTE/транзакцией, 2+ stateless реплики, HAProxy, health/readiness, graceful drain. Текстовые POST без `attachment_ids` работают как раньше и возвращают `attachment_ids: []`. Хэш идемпотентности включает `attachment_ids`, поэтому изменённый payload с тем же ключом даёт 409, а отсутствующее поле и `[]` семантически равны.
- **Ограничения одной загрузки.** 10 485 760 байт, 40 000 000 пикселей; лимит объявленного `Content-Length` проверяется до чтения, для chunked/неизвестной длины работает `http.MaxBytesReader`; `image.DecodeConfig` проверяет пиксели до полного decode. Декодирование ограничено семафором `UPLOAD_DECODE_CONCURRENCY=1` на реплику. S3 PUT ограничен `S3_PUT_CONCURRENCY=1` на реплику: дальнейшие загрузки ждут, уже находясь в ограниченном tmpfs, а не в неограниченной RAM. S3-операция ограничена 10 с, HTTP write timeout — 20 с, graceful shutdown — 6 с после 3 с drain.
- **Почему S3 PUT = 1 на реплику.** При нагрузочной проверке single-node SeaweedFS 3.80/3.98 с двумя одновременными многомегабайтными PUT на реплику периодически перезапускался (соединение рвалось, клиент получал 503). С одним PUT на реплику (2 на стенд из двух реплик) пять серий по 12 одновременных загрузок прошли без перезапуска S3. Это документированное ограничение стенда, а не пропуск ошибки: клиентская конкурентность остаётся ≥10, а очередь ограничена.
- **S3 healthcheck** проверяет фактический S3-порт 8333, а не только master 9333: иначе `s3-init` мог стартовать до готовности gateway. DNS для `s3` настроен fail-closed (`dns_search: invalid`), чтобы остановленный alias не разрешался через публичный поисковый домен.
### Согласованность S3/PostgreSQL и reconciler (Трек 2)
Инвариант: у каждой ready-строки есть объект; у каждого объекта, созданного API, есть строка (пока идёт upload — `pending`). Возможные состояния и реакция:
| Состояние БД | Объект S3 | Возраст | Действие |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO | | ready | есть | любой | OK, не трогать |
| Остальные пункты уровня 3 | TODO | TODO | TODO | | pending | есть/нет | < grace | защищено: активная загрузка или свежий intent |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | | pending | есть | ≥ grace | удалить строку, затем объект (сначала строка — иначе гонка с MarkReady) |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO | | pending | нет | ≥ grace | удалить строку |
| нет строки | есть | ≥ grace | orphan: удалить объект после повторной проверки БД |
| нет строки | есть | < grace | защищено: возможен PUT, чей COMMIT ещё не прошёл |
| ready | нет | любой | **не удалять и не выдавать за ready**: unresolved, нужен оператор (восстановить объект/разобрать метаданные) |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. Механизм: перед каждым удалением reconciler заново читает строку/ключ из PostgreSQL; удаление pending-строки условное (`WHERE status='pending'`); удаление объекта выполняется только после успешного удаления строки. `-apply` и dry-run — отдельные режимы; по умолчанию grace 1 час (`-grace`/`RECONCILE_GRACE_SECONDS` можно уменьшить для эксперимента). Reconciler — отдельный бинарник `/app/reconciler`, запускается одной off-контейнерной командой `compose run --rm --no-deps … api`; публичного API он не добавляет.
## Эксперименты и отказы ## 3. Доказательства критериев
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. Все команды выполнялись на ревизии `02fc97b…`, образе API `sha256:9f46ec2a6cf007f77202d3ae97afc0f710ee3cd191b8c620405f397b193932ce`, S3-образе `sha256:0513e5e4…508ad5ba`, 2 vCPU / 2 GiB. Полные stdout — в `evidence/commands/`, сводка — `evidence/commands/summary.txt` (15 команд, все exit 0).
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | ### Уровень 3
| Критерий README | Команда/сценарий | Наблюдаемый результат | Доказательство |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| TODO | TODO | TODO | TODO | | Возможности lab3 сохранены | `make test-student`, `make py39` | 149 проверок blackbox: регистрация/вход, строгий JSON, Unicode, ACL 404, пагинация, конкурентная регистрация/сообщения/идемпотентность; 2 реплики | `evidence/commands/go_tests.txt`, `smoke_python39.txt` |
| S3 в общем стенде; метаданные в PostgreSQL, байты в приватном bucket | `make test-container` | 2 API + PostgreSQL + Valkey + SeaweedFS + HAProxy; API без state-volume; S3 volume `…-s3data`; anonymous GET/list → 403 | `evidence/container-checks.json`, `evidence/commands/container_checks.txt` |
| POST вложения → 201 ready после сохранения; оригинал побайтно | `make test`, `make test-attachment` | 201 `status=ready`, SHA-256/размер совпадают, download == исходник; на границе 10 406 995 байт | `evidence/commands/smoke.txt`, `attachment_checks.txt` |
| Message с attachment_ids читается участниками | `make test`, `make test-student` | `text=""` + 10 вложений, порядок сохранён; участник читает, посторонний 404 | `evidence/commands/smoke.txt`, `go_tests.txt` |
| PNG/JPEG ≤10 MiB, ≤40 млн пикселей, MIME по содержимому, опасные filename, лимиты до чтения/декодирования | `make test-attachment` | 39 assertions: 413 на 10 MiB+1 и >40 MP, 415 на ложный MIME/повреждение/empty/multipart, 400 на `/`,`\\`,NUL,control,256 code points; Unicode имя принято | `evidence/commands/attachment_checks.txt` |
| Upload → stop обслужившей реплики → download через другую = тот же файл | `make test-failover`, `scripts/failover-upload.py` | uploader `773413…` остановлен (`exited`); download `9d9d4b…`; SHA-256 `0011ea7e…` совпал | `evidence/resilience/failover-upload.json`, `evidence/commands/failover_upload.txt` |
| Restart с volumes сохраняет метаданные и оригинал | `make test-persistence`, `scripts/persistence-evidence.py` | тот же токен, сообщение, метаданные и байты; container ids те же, StartedAt изменён у API/PostgreSQL/Valkey/S3; volumes не изменились | `evidence/resilience/persistence.json`, `evidence/commands/persistence_evidence.txt` |
## Ограничения и следующие шаги ### Уровень 4
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. | Критерий README | Команда/сценарий | Наблюдаемый результат | Доказательство |
| --- | --- | --- | --- |
| Негативы: большой файл, повреждение, подмена MIME, чужой attachment_id, файл другого чата; пользовательская ошибка не 500 | `make test-attachment` | все перечисленные случаи дают 400/404/413/415; 500 не наблюдался; при недоступном S3 валидация всё равно 415, а не 500 | `evidence/commands/attachment_checks.txt` |
| Прерывание/отказ между S3 и БД не оставляет вечных объектов; документированный механизм с grace | `make test-consistency` | dry-run нашёл stale orphan + 2 stale pending + 2 missing; apply удалил 2 объекта и 2 строки; свежие/активные/используемые сохранены; повторный apply — 0 удалений; после grace удалён только свежий orphan | `evidence/track2/summary.json`, `evidence/commands/track2.txt` |
| Лимиты/таймауты/потоковость; эксперимент ≥10 загрузок с пиком RAM | `make experiment` | 12 одновременных, 12×201, wall 1.088 с; peak process RSS HWM 53.6 МБ и 53.3 МБ при лимите 384 МБ; cgroup peak 68.7/59.4 МБ отдельно | `evidence/experiment/summary.json`, `rss-samples.json`, `evidence/commands/experiment.txt` |
| Bucket bootstrap идемпотентен; API — ограниченные credentials; админ-консоль не в общей сети; private bucket | `make test-container` | второй запуск `created:false, verified:true`; API key ≠ admin, административных ключей в API нет, другой bucket → denied; anonymous GET/list 403; порты S3 не опубликованы | `evidence/container-checks.json`, `evidence/commands/container_checks.txt` |
### Трек 2 (оценка 5)
| Требование трека | Как проверено | Результат |
| --- | --- | --- |
| Повторяемый reconciler для orphan/missing объектов и метаданных | `cmd/reconciler` + `scripts/track2.py`; 300 вложений (150 в сообщениях), 3 прогона dry-run | PASS, 68 assertions |
| Гипотеза, протокол, критерии безопасности | раздел 2 и `summary.json` (hypothesis/protocol/limitations) | инвариант + grace + re-check + запрет удаления used/fresh |
| Реальные ошибки на обеих сторонах | внедрены: stale orphan (S3), stale pending с объектом и без (БД), missing object для used/unused, fresh orphan, active pending | dry-run обнаружил все; apply исправил только доказуемо stale |
| Dry-run без мутаций | сравнение counts/наличия объектов и строк до/после | 0 удалений, все объекты/строки на месте |
| Безопасное исправление и повторный запуск | apply, затем immediate rerun | удалено 2 объекта/2 строки; rerun — 0 удалений |
| Свежие/активно загружаемые/используемые не удаляются | fresh orphan, active pending, 150 linked attachments, 6 реальных загрузок во время apply | active promoted ready и скачан; used SHA не изменился; fresh удалён только после grace |
| Grace period | `-grace 20s`; stale ждали 20+ с, fresh — нет | fresh protected в dry/apply/rerun, затем удалён после 20 с |
| API после сверки | 15 used messages, download used, foreign 404, missing 404, новый upload | PASS |
| Стоимость обхода | 321 строка/321 объект, 3 запуска | median total 11 мс (DB 4 мс, S3 list 6 мс); O(N) |
## 4. Эксперименты и отказы
### 4.1. Обязательный эксперимент: 12 одновременных загрузок
Гипотеза: при потоковой записи тела в ограниченный tmpfs, одном decode и одном S3 PUT на реплику пик процесса ограничен и не зависит от числа клиентов. Профиль: 6×1000×700 (2.10 МБ), 4×1500×1100 (4.95 МБ), 2×1600×2167 (10.41 МБ, граница 10 MiB); всего 53 233 100 байт, max 3 467 200 пикселей. API перезапущены перед прогоном, чтобы `VmHWM` начинался с нуля. Сэмплирование `/proc/1/status` (VmRSS/VmHWM) через `docker exec` каждые ~0.2 с; cgroup `memory.current/peak` — отдельная метрика.
| Метрика (источник) | API-1 | API-2 |
| --- | --- | --- |
| Baseline process RSS (VmRSS) | 32.4 МБ | 32.6 МБ |
| Peak sampled process RSS (VmRSS) | 53.1 МБ | 43.8 МБ (пик между сэмплами) |
| **Peak process RSS (VmHWM, kernel high-water)** | **53.6 МБ** | **53.3 МБ** |
| Peak cgroup memory.current (весь контейнер) | 58.4 МБ | 54.1 МБ |
| Peak cgroup memory.peak (весь контейнер) | 68.7 МБ | 59.4 МБ |
| Container memory limit | 384 МБ | 384 МБ |
- Фактическая конкурентность: **12** (12 успешных 201, 0 ошибок), wall **1.025 с**, по 6 загрузок на каждую реплику.
- Bounded memory: тело не буферизуется целиком в RAM, а потоково пишется в tmpfs; `MAX_UPLOAD_BYTES` и `MaxBytesReader` ограничивают вход; `image.DecodeConfig` отсекает >40 MP до полного decode; decode semaphore = 1; S3 PUT semaphore = 1; `GOMEMLIMIT=300MiB`; HTTP timeouts. При 12 клиентах PI-лимит 384 МБ не приближается: HWM ≤ 53.6 МБ.
- Ограничение измерения: сэмплер успел 4 среза (docker exec дорогой), поэтому на API-2 пик RSS между сэмплами не поймано; `VmHWM` (kernel high-water) закрывает этот пробел. cgroup включает page cache и не является RSS.
### 4.2. Трек 2: стоимость и сценарий
| Фаза | Что сделано | Результат |
| --- | --- | --- |
| База | 300 вложений по 111 817 Б, 150 привязаны к 15 сообщениям | 321 строка/321 объект на момент замера (включая данные публичных тестов) |
| Cost | 3 dry-run подряд | total 11/11/10 мс; median 11 мс; DB scan 4 мс, S3 list 6 мс |
| Inject | stale orphan; stale pending+object; stale pending без object; missing used; missing unused; fresh orphan; active pending | обнаружены все 7 категорий |
| Dry-run | `-grace 20s` без `-apply` | 0 мутаций; orphan/stale/missing перечислены; fresh/active в protected |
| Apply | `-apply -grace 20s`, одновременно 6 реальных загрузок | удалено 2 объекта и 2 строки; 6 загрузок 201; used/active целы; 2 missing — unresolved |
| Rerun | immediate `-apply` | 0 удалений |
| Grace | ждали >20 с, `-apply` | удалён только fresh orphan; ready-вложение активно и скачивается |
### 4.3. Отказы
| Воздействие | Ожидание | Наблюдение | Восстановление/потери |
| --- | --- | --- | --- |
| `docker compose stop s3` | upload/metadata/content → 503, валидация → 415, текст → 201 | так и произошло; 500 не было | `start s3`, wait healthy; существующий файл скачан, новый upload 201 |
| `docker compose stop postgres` | readiness/GET/me/POST → 503, liveness 200, bad auth → 401 | так и произошло | `start postgres`, wait ready; данные/сессия целы |
| `scripts/stop-one.sh` (API) | hook ≤10 с, реплика exited, запись восстанавливается ≤10 с, дублей нет | 130–138 успешных записей, 0 failed attempts, recovery ~3.2 с; goal replica не в последних ответах | восстановлена `up -d --no-deps api` |
| `scripts/restart.sh` | реальные контейнеры API+PostgreSQL+Valkey+S3 перезапущены, volumes сохранены | ids те же, StartedAt изменён, volumes те же, токен/сообщение/файл живы | hook ~52 с (S3 healthcheck), публичный тест PASS |
| Прерванный upload | нет строки и объекта | counts до/после равны | — |
| Crash между S3 PUT и COMMIT (pending) | reconciler удаляет после grace | dry-run нашёл, apply удалил | повторный apply 0 |
| Ready-метаданные без объекта | не выдавать за ready, сообщить | metadata/content 404, reconciler `missing_objects`/`unresolved_missing` | оператор восстанавливает объект вручную; автоматическое «лечение» не выдумывает байты |
## 5. Ограничения и следующие шаги
- Стенд однохостовый: HAProxy, PostgreSQL, Valkey и S3 — единые точки отказа. Эксперимент доказывает отказ одной API-реплики и рестарт контейнеров, но не отказ Docker-host, БД, LB или S3.
- `missing object` (ready-метаданные без байтов) reconciler только обнаруживает: удалять метаданные или выдавать failed-состояние, которого нет в контракте lab4, было бы маскировкой потери данных. Восстановление — операторское.
- Single-node SeaweedFS 3.98 стабилен на стенде при одном PUT на API-реплику; большее число одновременных крупных PUT не гарантируется. Для production нужен распределённый S3/брокер и отдельная проверка.
- Grace period по умолчанию 1 час; эксперимент использует 20 с только чтобы уложиться в учебный прогон. Значение должно превышать максимальную длительность upload (S3 timeout 10 с + запас).
- S3 ListObjects не является snapshot: reconciler защищает свежие объекты grace-периодом и повторной проверкой БД, но не даёт линеаризуемости с конкурентными загрузками.
- Стоимость обхода измерена на 321 объекте/строке локального стенда; это не production-бенчмарк.
- В lab4 нет асинхронных состояний lab5 (queued/processing, thumbnail) и presigned-upload трека 1 — они не добавлялись.
- Публичный контракт и `tests/` не ослаблялись; собственные проверки лежат в `student-tests/` и `scripts/`.
## 6. Сценарий защиты
1. `make up`, `make test` — показать 201/ready, скачивание и SHA-256; сравнить с исходником.
2. Третьим пользователем получить 404 для metadata/content; выполнить `wget` anonymous GET в backend-сети → 403.
3. `make test-persistence ACTION_SCRIPT=scripts/restart.sh` и `make test-failover ACTION_SCRIPT=scripts/stop-one.sh`; показать `evidence/resilience/*.json` (ids/StartedAt/volumes, uploader→download SHA).
4. `make test-consistency` и `evidence/track2/summary.json`: dry-run, apply, rerun, grace, missing unresolved.
5. `make experiment`: 12 загрузок, HWM ≤ 75 МБ при лимите 384 МБ; объяснить разницу RSS/cgroup и роль семафоров.
## 7. Сдача
- Ветка `solution/bvt2301-melnikov`, кодовый commit `02fc97b…`; принятый
финальный commit — `d4529a27e86e40d41daafa2af7e6e45703ff8492`, публикационные
docs-правки — отдельным коммитом поверх него.
- Опубликованный fork: https://gitea.privcloud.tech/MelnikStalker/mtusi2026lab4;
MR открыт в `mtusi2026/mtusi2026lab4` из этой ветки в `main` как заявка на
проверку, а не слияние.
- Секреты: `.env` и `infra/seaweedfs-s3.json` в `.gitignore`, mode 600; в evidence нет токенов, паролей, S3 credentials и текстов сообщений.
+700
View File
@@ -0,0 +1,700 @@
// Command loadgen is a synthetic HTTP load generator for the lab3 experiment.
// It is not part of the public API contract. It creates its own synthetic user
// and chat through the load balancer, then measures message POST throughput
// (or a mixed read/write profile) with per-second buckets and X-Instance-Id
// attribution.
//
// The default profile is closed-loop: `-concurrency` workers each send the
// next request as soon as the previous one finishes. `-rate` switches to an
// open-loop target rate. Both are reported honestly as HTTP acknowledgement
// throughput, not as a count of PostgreSQL commits.
package main
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"io"
"math"
"net/http"
"os"
"os/exec"
"sort"
"sync"
"sync/atomic"
"time"
)
var version = "dev"
type config struct {
baseURL string
duration time.Duration
warmup time.Duration
concurrency int
rate float64
readRatio float64
timeout time.Duration
output string
retryUncertain bool
note string
stopInstance string
stopScript string
stopAfter time.Duration
}
type seriesBucket struct {
Second int64 `json:"second"`
Success int64 `json:"success"`
Errors int64 `json:"errors"`
P50 float64 `json:"p50_ms"`
P95 float64 `json:"p95_ms"`
P99 float64 `json:"p99_ms"`
latency []float64
}
type summary struct {
Tool string `json:"tool"`
Version string `json:"version"`
StartedAt string `json:"started_at"`
FinishedAt string `json:"finished_at"`
MeasuredSeconds float64 `json:"measured_seconds"`
WarmupSeconds float64 `json:"warmup_seconds"`
Concurrency int `json:"concurrency"`
RateLimit float64 `json:"rate_limit_per_second"`
ReadRatio float64 `json:"read_ratio"`
RetryUncertain bool `json:"retry_uncertain"`
Profile string `json:"profile"`
Successful int64 `json:"successful_requests"`
Failed int64 `json:"failed_requests"`
ErrorRatio float64 `json:"error_ratio"`
SuccessfulRPS float64 `json:"successful_rps"`
OfferedRPS float64 `json:"offered_rps"`
LatencyMS latencySummary `json:"successful_latency_ms"`
StatusCounts map[string]int64 `json:"status_counts"`
Instances map[string]int64 `json:"instances"`
AppVersions map[string]int64 `json:"app_versions"`
Kinds map[string]int64 `json:"kinds"`
Series []seriesBucket `json:"series"`
Retries int64 `json:"uncertain_retries"`
Violations []string `json:"idempotency_violations,omitempty"`
Note string `json:"note"`
Failover *failoverSummary `json:"failover,omitempty"`
}
type failoverSummary struct {
TargetInstance string `json:"target_instance"`
StopStartedAt string `json:"stop_started_at"`
StopFinishedAt string `json:"stop_finished_at"`
StopScriptExit int `json:"stop_script_exit"`
StopDurationSeconds float64 `json:"stop_duration_seconds"`
FirstSuccessAfterStopSec float64 `json:"first_success_after_stop_seconds"`
FirstWriteAfterStopSec float64 `json:"first_write_after_stop_seconds"`
FirstOtherSuccessSec float64 `json:"first_success_on_other_replica_seconds"`
SuccessesAfterStop int64 `json:"successes_after_stop"`
OtherSuccessesAfterStop int64 `json:"successes_on_other_replica_after_stop"`
ErrorsAfterStop int64 `json:"errors_after_stop"`
TargetResponsesAfterStop int64 `json:"target_responses_after_stop"`
TargetLastResponseAt string `json:"target_last_response_at"`
}
type latencySummary struct {
P50 float64 `json:"p50"`
P95 float64 `json:"p95"`
P99 float64 `json:"p99"`
Max float64 `json:"max"`
Mean float64 `json:"mean"`
}
func main() {
cfg := config{}
flag.StringVar(&cfg.baseURL, "base-url", "http://127.0.0.1:8083", "LB base URL")
flag.DurationVar(&cfg.duration, "duration", 20*time.Second, "measured duration")
flag.DurationVar(&cfg.warmup, "warmup", 5*time.Second, "warmup before measurement")
flag.IntVar(&cfg.concurrency, "concurrency", 32, "workers (closed loop) or max in-flight (rate mode)")
flag.Float64Var(&cfg.rate, "rate", 0, "open-loop target requests/second; 0 = closed loop")
flag.Float64Var(&cfg.readRatio, "read-ratio", 0, "fraction of GET /users/me requests (failover probe)")
flag.DurationVar(&cfg.timeout, "timeout", 5*time.Second, "per-request timeout")
flag.StringVar(&cfg.output, "output", "", "write JSON summary to this path")
flag.BoolVar(&cfg.retryUncertain, "retry-uncertain", false, "retry failed POSTs with the same Idempotency-Key (failover probe)")
flag.StringVar(&cfg.note, "note", "", "free-form note stored in the summary")
flag.StringVar(&cfg.stopInstance, "stop-instance", "", "failover probe: stop this X-Instance-Id during the run")
flag.StringVar(&cfg.stopScript, "stop-script", "", "failover probe: executable that stops TARGET_INSTANCE_ID")
flag.DurationVar(&cfg.stopAfter, "stop-after", 0, "failover probe: stop after this much measured time")
flag.StringVar(&version, "version", "dev", "generator revision label")
flag.Parse()
if cfg.duration <= 0 || cfg.concurrency < 1 || cfg.readRatio < 0 || cfg.readRatio > 1 || cfg.rate < 0 {
fmt.Fprintln(os.Stderr, "invalid load parameters")
os.Exit(2)
}
client := &http.Client{
Timeout: cfg.timeout,
Transport: &http.Transport{
MaxIdleConns: cfg.concurrency*2 + 8,
MaxIdleConnsPerHost: cfg.concurrency*2 + 8,
IdleConnTimeout: 30 * time.Second,
DisableCompression: true,
},
}
actor, chat := bootstrap(client, cfg.baseURL)
runID := randomHex(8)
measureStart := time.Now().Add(cfg.warmup)
deadline := measureStart.Add(cfg.duration)
var failover *failoverState
if cfg.stopScript != "" {
target := cfg.stopInstance
if target == "" {
target = observeAnyInstance(client, cfg.baseURL, actor)
}
if target == "" {
fail("no X-Instance-Id observed for failover target")
}
failover = &failoverState{target: target, script: cfg.stopScript}
go failover.run(measureStart.Add(cfg.stopAfter))
}
var (
mu sync.Mutex
samples []result
series = map[int64]*seriesBucket{}
retries int64
)
worker := func(id int) {
seq := 0
for {
now := time.Now()
if !now.Before(deadline) {
return
}
// Warmup traffic is sent but excluded from every summary number.
measured := !now.Before(measureStart)
kind := "write"
if cfg.readRatio > 0 && float64((id+seq)%1000)/1000.0 < cfg.readRatio {
kind = "read"
}
start := time.Now()
result := oneRequest(client, cfg.baseURL, actor, chat, kind, fmt.Sprintf("%s-%d-%d", runID, id, seq), cfg.retryUncertain)
elapsed := time.Since(start)
seq++
if !measured {
continue
}
result.at = start
result.done = time.Now()
result.latency = elapsed
mu.Lock()
samples = append(samples, result)
if result.err != "" && result.ok {
retries++
}
bucket := series[start.Unix()]
if bucket == nil {
bucket = &seriesBucket{Second: start.Unix()}
series[start.Unix()] = bucket
}
if result.ok {
bucket.Success++
bucket.latency = append(bucket.latency, float64(result.latency.Microseconds())/1000.0)
} else {
bucket.Errors++
}
mu.Unlock()
if cfg.rate > 0 {
// Spread a fixed offered rate across workers. This is a
// best-effort pacing, not a hard scheduler; lateness is
// visible in the latency distribution.
interval := time.Duration(float64(time.Second) * float64(cfg.concurrency) / cfg.rate)
if sleep := interval - time.Since(start); sleep > 0 {
time.Sleep(sleep)
}
}
}
}
var wg sync.WaitGroup
for i := 0; i < cfg.concurrency; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
worker(id)
}(i)
}
wg.Wait()
finished := time.Now()
measuredSeconds := finished.Sub(measureStart).Seconds()
var failoverSnapshot *failoverState
if failover != nil {
failoverSnapshot = failover
}
sum := summarize(cfg, runID, measureStart, finished, measuredSeconds, samples, series, atomic.LoadInt64(&retries), failoverSnapshot)
if cfg.output != "" {
data, _ := json.MarshalIndent(sum, "", " ")
if err := os.WriteFile(cfg.output, append(data, '\n'), 0o644); err != nil {
fmt.Fprintln(os.Stderr, "cannot write output:", err)
os.Exit(1)
}
}
encoded, _ := json.MarshalIndent(sum, "", " ")
fmt.Println(string(encoded))
if sum.Successful == 0 {
os.Exit(1)
}
}
type credentials struct {
token string
user string
}
type chatInfo struct {
id string
}
type result struct {
at time.Time
done time.Time
latency time.Duration
ok bool
status int
instance string
appVer string
kind string
key string
message string
err string
}
func oneRequest(client *http.Client, base string, actor credentials, chat chatInfo, kind, key string, retry bool) result {
deadline := time.Now().Add(10 * time.Second)
for {
res := requestOnce(client, base, actor, chat, kind, key)
if res.ok || !retry || kind != "write" || time.Now().After(deadline) {
return res
}
// A timeout or LB 502/503 after SIGTERM is an uncertain result. The
// same key is safe to retry only because the server's idempotency
// record and message are committed atomically.
res.err = "retry:" + res.err
time.Sleep(30 * time.Millisecond)
}
}
func requestOnce(client *http.Client, base string, actor credentials, chat chatInfo, kind, key string) result {
method, path := http.MethodPost, "/api/v1/chats/"+chat.id+"/messages"
var body io.Reader
if kind == "read" {
method, path = http.MethodGet, "/api/v1/users/me"
} else {
payload, _ := json.Marshal(map[string]string{"text": "load " + key})
body = bytes.NewReader(payload)
}
req, err := http.NewRequestWithContext(context.Background(), method, base+path, body)
if err != nil {
return result{status: 0, err: "build_request"}
}
req.Header.Set("Authorization", "Bearer "+actor.token)
if kind == "write" {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", key)
}
response, err := client.Do(req)
if err != nil {
return result{status: 0, err: "transport"}
}
defer response.Body.Close()
data, readErr := io.ReadAll(io.LimitReader(response.Body, 1<<20))
res := result{
status: response.StatusCode,
instance: response.Header.Get("X-Instance-Id"),
appVer: response.Header.Get("X-App-Version"),
kind: kind,
key: key,
}
if readErr != nil {
res.err = "read_body"
return res
}
if response.StatusCode == http.StatusCreated || response.StatusCode == http.StatusOK {
res.ok = true
if kind == "write" {
var message struct {
ID string `json:"id"`
}
if err := json.Unmarshal(data, &message); err != nil || message.ID == "" {
res.ok = false
res.err = "bad_json"
} else {
res.message = message.ID
}
}
return res
}
res.err = "status"
return res
}
func bootstrap(client *http.Client, base string) (credentials, chatInfo) {
// /health/ready is retried until the stack is up.
waitReady(client, base)
username := "lg_" + randomHex(10)
password := "Loadgen-" + randomHex(12)
registered := struct {
ID string `json:"id"`
}{}
postJSON(client, base+"/api/v1/users", "", map[string]string{
"username": username, "display_name": "Load generator", "password": password,
}, &registered)
basic := basicAuth(username, password)
session := struct {
Token string `json:"token"`
}{}
postJSON(client, base+"/api/v1/auth/sessions", "Basic "+basic, nil, &session)
if session.Token == "" || registered.ID == "" {
fail("bootstrap failed")
}
chat := struct {
ID string `json:"id"`
}{}
postJSON(client, base+"/api/v1/chats", "Bearer "+session.Token, map[string]interface{}{
"title": "loadgen " + randomHex(6), "member_ids": []string{registered.ID},
}, &chat)
if chat.ID == "" {
fail("chat bootstrap failed")
}
return credentials{token: session.Token, user: registered.ID}, chatInfo{id: chat.ID}
}
func waitReady(client *http.Client, base string) {
deadline := time.Now().Add(90 * time.Second)
for time.Now().Before(deadline) {
response, err := client.Get(base + "/health/ready")
if err == nil {
io.Copy(io.Discard, response.Body)
response.Body.Close()
if response.StatusCode == http.StatusOK {
return
}
}
time.Sleep(250 * time.Millisecond)
}
fail("stack did not become ready")
}
func postJSON(client *http.Client, url, authorization string, body interface{}, out interface{}) {
var reader io.Reader
if body != nil {
data, _ := json.Marshal(body)
reader = bytes.NewReader(data)
}
req, err := http.NewRequest(http.MethodPost, url, reader)
if err != nil {
fail("build bootstrap request")
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if authorization != "" {
req.Header.Set("Authorization", authorization)
}
response, err := client.Do(req)
if err != nil {
fail("bootstrap transport failure")
}
defer response.Body.Close()
data, _ := io.ReadAll(io.LimitReader(response.Body, 1<<20))
if response.StatusCode != http.StatusCreated {
fail(fmt.Sprintf("bootstrap status %d", response.StatusCode))
}
if out != nil {
if err := json.Unmarshal(data, out); err != nil {
fail("bootstrap JSON")
}
}
}
func basicAuth(username, password string) string {
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
raw := []byte(username + ":" + password)
var encoded []byte
for i := 0; i < len(raw); i += 3 {
var chunk [3]byte
n := copy(chunk[:], raw[i:])
value := uint(chunk[0])<<16 | uint(chunk[1])<<8 | uint(chunk[2])
encoded = append(encoded, alphabet[value>>18&63], alphabet[value>>12&63])
if n > 1 {
encoded = append(encoded, alphabet[value>>6&63])
} else {
encoded = append(encoded, '=')
}
if n > 2 {
encoded = append(encoded, alphabet[value&63])
} else {
encoded = append(encoded, '=')
}
}
return string(encoded)
}
func summarize(cfg config, runID string, start, finished time.Time, seconds float64, samples []result, series map[int64]*seriesBucket, retries int64, failover *failoverState) summary {
sum := summary{
Tool: "mtusi-lab3-loadgen",
Version: version,
StartedAt: start.UTC().Format(time.RFC3339Nano),
FinishedAt: finished.UTC().Format(time.RFC3339Nano),
MeasuredSeconds: round(seconds, 3),
WarmupSeconds: cfg.warmup.Seconds(),
Concurrency: cfg.concurrency,
RateLimit: cfg.rate,
ReadRatio: cfg.readRatio,
RetryUncertain: cfg.retryUncertain,
Profile: "closed-loop",
StatusCounts: map[string]int64{},
Instances: map[string]int64{},
AppVersions: map[string]int64{},
Kinds: map[string]int64{},
Retries: retries,
Note: cfg.note,
}
if cfg.rate > 0 {
sum.Profile = fmt.Sprintf("open-loop target %.1f req/s (best effort)", cfg.rate)
}
sum.Note = cfg.note + "; synthetic messages created by loadgen, no retries unless -retry-uncertain"
var latencies []float64
idByKey := map[string]string{}
summaryFailover := buildFailoverSummary(failover, samples)
for _, item := range samples {
sum.Kinds[item.kind]++
statusKey := fmt.Sprintf("%d", item.status)
if item.status == 0 {
statusKey = "error:" + item.err
}
sum.StatusCounts[statusKey]++
if item.ok {
sum.Successful++
latencies = append(latencies, float64(item.latency.Microseconds())/1000.0)
if item.instance == "" {
item.instance = "(missing)"
}
sum.Instances[item.instance]++
ver := item.appVer
if ver == "" {
ver = "(missing)"
}
sum.AppVersions[ver]++
if item.kind == "write" && item.message != "" {
if previous, seen := idByKey[item.key]; seen && previous != item.message {
sum.Violations = append(sum.Violations, "same key returned different message ids")
}
idByKey[item.key] = item.message
}
} else {
sum.Failed++
}
}
sum.OfferedRPS = round(float64(sum.Successful+sum.Failed)/seconds, 3)
sum.SuccessfulRPS = round(float64(sum.Successful)/seconds, 3)
if total := sum.Successful + sum.Failed; total > 0 {
sum.ErrorRatio = round(float64(sum.Failed)/float64(total), 6)
}
sort.Float64s(latencies)
sum.LatencyMS = latencyPercentiles(latencies)
sum.Failover = summaryFailover
keys := make([]int64, 0, len(series))
for second := range series {
keys = append(keys, second)
}
sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
for _, second := range keys {
bucket := series[second]
sort.Float64s(bucket.latency)
bucket.P50 = percentile(bucket.latency, 0.50)
bucket.P95 = percentile(bucket.latency, 0.95)
bucket.P99 = percentile(bucket.latency, 0.99)
sum.Series = append(sum.Series, *bucket)
}
return sum
}
func percentile(sorted []float64, p float64) float64 {
if len(sorted) == 0 {
return 0
}
index := int(math.Ceil(p*float64(len(sorted)))) - 1
if index < 0 {
index = 0
}
if index >= len(sorted) {
index = len(sorted) - 1
}
return round(sorted[index], 3)
}
func latencyPercentiles(sorted []float64) latencySummary {
if len(sorted) == 0 {
return latencySummary{}
}
pick := func(p float64) float64 { return percentile(sorted, p) }
var total float64
for _, value := range sorted {
total += value
}
return latencySummary{
P50: pick(0.50), P95: pick(0.95), P99: pick(0.99),
Max: round(sorted[len(sorted)-1], 3), Mean: round(total/float64(len(sorted)), 3),
}
}
func round(value float64, digits int) float64 {
scale := math.Pow(10, float64(digits))
return math.Round(value*scale) / scale
}
func randomHex(n int) string {
buf := make([]byte, n)
if _, err := rand.Read(buf); err != nil {
fail("random")
}
return hex.EncodeToString(buf)
}
func fail(message string) {
fmt.Fprintln(os.Stderr, "loadgen:", message)
os.Exit(2)
}
type failoverState struct {
target string
script string
mu sync.Mutex
started time.Time
finished time.Time
exitCode int
err string
}
func (f *failoverState) run(at time.Time) {
if delay := time.Until(at); delay > 0 {
time.Sleep(delay)
}
f.mu.Lock()
f.started = time.Now()
f.mu.Unlock()
command := exec.Command(f.script)
command.Env = append(os.Environ(), "TARGET_INSTANCE_ID="+f.target)
command.Stdout = io.Discard
command.Stderr = io.Discard
err := command.Run()
f.mu.Lock()
defer f.mu.Unlock()
f.finished = time.Now()
if err == nil {
f.exitCode = 0
return
}
if exitError, ok := err.(*exec.ExitError); ok {
f.exitCode = exitError.ExitCode()
} else {
f.exitCode = -1
f.err = err.Error()
}
}
func (f *failoverState) snapshot() failoverState {
f.mu.Lock()
defer f.mu.Unlock()
return failoverState{
target: f.target,
started: f.started,
finished: f.finished,
exitCode: f.exitCode,
err: f.err,
}
}
func observeAnyInstance(client *http.Client, base string, actor credentials) string {
deadline := time.Now().Add(30 * time.Second)
for time.Now().Before(deadline) {
req, _ := http.NewRequest(http.MethodGet, base+"/api/v1/users/me", nil)
req.Header.Set("Authorization", "Bearer "+actor.token)
response, err := client.Do(req)
if err == nil {
io.Copy(io.Discard, response.Body)
response.Body.Close()
if instance := response.Header.Get("X-Instance-Id"); instance != "" {
return instance
}
}
time.Sleep(100 * time.Millisecond)
}
return ""
}
func buildFailoverSummary(failover *failoverState, samples []result) *failoverSummary {
if failover == nil {
return nil
}
state := failover.snapshot()
if state.started.IsZero() {
return nil
}
summary := &failoverSummary{
TargetInstance: state.target,
StopStartedAt: state.started.UTC().Format(time.RFC3339Nano),
StopFinishedAt: state.finished.UTC().Format(time.RFC3339Nano),
StopScriptExit: state.exitCode,
StopDurationSeconds: round(state.finished.Sub(state.started).Seconds(), 3),
FirstSuccessAfterStopSec: -1,
FirstWriteAfterStopSec: -1,
FirstOtherSuccessSec: -1,
}
var firstSuccess, firstWrite, firstOther time.Time
var lastTarget time.Time
for _, item := range samples {
if item.instance == state.target && item.done.After(lastTarget) {
lastTarget = item.done
}
if !item.at.After(state.started) {
continue
}
if item.ok {
summary.SuccessesAfterStop++
if firstSuccess.IsZero() || item.done.Before(firstSuccess) {
firstSuccess = item.done
}
if item.kind == "write" && (firstWrite.IsZero() || item.done.Before(firstWrite)) {
firstWrite = item.done
}
if item.instance != state.target {
summary.OtherSuccessesAfterStop++
if firstOther.IsZero() || item.done.Before(firstOther) {
firstOther = item.done
}
}
} else {
summary.ErrorsAfterStop++
}
if item.at.After(state.finished.Add(500*time.Millisecond)) && item.instance == state.target {
summary.TargetResponsesAfterStop++
}
}
if !firstSuccess.IsZero() {
summary.FirstSuccessAfterStopSec = round(firstSuccess.Sub(state.started).Seconds(), 3)
}
if !firstWrite.IsZero() {
summary.FirstWriteAfterStopSec = round(firstWrite.Sub(state.started).Seconds(), 3)
}
if !firstOther.IsZero() {
summary.FirstOtherSuccessSec = round(firstOther.Sub(state.started).Seconds(), 3)
}
if !lastTarget.IsZero() {
summary.TargetLastResponseAt = lastTarget.UTC().Format(time.RFC3339Nano)
}
return summary
}
+298
View File
@@ -0,0 +1,298 @@
// Command messenger runs the lab3 HTTP API and the container healthcheck
// helper. PostgreSQL holds users, chats, membership, messages and idempotency
// records; Valkey holds server-side sessions shared by every API replica.
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"mtusi.ru/messenger-lab4/internal/api"
"mtusi.ru/messenger-lab4/internal/config"
"mtusi.ru/messenger-lab4/internal/objectstore"
"mtusi.ru/messenger-lab4/internal/session"
"mtusi.ru/messenger-lab4/internal/store"
"mtusi.ru/messenger-lab4/internal/uuid"
)
// Overridden at build time with -X main.version=... and -X main.revision=...
var (
version = "dev"
revision = "unknown"
)
const idempotencyRetention = 24 * time.Hour
func main() {
healthcheck := flag.Bool("healthcheck", false, "probe the local liveness endpoint and exit 0/1")
flag.Parse()
cfg, err := config.Load()
if err != nil {
fmt.Fprintln(os.Stderr, "configuration error:", err)
os.Exit(2)
}
if *healthcheck {
os.Exit(runHealthcheck(cfg))
}
logger := newLogger(cfg)
ctx := context.Background()
instanceID := instanceIdentity()
repository, err := store.Open(ctx, cfg.DatabaseURL, store.Options{
MaxConns: cfg.DBMaxConns,
MinConns: cfg.DBMinConns,
ConnectTimeout: cfg.DBConnectTimeout,
StatementTimeout: cfg.DBStatementTimeout,
QueryTimeout: cfg.QueryTimeout,
})
if err != nil {
logger.Error("database configuration failed", "error", err)
os.Exit(2)
}
defer repository.Close()
if err := waitForDatabase(ctx, repository, cfg.StartupTimeout, logger); err != nil {
logger.Error("postgres did not become ready", "timeout_seconds", int(cfg.StartupTimeout.Seconds()), "error", err)
os.Exit(1)
}
sessions, err := session.Open(cfg.CacheURL, session.Options{
PoolSize: cfg.CachePoolSize,
DialTimeout: cfg.CacheTimeout,
IOTimeout: cfg.CacheTimeout,
TTL: cfg.SessionTTL,
})
if err != nil {
logger.Error("session store configuration failed", "error", err)
os.Exit(2)
}
defer func() { _ = sessions.Close() }()
objects, err := objectstore.Open(objectstore.Config{
Endpoint: cfg.S3Endpoint,
Region: cfg.S3Region,
Bucket: cfg.S3Bucket,
AccessKey: cfg.S3AccessKey,
SecretKey: cfg.S3SecretKey,
Timeout: cfg.S3Timeout,
})
if err != nil {
logger.Error("object store configuration failed", "error", err)
os.Exit(2)
}
app, err := api.New(repository, sessions, objects, logger, instanceID, version, api.Options{
MaxUploadBytes: cfg.MaxUploadBytes,
MaxImagePixels: cfg.MaxImagePixels,
DecodeConcurrency: cfg.DecodeConcurrency,
PutConcurrency: cfg.PutConcurrency,
TempDir: cfg.TempDir,
})
if err != nil {
logger.Error("application initialization failed", "error", err)
os.Exit(1)
}
server := &http.Server{
Handler: app.Handler(),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 20 * time.Second,
IdleTimeout: 60 * time.Second,
MaxHeaderBytes: 1 << 20,
}
address := net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port))
listener, err := net.Listen("tcp", address)
if err != nil {
logger.Error("listen failed", "address", address, "error", err)
os.Exit(1)
}
// Operator-only stats listener. It is bound to container loopback by
// default and is not published by compose, so it cannot bypass the LB.
var metricsServer *http.Server
if cfg.MetricsAddr != "off" {
metricsMux := http.NewServeMux()
metricsMux.HandleFunc("/internal/stats", app.InternalStatsHandler)
metricsServer = &http.Server{
Handler: metricsMux,
ReadHeaderTimeout: 2 * time.Second,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
}
metricsListener, listenErr := net.Listen("tcp", cfg.MetricsAddr)
if listenErr != nil {
logger.Error("metrics listen failed", "address", cfg.MetricsAddr, "error", listenErr)
os.Exit(1)
}
go func() {
if serveErr := metricsServer.Serve(metricsListener); serveErr != nil && !errors.Is(serveErr, http.ErrServerClosed) {
logger.Error("metrics server stopped unexpectedly", "error", serveErr)
}
}()
}
pruneCtx, pruneCancel := context.WithCancel(ctx)
defer pruneCancel()
go pruneIdempotency(pruneCtx, repository, logger)
logger.Info("server listening",
"address", listener.Addr().String(),
"env", cfg.Env,
"instance_id", instanceID,
"version", version,
"revision", revision,
"session_ttl_seconds", int(cfg.SessionTTL.Seconds()),
"s3_bucket", cfg.S3Bucket,
"max_upload_bytes", cfg.MaxUploadBytes,
"max_image_pixels", cfg.MaxImagePixels,
"decode_concurrency", cfg.DecodeConcurrency,
"s3_put_concurrency", cfg.PutConcurrency,
"shutdown_timeout_seconds", int(cfg.ShutdownTimeout.Seconds()),
"shutdown_drain_seconds", int(cfg.ShutdownDrain.Seconds()),
"db_max_conns", cfg.DBMaxConns,
)
serveErrors := make(chan error, 1)
go func() {
serveErrors <- server.Serve(listener)
}()
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT)
select {
case received := <-signals:
logger.Info("shutdown initiated", "signal", received.String(), "instance_id", instanceID)
// Stop advertising readiness first. The load balancer removes this
// backend during the drain window while the process still accepts
// requests, so in-flight work is not cut off by the health transition.
app.SetReady(false)
if cfg.ShutdownDrain > 0 {
logger.Info("draining", "seconds", int(cfg.ShutdownDrain.Seconds()))
time.Sleep(cfg.ShutdownDrain)
}
started := time.Now()
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
logger.Error("graceful shutdown failed", "error", err)
_ = server.Close()
os.Exit(1)
}
if metricsServer != nil {
_ = metricsServer.Close()
}
pruneCancel()
logger.Info("shutdown complete",
"instance_id", instanceID,
"elapsed_ms", float64(time.Since(started).Microseconds())/1000.0,
)
os.Exit(0)
case err := <-serveErrors:
if err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Error("server stopped unexpectedly", "error", err)
os.Exit(1)
}
}
}
// instanceIdentity is stable for the lifetime of this process and unique per
// container. INSTANCE_ID overrides it; otherwise the container hostname is the
// actual process identity, which lets scripts/stop-one.sh map an X-Instance-Id
// response to exactly one Docker container. lab7 replaces this with an opaque
// alias that does not reveal a hostname.
func instanceIdentity() string {
if value := strings.TrimSpace(os.Getenv("INSTANCE_ID")); value != "" {
return value
}
if hostname, err := os.Hostname(); err == nil && strings.TrimSpace(hostname) != "" {
return hostname
}
return uuid.NewRandom(8)
}
func newLogger(cfg config.Config) *slog.Logger {
handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: cfg.LogLevel})
return slog.New(handler).With("service", "messenger-lab4", "app_env", cfg.Env)
}
func waitForDatabase(ctx context.Context, repository *store.Store, timeout time.Duration, logger *slog.Logger) error {
deadline := time.Now().Add(timeout)
attempt := 0
for {
attempt++
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
err := repository.Ping(pingCtx)
cancel()
if err == nil {
return nil
}
if time.Now().After(deadline) {
return err
}
logger.Debug("waiting for postgres", "attempt", attempt, "error", err)
time.Sleep(500 * time.Millisecond)
}
}
func pruneIdempotency(ctx context.Context, repository *store.Store, logger *slog.Logger) {
run := func() {
pruneCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
deleted, err := repository.PruneIdempotency(pruneCtx, idempotencyRetention)
cancel()
if err != nil && ctx.Err() == nil {
logger.Warn("idempotency prune failed", "error", err)
return
}
if deleted > 0 {
logger.Info("pruned expired idempotency records", "rows", deleted, "retention_hours", 24)
}
}
run()
ticker := time.NewTicker(time.Hour)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
run()
}
}
}
// runHealthcheck is compiled into the same binary as the server, so the
// runtime image needs no curl, wget or shell. It always talks to loopback
// inside the container, independently of APP_HOST.
func runHealthcheck(cfg config.Config) int {
client := &http.Client{Timeout: 2 * time.Second}
url := "http://127.0.0.1:" + strconv.Itoa(cfg.Port) + "/health/live"
response, err := client.Get(url) //nolint:gosec // fixed loopback URL built from a validated port
if err != nil {
fmt.Fprintln(os.Stderr, "healthcheck request failed:", err)
return 1
}
defer response.Body.Close()
_, _ = io.Copy(io.Discard, response.Body)
if response.StatusCode != http.StatusOK {
fmt.Fprintln(os.Stderr, "healthcheck status:", response.StatusCode)
return 1
}
return 0
}
+69
View File
@@ -0,0 +1,69 @@
// Command migrate applies the embedded, checksummed PostgreSQL migrations and
// exits. It is a separate one-shot compose service: API replicas never race to
// migrate the shared schema. The advisory lock inside store.Migrate serialises
// concurrent invocations of this command as well.
package main
import (
"context"
"flag"
"fmt"
"log/slog"
"os"
"time"
"mtusi.ru/messenger-lab4/internal/config"
"mtusi.ru/messenger-lab4/internal/store"
)
var revision = "unknown"
func main() {
flag.Parse()
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})).
With("service", "messenger-lab4-migrate", "revision", revision)
cfg, err := config.LoadMigrate()
if err != nil {
logger.Error("configuration error", "error", err)
os.Exit(2)
}
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
repository, err := store.Open(ctx, cfg.DatabaseURL, store.Options{
MaxConns: cfg.DBMaxConns,
MinConns: 0,
ConnectTimeout: cfg.DBConnectTimeout,
StatementTimeout: cfg.DBStatementTimeout,
QueryTimeout: cfg.QueryTimeout,
})
if err != nil {
logger.Error("database configuration failed", "error", err)
os.Exit(2)
}
defer repository.Close()
for {
pingCtx, pingCancel := context.WithTimeout(ctx, 2*time.Second)
err = repository.Ping(pingCtx)
pingCancel()
if err == nil {
break
}
if ctx.Err() != nil {
logger.Error("postgres did not become ready", "error", err)
os.Exit(1)
}
logger.Info("waiting for postgres", "error", err)
time.Sleep(500 * time.Millisecond)
}
started := time.Now()
if err := repository.Migrate(ctx); err != nil {
logger.Error("migrations failed", "error", err)
os.Exit(1)
}
logger.Info("migrations complete", "elapsed_ms", float64(time.Since(started).Microseconds())/1000.0)
fmt.Println("migrations: up-to-date")
}
+357
View File
@@ -0,0 +1,357 @@
// Command reconciler is the track-2 consistency tool for the two stores.
//
// It compares PostgreSQL attachment rows with the objects under the private
// bucket prefix and reports:
// - ready row + object -> ok
// - ready row without object -> missing_object (report only: bytes
// cannot be invented or safely replaced; the operator must restore them)
// - pending row + object -> stale upload intent after the grace
// period; the object and the row are both removed
// - pending row without object -> stale upload intent; the row is removed
// - object without a row -> orphan object; removed only after grace
//
// Fresh objects and rows are never touched: the grace period protects an
// upload that is between its S3 PUT and its PostgreSQL COMMIT, and the
// reconciler re-checks the database immediately before every delete.
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"sort"
"strconv"
"time"
"mtusi.ru/messenger-lab4/internal/config"
"mtusi.ru/messenger-lab4/internal/objectstore"
"mtusi.ru/messenger-lab4/internal/store"
)
type item struct {
ID string `json:"id,omitempty"`
ObjectKey string `json:"object_key"`
Status string `json:"status,omitempty"`
AgeSeconds int64 `json:"age_seconds"`
ObjectPresent bool `json:"object_present,omitempty"`
}
type report struct {
GeneratedAt string `json:"generated_at"`
Mode string `json:"mode"`
Bucket string `json:"bucket"`
Prefix string `json:"prefix"`
GraceSeconds int64 `json:"grace_seconds"`
Database dbCounts `json:"database"`
ObjectStore s3Counts `json:"object_store"`
Findings findings `json:"findings"`
Actions actions `json:"actions"`
Timing timing `json:"timing"`
}
type dbCounts struct {
Rows int `json:"rows"`
Ready int `json:"ready"`
Pending int `json:"pending"`
}
type s3Counts struct {
Objects int `json:"objects"`
}
type findings struct {
OK int `json:"ok"`
OrphanObjects []item `json:"orphan_objects"`
ProtectedObjects []item `json:"protected_recent_objects"`
MissingObjects []item `json:"missing_objects"`
StalePending []item `json:"stale_pending"`
ProtectedPending []item `json:"protected_pending"`
}
type actions struct {
PlannedDeletes []string `json:"planned_deletes,omitempty"`
DeletedObjects []string `json:"deleted_objects"`
DeletedPendingRows []string `json:"deleted_pending_rows"`
Skipped []string `json:"skipped"`
UnresolvedMissing []string `json:"unresolved_missing"`
Errors []string `json:"errors"`
}
type timing struct {
DBScanMS int64 `json:"db_scan_ms"`
S3ListMS int64 `json:"s3_list_ms"`
TotalMS int64 `json:"total_ms"`
DBRows int `json:"db_rows"`
S3Objects int `json:"s3_objects"`
}
func main() {
apply := flag.Bool("apply", false, "perform safe deletions; without it the run is a read-only dry run")
prefix := flag.String("prefix", "attachments/", "bucket prefix owned by the application")
output := flag.String("output", "", "optional path for the JSON report")
defaultGrace := time.Hour
if raw := os.Getenv("RECONCILE_GRACE_SECONDS"); raw != "" {
seconds, err := strconv.Atoi(raw)
if err != nil || seconds < 1 {
fmt.Fprintln(os.Stderr, "reconciler: RECONCILE_GRACE_SECONDS must be a positive integer")
os.Exit(2)
}
defaultGrace = time.Duration(seconds) * time.Second
}
grace := flag.Duration("grace", defaultGrace, "minimum age before an orphan object or pending upload intent may be removed")
flag.Parse()
if *grace < time.Second {
fmt.Fprintln(os.Stderr, "reconciler: -grace must be at least 1s")
os.Exit(2)
}
if *prefix == "" || *prefix == "/" {
fmt.Fprintln(os.Stderr, "reconciler: -prefix must be a non-empty application prefix")
os.Exit(2)
}
cfg, err := config.LoadTool()
if err != nil {
fmt.Fprintln(os.Stderr, "reconciler: configuration error:", err)
os.Exit(2)
}
repository, err := store.Open(context.Background(), cfg.DatabaseURL, store.Options{
MaxConns: 4,
MinConns: 0,
ConnectTimeout: cfg.DBConnectTimeout,
StatementTimeout: cfg.DBStatementTimeout,
QueryTimeout: cfg.QueryTimeout,
})
if err != nil {
fmt.Fprintln(os.Stderr, "reconciler: database configuration error:", err)
os.Exit(2)
}
defer repository.Close()
objects, err := objectstore.Open(objectstore.Config{
Endpoint: cfg.S3Endpoint,
Region: cfg.S3Region,
Bucket: cfg.S3Bucket,
AccessKey: cfg.S3AccessKey,
SecretKey: cfg.S3SecretKey,
Timeout: cfg.S3Timeout,
})
if err != nil {
fmt.Fprintln(os.Stderr, "reconciler: object store configuration error:", err)
os.Exit(2)
}
started := time.Now().UTC()
result := report{
GeneratedAt: started.Format(time.RFC3339Nano),
Mode: "dry-run",
Bucket: cfg.S3Bucket,
Prefix: *prefix,
GraceSeconds: int64(grace.Seconds()),
}
if *apply {
result.Mode = "apply"
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
dbStarted := time.Now()
rows, err := repository.ListAttachmentsForReconcile(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, "reconciler: database scan failed:", err)
os.Exit(1)
}
result.Timing.DBScanMS = time.Since(dbStarted).Milliseconds()
result.Timing.DBRows = len(rows)
result.Database.Rows = len(rows)
s3Started := time.Now()
stored, err := objects.List(ctx, *prefix)
if err != nil {
fmt.Fprintln(os.Stderr, "reconciler: object store scan failed:", err)
os.Exit(1)
}
result.Timing.S3ListMS = time.Since(s3Started).Milliseconds()
result.Timing.S3Objects = len(stored)
result.ObjectStore.Objects = len(stored)
now := time.Now().UTC()
dbByKey := make(map[string]store.ReconcileAttachment, len(rows))
for _, row := range rows {
dbByKey[row.ObjectKey] = row
switch row.Status {
case "ready":
result.Database.Ready++
case "pending":
result.Database.Pending++
}
}
objectByKey := make(map[string]objectstore.ObjectInfo, len(stored))
for _, object := range stored {
objectByKey[object.Key] = object
}
// Objects with no metadata row: candidate orphans, unless still fresh.
for _, object := range stored {
if _, known := dbByKey[object.Key]; known {
continue
}
age := ageSeconds(now, object.LastModified)
if object.LastModified.IsZero() || age < int64(grace.Seconds()) {
result.Findings.ProtectedObjects = append(result.Findings.ProtectedObjects, item{
ObjectKey: object.Key, AgeSeconds: age,
})
continue
}
result.Findings.OrphanObjects = append(result.Findings.OrphanObjects, item{
ObjectKey: object.Key, AgeSeconds: age,
})
}
// Metadata rows: ready rows must have an object; pending rows are internal
// upload intents and are cleaned only after the grace period.
for _, row := range rows {
_, exists := objectByKey[row.ObjectKey]
age := ageSeconds(now, row.UpdatedAt)
switch row.Status {
case "ready":
if exists {
result.Findings.OK++
} else {
result.Findings.MissingObjects = append(result.Findings.MissingObjects, item{
ID: row.ID, ObjectKey: row.ObjectKey, Status: row.Status, AgeSeconds: age,
})
}
case "pending":
if age >= int64(grace.Seconds()) {
result.Findings.StalePending = append(result.Findings.StalePending, item{
ID: row.ID, ObjectKey: row.ObjectKey, Status: row.Status,
AgeSeconds: age, ObjectPresent: exists,
})
} else {
result.Findings.ProtectedPending = append(result.Findings.ProtectedPending, item{
ID: row.ID, ObjectKey: row.ObjectKey, Status: row.Status,
AgeSeconds: age, ObjectPresent: exists,
})
}
}
}
sortFindings(&result.Findings)
if *apply {
applyActions(ctx, repository, objects, result.Findings.OrphanObjects, result.Findings.StalePending, *grace, &result.Actions)
} else {
for _, orphan := range result.Findings.OrphanObjects {
result.Actions.PlannedDeletes = append(result.Actions.PlannedDeletes, orphan.ObjectKey)
}
for _, pending := range result.Findings.StalePending {
result.Actions.PlannedDeletes = append(result.Actions.PlannedDeletes, pending.ObjectKey)
}
}
for _, missing := range result.Findings.MissingObjects {
result.Actions.UnresolvedMissing = append(result.Actions.UnresolvedMissing, missing.ID)
}
result.Timing.TotalMS = time.Since(started).Milliseconds()
encoded, err := json.MarshalIndent(result, "", " ")
if err != nil {
fmt.Fprintln(os.Stderr, "reconciler: encode report failed:", err)
os.Exit(1)
}
fmt.Println(string(encoded))
if *output != "" {
if err := os.WriteFile(*output, append(encoded, '\n'), 0o644); err != nil {
fmt.Fprintln(os.Stderr, "reconciler: write report failed:", err)
os.Exit(1)
}
}
if len(result.Actions.Errors) > 0 {
os.Exit(1)
}
}
// applyActions performs the two safe mutations. Broken ready metadata is never
// deleted: automatic deletion would destroy the only record of a user's file
// and could hide data loss. Each mutation re-reads the database first.
func applyActions(ctx context.Context, repository *store.Store, objects *objectstore.Store, orphans, stale []item, grace time.Duration, result *actions) {
for _, orphan := range orphans {
stillReferenced, err := repository.AttachmentByObjectKey(ctx, orphan.ObjectKey)
if err != nil {
result.Errors = append(result.Errors, "recheck "+orphan.ObjectKey+": "+err.Error())
continue
}
if stillReferenced {
result.Skipped = append(result.Skipped, orphan.ObjectKey)
continue
}
if err := objects.Remove(ctx, orphan.ObjectKey); err != nil {
result.Errors = append(result.Errors, "delete "+orphan.ObjectKey+": "+err.Error())
continue
}
result.DeletedObjects = append(result.DeletedObjects, orphan.ObjectKey)
}
for _, pending := range stale {
status, key, updatedAt, err := repository.AttachmentState(ctx, pending.ID)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
result.Skipped = append(result.Skipped, pending.ObjectKey)
continue
}
result.Errors = append(result.Errors, "recheck "+pending.ID+": "+err.Error())
continue
}
if status != "pending" {
result.Skipped = append(result.Skipped, pending.ObjectKey)
continue
}
if time.Since(updatedAt) < grace {
// Defensive: the snapshot said stale, but the row is fresh now
// (a retried upload may have updated it). Never delete it.
result.Skipped = append(result.Skipped, pending.ObjectKey)
continue
}
// Delete the intent row first, then the object. The reverse order has
// a race: a concurrent MarkAttachmentReady could promote the row
// between Remove and DELETE, leaving a ready row whose bytes are gone.
// With this order a crash after the row delete leaves an orphan object
// that the next run removes after the grace period.
deleted, err := repository.DeleteAttachmentIfPending(ctx, pending.ID)
if err != nil {
result.Errors = append(result.Errors, "delete row "+pending.ID+": "+err.Error())
continue
}
if !deleted {
result.Skipped = append(result.Skipped, pending.ObjectKey)
continue
}
result.DeletedPendingRows = append(result.DeletedPendingRows, pending.ID)
if !pending.ObjectPresent {
continue
}
if err := objects.Remove(ctx, key); err != nil {
result.Errors = append(result.Errors, "delete orphaned object after row "+key+": "+err.Error())
continue
}
result.DeletedObjects = append(result.DeletedObjects, key)
}
}
func ageSeconds(now, then time.Time) int64 {
if then.IsZero() {
return -1
}
age := now.Sub(then)
if age < 0 {
return 0
}
return int64(age.Seconds())
}
func sortFindings(value *findings) {
sort.Slice(value.OrphanObjects, func(i, j int) bool { return value.OrphanObjects[i].ObjectKey < value.OrphanObjects[j].ObjectKey })
sort.Slice(value.ProtectedObjects, func(i, j int) bool { return value.ProtectedObjects[i].ObjectKey < value.ProtectedObjects[j].ObjectKey })
sort.Slice(value.MissingObjects, func(i, j int) bool { return value.MissingObjects[i].ObjectKey < value.MissingObjects[j].ObjectKey })
sort.Slice(value.StalePending, func(i, j int) bool { return value.StalePending[i].ObjectKey < value.StalePending[j].ObjectKey })
sort.Slice(value.ProtectedPending, func(i, j int) bool { return value.ProtectedPending[i].ObjectKey < value.ProtectedPending[j].ObjectKey })
}
+71
View File
@@ -0,0 +1,71 @@
// Command s3bootstrap creates the private attachment bucket idempotently and
// proves that the configured administrative credentials can use it. It is a
// one-shot compose service, separate from the API: API replicas never receive
// the administrative credentials and cannot create buckets.
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
"time"
"mtusi.ru/messenger-lab4/internal/objectstore"
)
func main() {
endpoint := strings.TrimSpace(os.Getenv("S3_ENDPOINT"))
bucket := strings.TrimSpace(os.Getenv("S3_BUCKET"))
region := strings.TrimSpace(os.Getenv("S3_REGION"))
if region == "" {
region = "us-east-1"
}
accessKey := strings.TrimSpace(os.Getenv("S3_ADMIN_ACCESS_KEY"))
secretKey := strings.TrimSpace(os.Getenv("S3_ADMIN_SECRET_KEY"))
if endpoint == "" || bucket == "" || accessKey == "" || secretKey == "" {
fmt.Fprintln(os.Stderr, "s3bootstrap: S3_ENDPOINT, S3_BUCKET, S3_ADMIN_ACCESS_KEY and S3_ADMIN_SECRET_KEY are required")
os.Exit(2)
}
timeout := 30 * time.Second
if raw := strings.TrimSpace(os.Getenv("S3_TIMEOUT_SECONDS")); raw != "" {
seconds, err := strconv.Atoi(raw)
if err != nil || seconds < 5 || seconds > 120 {
fmt.Fprintln(os.Stderr, "s3bootstrap: S3_TIMEOUT_SECONDS must be an integer between 5 and 120")
os.Exit(2)
}
timeout = time.Duration(seconds) * time.Second
}
store, err := objectstore.Open(objectstore.Config{
Endpoint: endpoint,
Region: region,
Bucket: bucket,
AccessKey: accessKey,
SecretKey: secretKey,
Timeout: timeout,
})
if err != nil {
fmt.Fprintln(os.Stderr, "s3bootstrap: configuration error:", err)
os.Exit(2)
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
created, err := store.EnsureBucket(ctx)
if err != nil {
fmt.Fprintln(os.Stderr, "s3bootstrap: bucket creation failed:", err)
os.Exit(1)
}
if err := store.Probe(ctx); err != nil {
fmt.Fprintln(os.Stderr, "s3bootstrap: credential/bucket probe failed:", err)
os.Exit(1)
}
result := map[string]any{
"bucket": bucket,
"created": created,
"verified": true,
}
encoded, _ := json.Marshal(result)
fmt.Println(string(encoded))
}
+134
View File
@@ -0,0 +1,134 @@
// Command s3ctl is a small operator/test helper for the private bucket. It is
// not part of the HTTP API: it uses the same restricted API credentials as the
// application and is used only to seed failure scenarios for the reconciler
// and to prove that anonymous access and cross-bucket access are denied.
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"time"
"mtusi.ru/messenger-lab4/internal/config"
"mtusi.ru/messenger-lab4/internal/objectstore"
)
func main() {
op := flag.String("op", "", "put, get, stat, delete or list")
key := flag.String("key", "", "object key")
file := flag.String("file", "", "file to upload for -op put")
contentType := flag.String("content-type", "application/octet-stream", "content type for -op put")
prefix := flag.String("prefix", "", "prefix for -op list")
bucketOverride := flag.String("bucket", "", "override the configured bucket (permission test)")
flag.Parse()
cfg, err := config.LoadTool()
if err != nil {
fmt.Fprintln(os.Stderr, "s3ctl: configuration error:", err)
os.Exit(2)
}
bucket := cfg.S3Bucket
if *bucketOverride != "" {
bucket = *bucketOverride
}
store, err := objectstore.Open(objectstore.Config{
Endpoint: cfg.S3Endpoint,
Region: cfg.S3Region,
Bucket: bucket,
AccessKey: cfg.S3AccessKey,
SecretKey: cfg.S3SecretKey,
Timeout: cfg.S3Timeout,
})
if err != nil {
fmt.Fprintln(os.Stderr, "s3ctl: configuration error:", err)
os.Exit(2)
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
switch *op {
case "put":
if *key == "" || *file == "" {
fail("-op put requires -key and -file")
}
handle, err := os.Open(*file)
if err != nil {
fail("cannot open -file: " + err.Error())
}
defer handle.Close()
info, err := handle.Stat()
if err != nil {
fail("cannot stat -file: " + err.Error())
}
if err := store.Put(ctx, *key, handle, info.Size(), *contentType); err != nil {
fail("put failed: " + err.Error())
}
print(map[string]any{"operation": "put", "key": *key, "size_bytes": info.Size()})
case "delete":
if *key == "" {
fail("-op delete requires -key")
}
if err := store.Remove(ctx, *key); err != nil {
fail("delete failed: " + err.Error())
}
print(map[string]any{"operation": "delete", "key": *key})
case "stat":
if *key == "" {
fail("-op stat requires -key")
}
info, err := store.Stat(ctx, *key)
if err != nil {
fail("stat failed: " + err.Error())
}
print(map[string]any{"operation": "stat", "key": info.Key, "size_bytes": info.Size, "content_type": info.ContentType, "last_modified": info.LastModified.UTC().Format(time.RFC3339Nano)})
case "list":
items, err := store.List(ctx, *prefix)
if err != nil {
fail("list failed: " + err.Error())
}
keys := make([]map[string]any, 0, len(items))
for _, item := range items {
keys = append(keys, map[string]any{"key": item.Key, "size_bytes": item.Size, "last_modified": item.LastModified.UTC().Format(time.RFC3339Nano)})
}
print(map[string]any{"operation": "list", "bucket": bucket, "prefix": *prefix, "objects": keys})
case "get":
if *key == "" {
fail("-op get requires -key")
}
body, info, err := store.Get(ctx, *key)
if err != nil {
fail("get failed: " + err.Error())
}
defer body.Close()
buffer := make([]byte, 32*1024)
written := int64(0)
for {
n, readErr := body.Read(buffer)
if n > 0 {
if _, err := os.Stdout.Write(buffer[:n]); err != nil {
fail("write stdout failed")
}
written += int64(n)
}
if readErr != nil {
break
}
}
fmt.Fprintf(os.Stderr, "s3ctl: read %d of %d bytes\n", written, info.Size)
default:
fail("-op must be one of put, get, stat, delete or list")
}
}
func print(value any) {
encoded, _ := json.Marshal(value)
fmt.Println(string(encoded))
}
func fail(message string) {
fmt.Fprintln(os.Stderr, "s3ctl:", message)
os.Exit(1)
}
+320
View File
@@ -0,0 +1,320 @@
# Lab4 local teaching stand: client -> HAProxy -> 2+ interchangeable API
# processes -> shared PostgreSQL and Valkey, plus a private SeaweedFS S3 store.
#
# There is intentionally no container_name: a Compose service with fixed
# container names cannot be scaled. Every replica gets its own container ID,
# hostname and X-Instance-Id. Only HAProxy on 127.0.0.1:8084 is published;
# API, S3, SeaweedFS master/filer/volume and the admin surfaces stay on the
# internal backend network.
#
# Start: make env && make up
# Stop: make stop (processes stopped, named volumes and data preserved)
# Remove: make down (containers removed, volumes preserved)
# Purge: make purge (containers AND named volumes removed; explicit data loss)
name: ${COMPOSE_PROJECT_NAME:-mtusi-lab4-melnikov}
x-api-build: &api-build
context: .
args:
VERSION: ${APP_VERSION:-1.0.0}
REVISION: ${GIT_REVISION:-unknown}
x-s3-common: &s3-common
S3_ENDPOINT: http://s3:8333
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
S3_TIMEOUT_SECONDS: ${S3_TIMEOUT_SECONDS:-10}
services:
postgres:
image: postgres:16.4-alpine3.20@sha256:5660c2cbfea50c7a9127d17dc4e48543eedd3d7a41a595a2dfa572471e37e64c
environment:
POSTGRES_USER: ${POSTGRES_USER:-messenger}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env via make env}
POSTGRES_DB: ${POSTGRES_DB:-messenger}
PGDATA: /var/lib/postgresql/data/pgdata
command:
- postgres
- -c
- max_connections=100
- -c
- shared_buffers=128MB
- -c
- effective_cache_size=256MB
- -c
- work_mem=4MB
- -c
- maintenance_work_mem=64MB
- -c
- max_wal_size=4GB
- -c
- checkpoint_timeout=30min
- -c
- checkpoint_completion_target=0.9
volumes:
- pgdata:/var/lib/postgresql/data
networks:
- backend
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 3s
timeout: 3s
retries: 20
start_period: 5s
restart: unless-stopped
security_opt:
- no-new-privileges:true
stop_grace_period: 20s
deploy:
resources:
limits:
cpus: "${POSTGRES_CPU_LIMIT:-0.5}"
memory: ${POSTGRES_MEM_LIMIT:-384M}
valkey:
image: valkey/valkey:8.0.2-alpine@sha256:752ba000a58bc8925d11ee863a39b5225617cd2cb3dbc9ec8ac65268b65ebb6d
environment:
VALKEY_PASSWORD: ${VALKEY_PASSWORD:?set VALKEY_PASSWORD in .env via make env}
# Shared session store. AOF everysec is the durability boundary: graceful
# restart keeps acknowledged sessions; a hard crash can lose up to one
# second of session writes. TTLs are absolute deadlines, so replaying the
# AOF neither revives nor extends a session.
command:
- valkey-server
- --appendonly
- "yes"
- --appendfsync
- everysec
- --requirepass
- ${VALKEY_PASSWORD:?set VALKEY_PASSWORD in .env via make env}
- --protected-mode
- "no"
volumes:
- valkeydata:/data
networks:
- backend
healthcheck:
test: ["CMD-SHELL", "valkey-cli --no-auth-warning -a \"$$VALKEY_PASSWORD\" ping | grep -q PONG"]
interval: 3s
timeout: 3s
retries: 20
start_period: 5s
restart: unless-stopped
security_opt:
- no-new-privileges:true
stop_grace_period: 20s
deploy:
resources:
limits:
cpus: "${VALKEY_CPU_LIMIT:-0.1}"
memory: ${VALKEY_MEM_LIMIT:-96M}
# One S3-compatible server (SeaweedFS) owns the original bytes. The image is
# pinned by tag and digest. The master/filer/volume/S3 ports stay unpublished;
# only the API reaches the private bucket over the backend network.
s3:
image: chrislusf/seaweedfs:3.98@sha256:2f7de737bd35c5e2cf93944e8aa66de802a135f068ea285d8d290d0206347d22
command:
- server
- -dir=/data
- -s3
- -s3.port=8333
- -s3.config=/etc/seaweedfs/s3.json
volumes:
- s3data:/data
# Generated locally by make env from .env; contains local synthetic
# credentials only and is ignored by Git.
- ./infra/seaweedfs-s3.json:/etc/seaweedfs/s3.json:ro
networks:
- backend
healthcheck:
# The master answers on 9333 before the S3 gateway on 8333 is ready.
# Probe the actual S3 port: any HTTP response (normally 403 for an
# anonymous root request) proves the gateway is listening.
test: ["CMD-SHELL", "wget -S -O /dev/null http://127.0.0.1:8333/ 2>&1 | grep -qE 'HTTP/[0-9.]+ (200|400|403)'"]
interval: 3s
timeout: 3s
retries: 30
start_period: 20s
restart: unless-stopped
security_opt:
- no-new-privileges:true
stop_grace_period: 20s
deploy:
resources:
limits:
cpus: "${S3_CPU_LIMIT:-0.4}"
memory: ${S3_MEM_LIMIT:-384M}
# One-shot, idempotent bucket bootstrap with the administrative SeaweedFS
# identity. The API never receives these credentials.
s3-init:
image: ${API_IMAGE:-mtusi-messenger-lab4-melnikov:local}
build: *api-build
entrypoint: ["/app/s3bootstrap"]
environment:
<<: *s3-common
S3_ADMIN_ACCESS_KEY: ${S3_ADMIN_ACCESS_KEY:?set S3_ADMIN_ACCESS_KEY in .env via make env}
S3_ADMIN_SECRET_KEY: ${S3_ADMIN_SECRET_KEY:?set S3_ADMIN_SECRET_KEY in .env via make env}
depends_on:
s3:
condition: service_healthy
networks:
- backend
# A stopped service alias must fail closed. Without an explicit search
# domain, the host's public search suffixes could turn the single-label
# name "s3" into a public host when the container is temporarily absent.
# "invalid" is reserved by RFC 2606 and always NXDOMAIN.
dns_search:
- invalid
restart: "no"
read_only: true
tmpfs:
- /tmp
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "0.2"
memory: 64M
# One-shot migration runner. API replicas depend on this service completing,
# so the schema is never migrated by a race between replicas. The advisory
# lock and checksums make a repeated invocation safe.
migrate:
image: ${API_IMAGE:-mtusi-messenger-lab4-melnikov:local}
build: *api-build
entrypoint: ["/app/migrate"]
environment:
APP_ENV: ${APP_ENV:-lab}
LOG_LEVEL: ${LOG_LEVEL:-info}
DATABASE_URL: postgres://${POSTGRES_USER:-messenger}:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env via make env}@postgres:5432/${POSTGRES_DB:-messenger}?sslmode=disable
DB_MAX_CONNS: "2"
DB_CONNECT_TIMEOUT_SECONDS: "3"
DB_STATEMENT_TIMEOUT_SECONDS: "10"
DB_QUERY_TIMEOUT_SECONDS: "10"
depends_on:
postgres:
condition: service_healthy
networks:
- backend
restart: "no"
read_only: true
security_opt:
- no-new-privileges:true
deploy:
resources:
limits:
cpus: "0.25"
memory: 128M
api:
image: ${API_IMAGE:-mtusi-messenger-lab4-melnikov:local}
build: *api-build
environment:
APP_HOST: 0.0.0.0
APP_PORT: "8080"
APP_ENV: ${APP_ENV:-lab}
LOG_LEVEL: ${LOG_LEVEL:-info}
DATABASE_URL: postgres://${POSTGRES_USER:-messenger}:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env via make env}@postgres:5432/${POSTGRES_DB:-messenger}?sslmode=disable
CACHE_URL: redis://:${VALKEY_PASSWORD:?set VALKEY_PASSWORD in .env via make env}@valkey:6379/0
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
DB_MAX_CONNS: ${DB_MAX_CONNS:-8}
DB_MIN_CONNS: ${DB_MIN_CONNS:-1}
DB_CONNECT_TIMEOUT_SECONDS: ${DB_CONNECT_TIMEOUT_SECONDS:-3}
DB_STATEMENT_TIMEOUT_SECONDS: ${DB_STATEMENT_TIMEOUT_SECONDS:-3}
DB_QUERY_TIMEOUT_SECONDS: ${DB_QUERY_TIMEOUT_SECONDS:-3}
CACHE_POOL_SIZE: ${CACHE_POOL_SIZE:-8}
CACHE_TIMEOUT_SECONDS: ${CACHE_TIMEOUT_SECONDS:-2}
SHUTDOWN_TIMEOUT_SECONDS: ${SHUTDOWN_TIMEOUT_SECONDS:-6}
SHUTDOWN_DRAIN_SECONDS: ${SHUTDOWN_DRAIN_SECONDS:-3}
STARTUP_TIMEOUT_SECONDS: ${STARTUP_TIMEOUT_SECONDS:-30}
METRICS_ADDR: 127.0.0.1:9090
GOMEMLIMIT: ${GOMEMLIMIT:-300MiB}
<<: *s3-common
S3_ACCESS_KEY: ${S3_API_ACCESS_KEY:?set S3_API_ACCESS_KEY in .env via make env}
S3_SECRET_KEY: ${S3_API_SECRET_KEY:?set S3_API_SECRET_KEY in .env via make env}
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
UPLOAD_DECODE_CONCURRENCY: ${UPLOAD_DECODE_CONCURRENCY:-1}
S3_PUT_CONCURRENCY: ${S3_PUT_CONCURRENCY:-1}
depends_on:
postgres:
condition: service_healthy
valkey:
condition: service_healthy
migrate:
condition: service_completed_successfully
s3-init:
condition: service_completed_successfully
networks:
- backend
# Same fail-closed DNS rule as s3-init: while S3 is stopped, "s3" must not
# fall through to a public search-domain host.
dns_search:
- invalid
healthcheck:
test: ["CMD", "/app/messenger", "-healthcheck"]
interval: 3s
timeout: 2s
retries: 12
start_period: 10s
restart: unless-stopped
read_only: true
tmpfs:
# Bounded scratch space for one upload in flight. It is an ephemeral
# staging area, never the source of truth for a ready attachment.
- /tmp:size=256m,mode=1777
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
stop_grace_period: 15s
deploy:
replicas: ${API_REPLICAS:-2}
resources:
limits:
cpus: "${API_CPU_LIMIT:-0.5}"
memory: ${API_MEM_LIMIT:-384M}
lb:
image: haproxy:3.0-alpine@sha256:457d1c0dcbf2dfc0e0358723c07df4410d30e7de42bec036b383cfede4a5dbe3
volumes:
- ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
ports:
- "127.0.0.1:${LB_PORT:-8084}:8080"
networks:
- backend
healthcheck:
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:8404/stats || exit 1"]
interval: 3s
timeout: 2s
retries: 10
start_period: 5s
restart: unless-stopped
read_only: true
tmpfs:
- /tmp
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
stop_grace_period: 10s
deploy:
resources:
limits:
cpus: "${LB_CPU_LIMIT:-0.2}"
memory: ${LB_MEM_LIMIT:-64M}
volumes:
pgdata:
name: ${COMPOSE_PROJECT_NAME:-mtusi-lab4-melnikov}-pgdata
valkeydata:
name: ${COMPOSE_PROJECT_NAME:-mtusi-lab4-melnikov}-valkeydata
s3data:
name: ${COMPOSE_PROJECT_NAME:-mtusi-lab4-melnikov}-s3data
networks:
backend:
name: ${COMPOSE_PROJECT_NAME:-mtusi-lab4-melnikov}-net
+374
View File
@@ -0,0 +1,374 @@
== clean clone ==
source revision: fdbb4264848357130b348709607e80095033207c
clone: /Users/ivanmuller/Desktop/oh_my_life/.local/highload-tasks/lab4-artifacts/clean-clone.itVSEa
project: mtusi-lab4-melnikov-clean; LB port: 8085; image: mtusi-lab4-melnikov-clean:local
stopping the main lab4 stand with data preserved for the check
Container mtusi-lab4-melnikov-lb-1 Stopping
Container mtusi-lab4-melnikov-api-1 Stopping
Container mtusi-lab4-melnikov-api-2 Stopping
Container mtusi-lab4-melnikov-lb-1 Stopped
Container mtusi-lab4-melnikov-api-2 Stopped
Container mtusi-lab4-melnikov-api-1 Stopped
Container mtusi-lab4-melnikov-migrate-1 Stopping
Container mtusi-lab4-melnikov-s3-init-1 Stopping
Container mtusi-lab4-melnikov-valkey-1 Stopping
Container mtusi-lab4-melnikov-migrate-1 Stopped
Container mtusi-lab4-melnikov-postgres-1 Stopping
Container mtusi-lab4-melnikov-s3-init-1 Stopped
Container mtusi-lab4-melnikov-s3-1 Stopping
Container mtusi-lab4-melnikov-postgres-1 Stopped
Container mtusi-lab4-melnikov-valkey-1 Stopped
Container mtusi-lab4-melnikov-s3-1 Stopped
== local configuration with fresh synthetic credentials ==
wrote .env with generated local synthetic credentials (mode 600); values not printed
wrote infra/seaweedfs-s3.json (mode 600); values not printed
== offline contract and syntax checks ==
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
== build, migrate and bootstrap the bucket from empty volumes ==
GIT_REVISION="fdbb4264848357130b348709607e80095033207c" API_IMAGE="mtusi-lab4-melnikov-clean:local" ./scripts/compose.sh --env-file .env up -d --build
time="2026-12-04T14:58:02+03:00" level=warning msg="Docker Compose is configured to build using Bake, but buildx isn't installed"
#0 building with "colima" instance using docker driver
#1 [migrate internal] load build definition from Dockerfile
#1 transferring dockerfile: 2.79kB done
#1 DONE 0.0s
#2 [s3-init internal] load build definition from Dockerfile
#2 transferring dockerfile: 2.79kB done
#2 DONE 0.0s
#3 [s3-init] resolve image config for docker-image://docker.io/docker/dockerfile:1
#3 DONE 0.2s
#4 [migrate] docker-image://docker.io/docker/dockerfile:1@sha256:572cebbc2b15e6f84c077742952674889cb63cd5e9b80abdffcbe587b6f19183
#4 CACHED
#5 [migrate internal] load metadata for docker.io/library/alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1
#5 DONE 0.0s
#6 [migrate internal] load metadata for docker.io/library/golang:1.25.1-alpine3.22@sha256:b6ed3fd0452c0e9bcdef5597f29cc1418f61672e9d3a2f55bf02e7222c014abd
#6 DONE 0.0s
#7 [s3-init internal] load .dockerignore
#7 transferring context: 220B done
#7 DONE 0.0s
#8 [migrate internal] load .dockerignore
#8 transferring context: 220B done
#8 DONE 0.0s
#9 [migrate build 1/7] FROM docker.io/library/golang:1.25.1-alpine3.22@sha256:b6ed3fd0452c0e9bcdef5597f29cc1418f61672e9d3a2f55bf02e7222c014abd
#9 DONE 0.0s
#10 [migrate runtime 1/7] FROM docker.io/library/alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1
#10 DONE 0.0s
#11 [s3-init internal] load build context
#11 transferring context: 20.88MB 0.2s done
#11 DONE 0.2s
#12 [migrate internal] load build context
#12 transferring context: 20.88MB 0.2s done
#12 DONE 0.2s
#13 [s3-init build 2/7] WORKDIR /src
#13 CACHED
#14 [s3-init build 4/7] COPY vendor ./vendor
#14 CACHED
#15 [s3-init build 3/7] COPY go.mod go.sum ./
#15 CACHED
#16 [s3-init build 5/7] COPY cmd ./cmd
#16 CACHED
#17 [migrate build 6/7] COPY internal ./internal
#17 CACHED
#18 [migrate build 7/7] RUN go build -trimpath -buildvcs=false -ldflags="-s -w -buildid= -X main.version=1.0.0 -X main.revision=fdbb4264848357130b348709607e80095033207c" -o /out/messenger ./cmd/messenger && go build -trimpath -buildvcs=false -ldflags="-s -w -buildid= -X main.revision=fdbb4264848357130b348709607e80095033207c" -o /out/migrate ./cmd/migrate && go build -trimpath -buildvcs=false -ldflags="-s -w -buildid= -X main.revision=fdbb4264848357130b348709607e80095033207c" -o /out/s3bootstrap ./cmd/s3bootstrap && go build -trimpath -buildvcs=false -ldflags="-s -w -buildid= -X main.revision=fdbb4264848357130b348709607e80095033207c" -o /out/s3ctl ./cmd/s3ctl && go build -trimpath -buildvcs=false -ldflags="-s -w -buildid= -X main.revision=fdbb4264848357130b348709607e80095033207c" -o /out/reconciler ./cmd/reconciler
#18 DONE 20.2s
#19 [migrate runtime 2/7] WORKDIR /app
#19 CACHED
#20 [migrate runtime 3/7] COPY --from=build --chown=10001:10001 /out/messenger /app/messenger
#20 DONE 0.1s
#21 [migrate build 4/7] COPY vendor ./vendor
#21 CACHED
#22 [migrate build 3/7] COPY go.mod go.sum ./
#22 CACHED
#13 [migrate build 2/7] WORKDIR /src
#13 CACHED
#23 [migrate build 7/7] RUN go build -trimpath -buildvcs=false -ldflags="-s -w -buildid= -X main.version=1.0.0 -X main.revision=fdbb4264848357130b348709607e80095033207c" -o /out/messenger ./cmd/messenger && go build -trimpath -buildvcs=false -ldflags="-s -w -buildid= -X main.revision=fdbb4264848357130b348709607e80095033207c" -o /out/migrate ./cmd/migrate && go build -trimpath -buildvcs=false -ldflags="-s -w -buildid= -X main.revision=fdbb4264848357130b348709607e80095033207c" -o /out/s3bootstrap ./cmd/s3bootstrap && go build -trimpath -buildvcs=false -ldflags="-s -w -buildid= -X main.revision=fdbb4264848357130b348709607e80095033207c" -o /out/s3ctl ./cmd/s3ctl && go build -trimpath -buildvcs=false -ldflags="-s -w -buildid= -X main.revision=fdbb4264848357130b348709607e80095033207c" -o /out/reconciler ./cmd/reconciler
#23 CACHED
#24 [migrate build 5/7] COPY cmd ./cmd
#24 CACHED
#25 [migrate build 6/7] COPY internal ./internal
#25 CACHED
#26 [migrate runtime 3/7] COPY --from=build --chown=10001:10001 /out/messenger /app/messenger
#26 CACHED
#27 [migrate runtime 4/7] COPY --from=build --chown=10001:10001 /out/migrate /app/migrate
#27 DONE 0.0s
#28 [s3-init runtime 5/7] COPY --from=build --chown=10001:10001 /out/s3bootstrap /app/s3bootstrap
#28 DONE 0.0s
#29 [s3-init runtime 6/7] COPY --from=build --chown=10001:10001 /out/s3ctl /app/s3ctl
#29 DONE 0.0s
#30 [s3-init runtime 7/7] COPY --from=build --chown=10001:10001 /out/reconciler /app/reconciler
#30 DONE 0.0s
#31 [s3-init] exporting to image
#31 exporting layers 0.1s done
#31 writing image sha256:6e55e347f8f4505d5b9512450622a61bf0b2a31fd718683906d9a20feb666ef4 done
#31 naming to docker.io/library/mtusi-lab4-melnikov-clean:local done
#31 DONE 0.1s
#32 [migrate] exporting to image
#32 exporting layers 0.1s done
#32 writing image sha256:1c0594a9f7074770777972018923ddfdac7307608429ce422918f98df4fe90d2 done
#32 naming to docker.io/library/mtusi-lab4-melnikov-clean:local done
#32 DONE 0.1s
#33 [migrate] resolving provenance for metadata file
#33 DONE 0.0s
#34 [s3-init] resolving provenance for metadata file
#34 DONE 0.0s
#35 [api internal] load build definition from Dockerfile
#35 transferring dockerfile: 2.79kB done
#35 DONE 0.0s
#3 [api] resolve image config for docker-image://docker.io/docker/dockerfile:1
#3 DONE 0.5s
#4 [api] docker-image://docker.io/docker/dockerfile:1@sha256:572cebbc2b15e6f84c077742952674889cb63cd5e9b80abdffcbe587b6f19183
#4 CACHED
#5 [api internal] load metadata for docker.io/library/alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1
#5 DONE 0.0s
#6 [api internal] load metadata for docker.io/library/golang:1.25.1-alpine3.22@sha256:b6ed3fd0452c0e9bcdef5597f29cc1418f61672e9d3a2f55bf02e7222c014abd
#6 DONE 0.0s
#36 [api internal] load .dockerignore
#36 transferring context: 220B done
#36 DONE 0.0s
#9 [api build 1/7] FROM docker.io/library/golang:1.25.1-alpine3.22@sha256:b6ed3fd0452c0e9bcdef5597f29cc1418f61672e9d3a2f55bf02e7222c014abd
#9 DONE 0.0s
#10 [api runtime 1/7] FROM docker.io/library/alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1
#10 DONE 0.0s
#37 [api internal] load build context
#37 transferring context: 84.08kB 0.0s done
#37 DONE 0.0s
#38 [api] resolving provenance for metadata file
#38 DONE 0.0s
#39 [api runtime 6/7] COPY --from=build --chown=10001:10001 /out/s3ctl /app/s3ctl
#39 CACHED
#40 [api build 4/7] COPY vendor ./vendor
#40 CACHED
#41 [api build 3/7] COPY go.mod go.sum ./
#41 CACHED
#42 [api runtime 3/7] COPY --from=build --chown=10001:10001 /out/messenger /app/messenger
#42 CACHED
#43 [api build 7/7] RUN go build -trimpath -buildvcs=false -ldflags="-s -w -buildid= -X main.version=1.0.0 -X main.revision=fdbb4264848357130b348709607e80095033207c" -o /out/messenger ./cmd/messenger && go build -trimpath -buildvcs=false -ldflags="-s -w -buildid= -X main.revision=fdbb4264848357130b348709607e80095033207c" -o /out/migrate ./cmd/migrate && go build -trimpath -buildvcs=false -ldflags="-s -w -buildid= -X main.revision=fdbb4264848357130b348709607e80095033207c" -o /out/s3bootstrap ./cmd/s3bootstrap && go build -trimpath -buildvcs=false -ldflags="-s -w -buildid= -X main.revision=fdbb4264848357130b348709607e80095033207c" -o /out/s3ctl ./cmd/s3ctl && go build -trimpath -buildvcs=false -ldflags="-s -w -buildid= -X main.revision=fdbb4264848357130b348709607e80095033207c" -o /out/reconciler ./cmd/reconciler
#43 CACHED
#44 [api build 5/7] COPY cmd ./cmd
#44 CACHED
#19 [api runtime 2/7] WORKDIR /app
#19 CACHED
#45 [api runtime 5/7] COPY --from=build --chown=10001:10001 /out/s3bootstrap /app/s3bootstrap
#45 CACHED
#46 [api runtime 4/7] COPY --from=build --chown=10001:10001 /out/migrate /app/migrate
#46 CACHED
#13 [api build 2/7] WORKDIR /src
#13 CACHED
#47 [api build 6/7] COPY internal ./internal
#47 CACHED
#48 [api runtime 7/7] COPY --from=build --chown=10001:10001 /out/reconciler /app/reconciler
#48 CACHED
#49 [api] exporting to image
#49 exporting layers done
#49 writing image sha256:7db29b35c6f376a1619e8467362a17a0cc2e12e37368bbc6211a46fd40269fa7 done
#49 naming to docker.io/library/mtusi-lab4-melnikov-clean:local done
#49 DONE 0.0s
api Built
migrate Built
s3-init Built
Network mtusi-lab4-melnikov-clean-net Creating
Network mtusi-lab4-melnikov-clean-net Created
Volume "mtusi-lab4-melnikov-clean-pgdata" Creating
Volume "mtusi-lab4-melnikov-clean-pgdata" Created
Volume "mtusi-lab4-melnikov-clean-valkeydata" Creating
Volume "mtusi-lab4-melnikov-clean-valkeydata" Created
Volume "mtusi-lab4-melnikov-clean-s3data" Creating
Volume "mtusi-lab4-melnikov-clean-s3data" Created
Container mtusi-lab4-melnikov-clean-postgres-1 Creating
Container mtusi-lab4-melnikov-clean-lb-1 Creating
Container mtusi-lab4-melnikov-clean-valkey-1 Creating
Container mtusi-lab4-melnikov-clean-s3-1 Creating
Container mtusi-lab4-melnikov-clean-postgres-1 Created
Container mtusi-lab4-melnikov-clean-valkey-1 Created
Container mtusi-lab4-melnikov-clean-migrate-1 Creating
Container mtusi-lab4-melnikov-clean-s3-1 Created
Container mtusi-lab4-melnikov-clean-s3-init-1 Creating
Container mtusi-lab4-melnikov-clean-lb-1 Created
Container mtusi-lab4-melnikov-clean-migrate-1 Created
Container mtusi-lab4-melnikov-clean-s3-init-1 Created
Container mtusi-lab4-melnikov-clean-api-2 Creating
Container mtusi-lab4-melnikov-clean-api-1 Creating
Container mtusi-lab4-melnikov-clean-api-1 Created
Container mtusi-lab4-melnikov-clean-api-2 Created
Container mtusi-lab4-melnikov-clean-s3-1 Starting
Container mtusi-lab4-melnikov-clean-valkey-1 Starting
Container mtusi-lab4-melnikov-clean-postgres-1 Starting
Container mtusi-lab4-melnikov-clean-lb-1 Starting
Container mtusi-lab4-melnikov-clean-postgres-1 Started
Container mtusi-lab4-melnikov-clean-postgres-1 Waiting
Container mtusi-lab4-melnikov-clean-lb-1 Started
Container mtusi-lab4-melnikov-clean-s3-1 Started
Container mtusi-lab4-melnikov-clean-valkey-1 Started
Container mtusi-lab4-melnikov-clean-s3-1 Waiting
Container mtusi-lab4-melnikov-clean-postgres-1 Healthy
Container mtusi-lab4-melnikov-clean-migrate-1 Starting
Container mtusi-lab4-melnikov-clean-migrate-1 Started
Container mtusi-lab4-melnikov-clean-s3-1 Healthy
Container mtusi-lab4-melnikov-clean-s3-init-1 Starting
Container mtusi-lab4-melnikov-clean-s3-init-1 Started
Container mtusi-lab4-melnikov-clean-valkey-1 Waiting
Container mtusi-lab4-melnikov-clean-migrate-1 Waiting
Container mtusi-lab4-melnikov-clean-s3-init-1 Waiting
Container mtusi-lab4-melnikov-clean-postgres-1 Waiting
Container mtusi-lab4-melnikov-clean-valkey-1 Healthy
Container mtusi-lab4-melnikov-clean-postgres-1 Healthy
Container mtusi-lab4-melnikov-clean-migrate-1 Exited
Container mtusi-lab4-melnikov-clean-s3-init-1 Exited
Container mtusi-lab4-melnikov-clean-api-2 Starting
Container mtusi-lab4-melnikov-clean-api-2 Started
Container mtusi-lab4-melnikov-clean-api-1 Starting
Container mtusi-lab4-melnikov-clean-api-1 Started
./scripts/wait-ready.sh
ready: http://127.0.0.1:8085/health/ready
users=0
attachments=0
migrations=1,2,3,4,5
s3-init-1 | {"bucket":"messenger-attachments","created":true,"verified":true}
NAME STATUS
mtusi-lab4-melnikov-clean-api-1 Up Less than a second (health: starting)
mtusi-lab4-melnikov-clean-api-2 Up Less than a second (health: starting)
mtusi-lab4-melnikov-clean-lb-1 Up 24 seconds (healthy)
mtusi-lab4-melnikov-clean-postgres-1 Up 24 seconds (healthy)
mtusi-lab4-melnikov-clean-s3-1 Up 24 seconds (healthy)
mtusi-lab4-melnikov-clean-valkey-1 Up 24 seconds (healthy)
== public and own API tests on the clean stand ==
python3 tests/smoke.py --base-url "http://127.0.0.1:8085"
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
go test -count=1 ./...
? mtusi.ru/messenger-lab4/cmd/loadgen [no test files]
? mtusi.ru/messenger-lab4/cmd/messenger [no test files]
? mtusi.ru/messenger-lab4/cmd/migrate [no test files]
? mtusi.ru/messenger-lab4/cmd/reconciler [no test files]
? mtusi.ru/messenger-lab4/cmd/s3bootstrap [no test files]
? mtusi.ru/messenger-lab4/cmd/s3ctl [no test files]
ok mtusi.ru/messenger-lab4/internal/api 0.543s
ok mtusi.ru/messenger-lab4/internal/auth 0.388s
ok mtusi.ru/messenger-lab4/internal/config 0.665s
ok mtusi.ru/messenger-lab4/internal/cursor 0.288s
ok mtusi.ru/messenger-lab4/internal/model 1.081s
? mtusi.ru/messenger-lab4/internal/objectstore [no test files]
? mtusi.ru/messenger-lab4/internal/session [no test files]
ok mtusi.ru/messenger-lab4/internal/store 1.225s
ok mtusi.ru/messenger-lab4/internal/uuid 0.877s
python3 student-tests/blackbox.py --base-url "http://127.0.0.1:8085"
PASS health
PASS registration/auth
PASS registration validation
PASS chats/membership
PASS messages
PASS attachments and message links
PASS instances (2 observed)
PASS idempotency replay/conflict/scope/validation
PASS concurrent idempotency across 2 replicas
PASS pagination
PASS concurrent registration
PASS concurrent messages
PASS logout
PASS: lab4 student black-box suite, 149 checks
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://127.0.0.1:8085"
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
== intentional cleanup of this temporary clone's resources ==
PURGE removes containers AND named volumes mtusi-lab4-melnikov-*: all synthetic data is lost.
./scripts/compose.sh --env-file .env down -v
Container mtusi-lab4-melnikov-clean-lb-1 Stopping
Container mtusi-lab4-melnikov-clean-api-2 Stopping
Container mtusi-lab4-melnikov-clean-api-1 Stopping
Container mtusi-lab4-melnikov-clean-lb-1 Stopped
Container mtusi-lab4-melnikov-clean-lb-1 Removing
Container mtusi-lab4-melnikov-clean-lb-1 Removed
Container mtusi-lab4-melnikov-clean-api-1 Stopped
Container mtusi-lab4-melnikov-clean-api-1 Removing
Container mtusi-lab4-melnikov-clean-api-2 Stopped
Container mtusi-lab4-melnikov-clean-api-2 Removing
Container mtusi-lab4-melnikov-clean-api-1 Removed
Container mtusi-lab4-melnikov-clean-api-2 Removed
Container mtusi-lab4-melnikov-clean-valkey-1 Stopping
Container mtusi-lab4-melnikov-clean-s3-init-1 Stopping
Container mtusi-lab4-melnikov-clean-migrate-1 Stopping
Container mtusi-lab4-melnikov-clean-s3-init-1 Stopped
Container mtusi-lab4-melnikov-clean-s3-init-1 Removing
Container mtusi-lab4-melnikov-clean-migrate-1 Stopped
Container mtusi-lab4-melnikov-clean-migrate-1 Removing
Container mtusi-lab4-melnikov-clean-s3-init-1 Removed
Container mtusi-lab4-melnikov-clean-s3-1 Stopping
Container mtusi-lab4-melnikov-clean-migrate-1 Removed
Container mtusi-lab4-melnikov-clean-postgres-1 Stopping
Container mtusi-lab4-melnikov-clean-postgres-1 Stopped
Container mtusi-lab4-melnikov-clean-postgres-1 Removing
Container mtusi-lab4-melnikov-clean-postgres-1 Removed
Container mtusi-lab4-melnikov-clean-valkey-1 Stopped
Container mtusi-lab4-melnikov-clean-valkey-1 Removing
Container mtusi-lab4-melnikov-clean-valkey-1 Removed
Container mtusi-lab4-melnikov-clean-s3-1 Stopped
Container mtusi-lab4-melnikov-clean-s3-1 Removing
Container mtusi-lab4-melnikov-clean-s3-1 Removed
Volume mtusi-lab4-melnikov-clean-s3data Removing
Volume mtusi-lab4-melnikov-clean-valkeydata Removing
Network mtusi-lab4-melnikov-clean-net Removing
Volume mtusi-lab4-melnikov-clean-pgdata Removing
Volume mtusi-lab4-melnikov-clean-s3data Removed
Volume mtusi-lab4-melnikov-clean-pgdata Removed
Volume mtusi-lab4-melnikov-clean-valkeydata Removed
Network mtusi-lab4-melnikov-clean-net Removed
PASS: clean clone built, migrated, bootstrapped and tested; temporary resources removed
main lab4 stand was stopped for the check; data volumes are preserved.
run 'make up' in /Users/ivanmuller/Desktop/oh_my_life/highload/lab4 to restart it.
+15
View File
@@ -0,0 +1,15 @@
### attachment_checks
### command: make PYTHON=/usr/bin/python3 test-attachment
### started_at: 2026-12-04T11:31:07Z
/usr/bin/python3 student-tests/attachment-checks.py --base-url "http://127.0.0.1:8084"
PASS size and pixel limits
PASS MIME, damage and filename display
PASS filename validation
PASS attachment ACL
PASS interrupted upload leaves no row/object
PASS unavailable S3 is 503, not 500, and recovers
PASS unavailable PostgreSQL is 503, liveness stays up, data recovers
PASS no token/password/message/S3 secret in API logs
PASS: lab4 attachment checks, 39 assertions
### exit_code: 0
+22
View File
@@ -0,0 +1,22 @@
### container_checks
### command: make PYTHON=/usr/bin/python3 test-container
### started_at: 2026-12-04T11:31:52Z
/usr/bin/python3 scripts/container-checks.py --base-url "http://127.0.0.1:8084"
lab4 container checks at 2026-12-04T11:31:54.054715Z
result: PASS
git revision: 02fc97b78aff9a1890bd2bade40f6cd8654e2000
API replicas: 2 (40fdc2d47091, 3e58d4b42901)
API image ids: sha256:9f46ec2a6cf007f77202d3ae97afc0f710ee3cd191b8c620405f397b193932ce
S3 image id: sha256:0513e5e469b80438fcb8961e4b7c422e782251114d4930ac17cd9fbe508ad5ba
API ports published: {'mtusi-lab4-melnikov-api-1': '', 'mtusi-lab4-melnikov-api-2': ''}
S3 ports published: ''
LB ports: 8080/tcp -> 127.0.0.1:8084
volumes: mtusi-lab4-melnikov-pgdata, mtusi-lab4-melnikov-s3data, mtusi-lab4-melnikov-valkeydata
limits: {"api":[{"name":"mtusi-lab4-melnikov-api-1","nano_cpus":500000000,"memory_bytes":402653184,"readonly_rootfs":true,"cap_drop":["ALL"],"security_opt":["no-new-privileges:true"],"user":"10001:10001","mounts":[],"volume_mounts":[]},{"name":"mtusi-lab4-melnikov-api-2","nano_cpus":500000000,"memory_bytes":402653184,"readonly_rootfs":true,"cap_drop":["ALL"],"security_opt":["no-new-privileges:true"],"user":"10001:10001","mounts":[],"volume_mounts":[]}],"postgres":[{"name":"mtusi-lab4-melnikov-postgres-1","nano_cpus":500000000,"memory_bytes":402653184,"readonly_rootfs":false,"cap_drop":null,"security_opt":["no-new-privileges:true"],"user":"","mounts":["mtusi-lab4-melnikov-pgdata"],"volume_mounts":["mtusi-lab4-melnikov-pgdata"]}],"valkey":[{"name":"mtusi-lab4-melnikov-valkey-1","nano_cpus":100000000,"memory_bytes":100663296,"readonly_rootfs":false,"cap_drop":null,"security_opt":["no-new-privileges:true"],"user":"","mounts":["mtusi-lab4-melnikov-valkeydata"],"volume_mounts":["mtusi-lab4-melnikov-valkeydata"]}],"s3":[{"name":"mtusi-lab4-melnikov-s3-1","nano_cpus":400000000,"memory_bytes":402653184,"readonly_rootfs":false,"cap_drop":null,"security_opt":["no-new-privileges:true"],"user":"","mounts":["mtusi-lab4-melnikov-s3data","/Users/ivanmuller/Desktop/oh_my_life/highload/lab4/infra/seaweedfs-s3.json"],"volume_mounts":["mtusi-lab4-melnikov-s3data"]}],"lb":[{"name":"mtusi-lab4-melnikov-lb-1","nano_cpus":200000000,"memory_bytes":67108864,"readonly_rootfs":true,"cap_drop":["ALL"],"security_opt":["no-new-privileges:true"],"user":"haproxy","mounts":["/Users/ivanmuller/Desktop/oh_my_life/highload/lab4/infra/haproxy.cfg"],"volume_mounts":[]}]}
observed session instances: 3e58d4b42901, 40fdc2d47091
anonymous object GET denied: True
anonymous bucket list denied: True
bootstrap second run: exit=0 created_false=True
PASS: container, S3 privacy and credential checks
### exit_code: 0
+14
View File
@@ -0,0 +1,14 @@
started_at: 2026-12-04T11:30:56Z
base_url: http://127.0.0.1:8084
git_revision: 02fc97b78aff9a1890bd2bade40f6cd8654e2000
git_status_lines: 1
python3: Python 3.14.4
python39: Python 3.9.6
go: go version go1.25.1 darwin/arm64
docker_server: 27.4.0
docker_cpus_mem: CPUs=2 MemTotal=2054631424
api_images:
/mtusi-lab4-melnikov-api-1 image=sha256:9f46ec2a6cf007f77202d3ae97afc0f710ee3cd191b8c620405f397b193932ce started=2026-12-04T11:30:54.036964331Z
/mtusi-lab4-melnikov-api-2 image=sha256:9f46ec2a6cf007f77202d3ae97afc0f710ee3cd191b8c620405f397b193932ce started=2026-12-04T11:30:53.915503045Z
s3_image:
/mtusi-lab4-melnikov-s3-1 image=sha256:0513e5e469b80438fcb8961e4b7c422e782251114d4930ac17cd9fbe508ad5ba
+10
View File
@@ -0,0 +1,10 @@
### experiment
### command: make PYTHON=/usr/bin/python3 experiment
### started_at: 2026-12-04T11:34:51Z
/usr/bin/python3 scripts/upload-experiment.py --base-url "http://127.0.0.1:8084"
== restart API replicas to reset the process high-water mark ==
== generate the reproducible upload profile ==
{"result": "PASS", "observed_peak_concurrency": 12, "successful_uploads": 12, "wall_seconds": 1.088, "process_peak_sampled_rss_bytes": {"255348db8382": 53067776, "291762b7fcf7": 43819008}, "process_final_hwm_bytes": {"255348db8382": 53592064, "291762b7fcf7": 53338112}, "api_memory_limit_bytes": 402653184}
PASS: >=10 concurrent uploads with bounded API process RSS
### exit_code: 0
+9
View File
@@ -0,0 +1,9 @@
### failover_public
### command: make PYTHON=/usr/bin/python3 test-failover ACTION_SCRIPT=scripts/stop-one.sh
### started_at: 2026-12-04T11:33:37Z
/usr/bin/python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:8084"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 139, "failed_attempts": 0, "first_recovery_seconds": 3.246}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
### exit_code: 0
+7
View File
@@ -0,0 +1,7 @@
### failover_upload
### command: /usr/bin/python3 scripts/failover-upload.py --base-url http://127.0.0.1:8084
### started_at: 2026-12-04T11:33:57Z
{"upload_instance": "255348db8382", "download_instance": "291762b7fcf7", "instances_seen": ["291762b7fcf7"], "sha256_matches": true, "stopped_container_state": "exited", "restored_at": "2026-12-04T11:34:01.329817Z"}
PASS: upload survived replica stop and downloaded with the same SHA-256 via another replica
### exit_code: 0
+21
View File
@@ -0,0 +1,21 @@
### go_race
### command: make PYTHON=/usr/bin/python3 test-student-race
### started_at: 2026-12-04T11:31:00Z
go test -race -count=1 ./...
? mtusi.ru/messenger-lab4/cmd/loadgen [no test files]
? mtusi.ru/messenger-lab4/cmd/messenger [no test files]
? mtusi.ru/messenger-lab4/cmd/migrate [no test files]
? mtusi.ru/messenger-lab4/cmd/reconciler [no test files]
? mtusi.ru/messenger-lab4/cmd/s3bootstrap [no test files]
? mtusi.ru/messenger-lab4/cmd/s3ctl [no test files]
ok mtusi.ru/messenger-lab4/internal/api 1.608s
ok mtusi.ru/messenger-lab4/internal/auth 3.915s
ok mtusi.ru/messenger-lab4/internal/config 1.307s
ok mtusi.ru/messenger-lab4/internal/cursor 1.166s
ok mtusi.ru/messenger-lab4/internal/model 1.723s
? mtusi.ru/messenger-lab4/internal/objectstore [no test files]
? mtusi.ru/messenger-lab4/internal/session [no test files]
ok mtusi.ru/messenger-lab4/internal/store 1.871s
ok mtusi.ru/messenger-lab4/internal/uuid 2.008s
### exit_code: 0
+36
View File
@@ -0,0 +1,36 @@
### go_tests
### command: make PYTHON=/usr/bin/python3 test-student
### started_at: 2026-12-04T11:30:57Z
go test -count=1 ./...
? mtusi.ru/messenger-lab4/cmd/loadgen [no test files]
? mtusi.ru/messenger-lab4/cmd/messenger [no test files]
? mtusi.ru/messenger-lab4/cmd/migrate [no test files]
? mtusi.ru/messenger-lab4/cmd/reconciler [no test files]
? mtusi.ru/messenger-lab4/cmd/s3bootstrap [no test files]
? mtusi.ru/messenger-lab4/cmd/s3ctl [no test files]
ok mtusi.ru/messenger-lab4/internal/api 0.251s
ok mtusi.ru/messenger-lab4/internal/auth 1.036s
ok mtusi.ru/messenger-lab4/internal/config 0.373s
ok mtusi.ru/messenger-lab4/internal/cursor 0.527s
ok mtusi.ru/messenger-lab4/internal/model 0.662s
? mtusi.ru/messenger-lab4/internal/objectstore [no test files]
? mtusi.ru/messenger-lab4/internal/session [no test files]
ok mtusi.ru/messenger-lab4/internal/store 0.945s
ok mtusi.ru/messenger-lab4/internal/uuid 1.080s
/usr/bin/python3 student-tests/blackbox.py --base-url "http://127.0.0.1:8084"
PASS health
PASS registration/auth
PASS registration validation
PASS chats/membership
PASS messages
PASS attachments and message links
PASS instances (2 observed)
PASS idempotency replay/conflict/scope/validation
PASS concurrent idempotency across 2 replicas
PASS pagination
PASS concurrent registration
PASS concurrent messages
PASS logout
PASS: lab4 student black-box suite, 149 checks
### exit_code: 0
+7
View File
@@ -0,0 +1,7 @@
### make_check
### command: make PYTHON=/usr/bin/python3 check
### started_at: 2026-12-04T11:30:57Z
/usr/bin/python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
### exit_code: 0
+9
View File
@@ -0,0 +1,9 @@
### make_validate
### command: make PYTHON=.venv/bin/python validate
### started_at: 2026-12-04T11:30:57Z
.venv/bin/python scripts/validate_openapi.py
/Users/ivanmuller/Desktop/oh_my_life/highload/lab4/.venv/lib/python3.9/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
warnings.warn(
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
### exit_code: 0
@@ -0,0 +1,8 @@
### persistence_evidence
### command: /usr/bin/python3 scripts/persistence-evidence.py --base-url http://127.0.0.1:8084
### started_at: 2026-12-04T11:32:43Z
running scripts/restart.sh (all API replicas and used stores, volumes kept)
{"result": "PASS", "checks": {"same_container_ids": true, "started_at_changed": true, "all_services_restarted": true, "volumes_unchanged": true, "same_token_still_valid": true, "message_survived": true, "attachment_metadata_survived": true, "attachment_bytes_survived": true}}
PASS: real containers restarted, volumes and data preserved
### exit_code: 0
+8
View File
@@ -0,0 +1,8 @@
### persistence_public
### command: make PYTHON=/usr/bin/python3 test-persistence ACTION_SCRIPT=scripts/restart.sh
### started_at: 2026-12-04T11:31:54Z
/usr/bin/python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://127.0.0.1:8084"
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
### exit_code: 0
+7
View File
@@ -0,0 +1,7 @@
### smoke
### command: make PYTHON=/usr/bin/python3 test
### started_at: 2026-12-04T11:31:05Z
/usr/bin/python3 tests/smoke.py --base-url "http://127.0.0.1:8084"
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
### exit_code: 0
@@ -0,0 +1,7 @@
### smoke_after_experiment
### command: make PYTHON=/usr/bin/python3 test
### started_at: 2026-12-04T11:34:58Z
/usr/bin/python3 tests/smoke.py --base-url "http://127.0.0.1:8084"
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
### exit_code: 0
+23
View File
@@ -0,0 +1,23 @@
### smoke_python39
### command: ./scripts/py39-tests.sh
### started_at: 2026-12-04T11:31:05Z
Python 3.9.6
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
PASS health
PASS registration/auth
PASS registration validation
PASS chats/membership
PASS messages
PASS attachments and message links
PASS instances (2 observed)
PASS idempotency replay/conflict/scope/validation
PASS concurrent idempotency across 2 replicas
PASS pagination
PASS concurrent registration
PASS concurrent messages
PASS logout
PASS: lab4 student black-box suite, 149 checks
PASS: Python 3.9 compilation, public smoke and student black-box suite
### exit_code: 0
+2
View File
@@ -0,0 +1,2 @@
finished_at: 2026-12-04T11:34:58Z
15 ### exit_code: 0
+16
View File
@@ -0,0 +1,16 @@
### track2
### command: make PYTHON=/usr/bin/python3 test-consistency
### started_at: 2026-12-04T11:34:02Z
/usr/bin/python3 scripts/track2.py --base-url "http://127.0.0.1:8084"
== reproducible base set ==
== cost of a clean traversal ==
== inject faults on both sides ==
== dry run: detection without mutation ==
== apply: only provable stale items ==
== rerun before grace expiry: no new deletions ==
== grace expiry: the fresh orphan is now old enough ==
== API and used attachments after reconciliation ==
{"result": "PASS", "assertions": 68, "failed": 0, "cost_ms_median": 11}
PASS: track 2 reconciler experiment
### exit_code: 0
+176
View File
@@ -0,0 +1,176 @@
{
"no_container_name_in_compose": true,
"third_party_images_pinned_by_digest": true,
"third_party_images": [
"postgres:16.4-alpine3.20@sha256:5660c2cbfea50c7a9127d17dc4e48543eedd3d7a41a595a2dfa572471e37e64c",
"valkey/valkey:8.0.2-alpine@sha256:752ba000a58bc8925d11ee863a39b5225617cd2cb3dbc9ec8ac65268b65ebb6d",
"chrislusf/seaweedfs:3.98@sha256:2f7de737bd35c5e2cf93944e8aa66de802a135f068ea285d8d290d0206347d22",
"haproxy:3.0-alpine@sha256:457d1c0dcbf2dfc0e0358723c07df4410d30e7de42bec036b383cfede4a5dbe3"
],
"api_replica_count": 2,
"api_container_ids_distinct": true,
"api_hostnames_distinct": true,
"api_image_ids": [
"sha256:9f46ec2a6cf007f77202d3ae97afc0f710ee3cd191b8c620405f397b193932ce"
],
"s3_image_id": "sha256:0513e5e469b80438fcb8961e4b7c422e782251114d4930ac17cd9fbe508ad5ba",
"git_revision": "02fc97b78aff9a1890bd2bade40f6cd8654e2000",
"api_ports": {
"mtusi-lab4-melnikov-api-1": "",
"mtusi-lab4-melnikov-api-2": ""
},
"s3_published_ports": "",
"lb_ports": "8080/tcp -> 127.0.0.1:8084",
"api_has_no_published_ports": true,
"s3_has_no_published_ports": true,
"lb_published_loopback_only": true,
"limits": {
"api": [
{
"name": "mtusi-lab4-melnikov-api-1",
"nano_cpus": 500000000,
"memory_bytes": 402653184,
"readonly_rootfs": true,
"cap_drop": [
"ALL"
],
"security_opt": [
"no-new-privileges:true"
],
"user": "10001:10001",
"mounts": [],
"volume_mounts": []
},
{
"name": "mtusi-lab4-melnikov-api-2",
"nano_cpus": 500000000,
"memory_bytes": 402653184,
"readonly_rootfs": true,
"cap_drop": [
"ALL"
],
"security_opt": [
"no-new-privileges:true"
],
"user": "10001:10001",
"mounts": [],
"volume_mounts": []
}
],
"postgres": [
{
"name": "mtusi-lab4-melnikov-postgres-1",
"nano_cpus": 500000000,
"memory_bytes": 402653184,
"readonly_rootfs": false,
"cap_drop": null,
"security_opt": [
"no-new-privileges:true"
],
"user": "",
"mounts": [
"mtusi-lab4-melnikov-pgdata"
],
"volume_mounts": [
"mtusi-lab4-melnikov-pgdata"
]
}
],
"valkey": [
{
"name": "mtusi-lab4-melnikov-valkey-1",
"nano_cpus": 100000000,
"memory_bytes": 100663296,
"readonly_rootfs": false,
"cap_drop": null,
"security_opt": [
"no-new-privileges:true"
],
"user": "",
"mounts": [
"mtusi-lab4-melnikov-valkeydata"
],
"volume_mounts": [
"mtusi-lab4-melnikov-valkeydata"
]
}
],
"s3": [
{
"name": "mtusi-lab4-melnikov-s3-1",
"nano_cpus": 400000000,
"memory_bytes": 402653184,
"readonly_rootfs": false,
"cap_drop": null,
"security_opt": [
"no-new-privileges:true"
],
"user": "",
"mounts": [
"mtusi-lab4-melnikov-s3data",
"/Users/ivanmuller/Desktop/oh_my_life/highload/lab4/infra/seaweedfs-s3.json"
],
"volume_mounts": [
"mtusi-lab4-melnikov-s3data"
]
}
],
"lb": [
{
"name": "mtusi-lab4-melnikov-lb-1",
"nano_cpus": 200000000,
"memory_bytes": 67108864,
"readonly_rootfs": true,
"cap_drop": [
"ALL"
],
"security_opt": [
"no-new-privileges:true"
],
"user": "haproxy",
"mounts": [
"/Users/ivanmuller/Desktop/oh_my_life/highload/lab4/infra/haproxy.cfg"
],
"volume_mounts": []
}
]
},
"all_services_have_cpu_and_memory_limits": true,
"api_non_root": true,
"api_read_only_rootfs": true,
"api_cap_drop_all": true,
"api_no_new_privileges": true,
"api_has_no_state_volume": true,
"s3_has_data_volume": true,
"named_volumes": [
"mtusi-lab4-melnikov-pgdata",
"mtusi-lab4-melnikov-s3data",
"mtusi-lab4-melnikov-valkeydata"
],
"volumes_have_prefix": true,
"api_s3_access_key_present": true,
"api_s3_secret_present": true,
"api_credentials_differ_from_admin": true,
"api_has_no_admin_credentials": true,
"api_credentials_can_list_own_bucket": true,
"api_credentials_denied_other_bucket": true,
"bucket_bootstrap_second_run_exit": 0,
"bucket_bootstrap_second_run_created_false": true,
"bucket_bootstrap_second_run_verified": true,
"anonymous_object_get_status": " HTTP/1.1 403 Forbidden\nwget: server returned error: HTTP/1.1 403 Forbidden\n",
"anonymous_object_get_denied": true,
"anonymous_list_status": " HTTP/1.1 403 Forbidden\nwget: server returned error: HTTP/1.1 403 Forbidden\n",
"anonymous_list_denied": true,
"attachment_download_still_authorized": true,
"observed_instances": [
"3e58d4b42901",
"40fdc2d47091"
],
"session_crosses_replicas": true,
"session_instances_are_api_hostnames": true,
"health_ready_via_lb": true,
"result": "PASS",
"failed": [],
"checked_at": "2026-12-04T11:31:54.054715Z",
"base_url": "http://127.0.0.1:8084"
}
+15
View File
@@ -0,0 +1,15 @@
lab4 container checks at 2026-12-04T11:31:54.054715Z
result: PASS
git revision: 02fc97b78aff9a1890bd2bade40f6cd8654e2000
API replicas: 2 (40fdc2d47091, 3e58d4b42901)
API image ids: sha256:9f46ec2a6cf007f77202d3ae97afc0f710ee3cd191b8c620405f397b193932ce
S3 image id: sha256:0513e5e469b80438fcb8961e4b7c422e782251114d4930ac17cd9fbe508ad5ba
API ports published: {'mtusi-lab4-melnikov-api-1': '', 'mtusi-lab4-melnikov-api-2': ''}
S3 ports published: ''
LB ports: 8080/tcp -> 127.0.0.1:8084
volumes: mtusi-lab4-melnikov-pgdata, mtusi-lab4-melnikov-s3data, mtusi-lab4-melnikov-valkeydata
limits: {"api":[{"name":"mtusi-lab4-melnikov-api-1","nano_cpus":500000000,"memory_bytes":402653184,"readonly_rootfs":true,"cap_drop":["ALL"],"security_opt":["no-new-privileges:true"],"user":"10001:10001","mounts":[],"volume_mounts":[]},{"name":"mtusi-lab4-melnikov-api-2","nano_cpus":500000000,"memory_bytes":402653184,"readonly_rootfs":true,"cap_drop":["ALL"],"security_opt":["no-new-privileges:true"],"user":"10001:10001","mounts":[],"volume_mounts":[]}],"postgres":[{"name":"mtusi-lab4-melnikov-postgres-1","nano_cpus":500000000,"memory_bytes":402653184,"readonly_rootfs":false,"cap_drop":null,"security_opt":["no-new-privileges:true"],"user":"","mounts":["mtusi-lab4-melnikov-pgdata"],"volume_mounts":["mtusi-lab4-melnikov-pgdata"]}],"valkey":[{"name":"mtusi-lab4-melnikov-valkey-1","nano_cpus":100000000,"memory_bytes":100663296,"readonly_rootfs":false,"cap_drop":null,"security_opt":["no-new-privileges:true"],"user":"","mounts":["mtusi-lab4-melnikov-valkeydata"],"volume_mounts":["mtusi-lab4-melnikov-valkeydata"]}],"s3":[{"name":"mtusi-lab4-melnikov-s3-1","nano_cpus":400000000,"memory_bytes":402653184,"readonly_rootfs":false,"cap_drop":null,"security_opt":["no-new-privileges:true"],"user":"","mounts":["mtusi-lab4-melnikov-s3data","/Users/ivanmuller/Desktop/oh_my_life/highload/lab4/infra/seaweedfs-s3.json"],"volume_mounts":["mtusi-lab4-melnikov-s3data"]}],"lb":[{"name":"mtusi-lab4-melnikov-lb-1","nano_cpus":200000000,"memory_bytes":67108864,"readonly_rootfs":true,"cap_drop":["ALL"],"security_opt":["no-new-privileges:true"],"user":"haproxy","mounts":["/Users/ivanmuller/Desktop/oh_my_life/highload/lab4/infra/haproxy.cfg"],"volume_mounts":[]}]}
observed session instances: 3e58d4b42901, 40fdc2d47091
anonymous object GET denied: True
anonymous bucket list denied: True
bootstrap second run: exit=0 created_false=True
+130
View File
@@ -0,0 +1,130 @@
{
"samples": [
{
"sampled_at": "2026-12-04T11:34:56.471876Z",
"monotonic_seconds": 5.414499,
"api": {
"255348db8382": {
"process": {
"hwm_bytes": 53067776,
"rss_bytes": 53067776
},
"cgroup": {
"current_bytes": 54026240,
"peak_bytes": 68681728
}
},
"291762b7fcf7": {
"process": {
"hwm_bytes": 53338112,
"rss_bytes": 43819008
},
"cgroup": {
"current_bytes": 54124544,
"peak_bytes": 59400192
}
}
}
},
{
"sampled_at": "2026-12-04T11:34:57.052474Z",
"monotonic_seconds": 5.995101,
"api": {
"255348db8382": {
"process": {
"hwm_bytes": 53592064,
"rss_bytes": 47435776
},
"cgroup": {
"current_bytes": 58441728,
"peak_bytes": 68681728
}
},
"291762b7fcf7": {
"process": {
"hwm_bytes": 53338112,
"rss_bytes": 43819008
},
"cgroup": {
"current_bytes": 44965888,
"peak_bytes": 59400192
}
}
}
},
{
"sampled_at": "2026-12-04T11:34:57.479157Z",
"monotonic_seconds": 6.421775,
"api": {
"255348db8382": {
"process": {
"hwm_bytes": 53592064,
"rss_bytes": 49532928
},
"cgroup": {
"current_bytes": 50536448,
"peak_bytes": 68681728
}
},
"291762b7fcf7": {
"process": {
"hwm_bytes": 53338112,
"rss_bytes": 43819008
},
"cgroup": {
"current_bytes": 34533376,
"peak_bytes": 59400192
}
}
}
},
{
"sampled_at": "2026-12-04T11:34:57.897775Z",
"monotonic_seconds": 6.840419,
"api": {
"255348db8382": {
"process": {
"hwm_bytes": 53592064,
"rss_bytes": 49532928
},
"cgroup": {
"current_bytes": 40091648,
"peak_bytes": 68681728
}
},
"291762b7fcf7": {
"process": {
"hwm_bytes": 53338112,
"rss_bytes": 43819008
},
"cgroup": {
"current_bytes": 34598912,
"peak_bytes": 59400192
}
}
}
}
],
"baseline": {
"255348db8382": {
"process": {
"hwm_bytes": 32636928,
"rss_bytes": 32636928
},
"cgroup": {
"current_bytes": 23568384,
"peak_bytes": 25030656
}
},
"291762b7fcf7": {
"process": {
"hwm_bytes": 32636928,
"rss_bytes": 32636928
},
"cgroup": {
"current_bytes": 23572480,
"peak_bytes": 25120768
}
}
}
}
+352
View File
@@ -0,0 +1,352 @@
{
"experiment": "lab4 concurrent upload: peak API process RSS",
"generated_at": "2026-12-04T11:34:58.139639Z",
"git_revision": "02fc97b78aff9a1890bd2bade40f6cd8654e2000",
"api_image_id": "sha256:9f46ec2a6cf007f77202d3ae97afc0f710ee3cd191b8c620405f397b193932ce",
"base_url": "http://127.0.0.1:8084",
"started_at": "2026-12-04T11:34:56.471905Z",
"finished_at": "2026-12-04T11:34:57.559844Z",
"wall_seconds": 1.088,
"configured_concurrency": 12,
"observed_peak_concurrency": 12,
"successful_uploads": 12,
"failed_uploads": 0,
"api_instances": [
"255348db8382",
"291762b7fcf7"
],
"uploads_per_instance": {
"291762b7fcf7": {
"uploads": 6,
"bytes": 23765280
},
"255348db8382": {
"uploads": 6,
"bytes": 29467820
}
},
"profile": {
"files": 12,
"total_bytes": 53233100,
"min_bytes": 2101403,
"max_bytes": 10406995,
"max_pixels": 3467200,
"small": {
"count": 6,
"width": 1000,
"height": 700
},
"medium": {
"count": 4,
"width": 1500,
"height": 1100
},
"near_max_bytes": {
"count": 2,
"width": 1600,
"height": 2167
}
},
"limits": {
"api_memory_limit_bytes": 402653184,
"GOMEMLIMIT": "300MiB",
"UPLOAD_DECODE_CONCURRENCY": "1",
"S3_PUT_CONCURRENCY": "1",
"MAX_UPLOAD_BYTES": "10485760",
"MAX_IMAGE_PIXELS": "40000000"
},
"memory_metrics": {
"process_rss_source": "/proc/1/status VmRSS inside each API container, sampled by docker exec",
"process_hwm_source": "/proc/1/status VmHWM inside each API container",
"cgroup_source": "/sys/fs/cgroup/memory.current and memory.peak (whole container cgroup)",
"sample_interval_seconds": 0.2,
"samples_taken": 4,
"first_sample_at": "2026-12-04T11:34:56.471876Z",
"last_sample_at": "2026-12-04T11:34:57.897775Z",
"max_sample_gap_seconds": 0.581,
"per_instance": {
"255348db8382": {
"samples": 4,
"baseline_rss_bytes": 32636928,
"baseline_hwm_bytes": 32636928,
"peak_sampled_rss_bytes": 53067776,
"peak_sampled_rss_delta_bytes": 20430848,
"final_hwm_bytes": 53592064,
"peak_cgroup_current_bytes": 58441728,
"peak_cgroup_memory_peak_bytes": 68681728,
"api_memory_limit_bytes": 402653184
},
"291762b7fcf7": {
"samples": 4,
"baseline_rss_bytes": 32636928,
"baseline_hwm_bytes": 32636928,
"peak_sampled_rss_bytes": 43819008,
"peak_sampled_rss_delta_bytes": 11182080,
"final_hwm_bytes": 53338112,
"peak_cgroup_current_bytes": 54124544,
"peak_cgroup_memory_peak_bytes": 59400192,
"api_memory_limit_bytes": 402653184
}
}
},
"uploads": [
{
"index": 0,
"profile": "small",
"filename": "load-00.png",
"width": 1000,
"height": 700,
"pixels": 700000,
"bytes": 2101403,
"sha256": "79cbb720f624ede46a0cfa457295be4d59a01c89d5655eee9fec1c20709a9192",
"started_at": "2026-12-04T11:34:56.513575Z",
"finished_at": "2026-12-04T11:34:56.747488Z",
"started_monotonic": 5.4561885,
"finished_monotonic": 5.690098791,
"duration_ms": 233.91,
"status": 201,
"instance_id": "291762b7fcf7",
"attachment_id": "762a1f02-1f07-4491-afc6-d91048e6fe6f",
"server_sha256": "79cbb720f624ede46a0cfa457295be4d59a01c89d5655eee9fec1c20709a9192",
"server_size_bytes": 2101403,
"server_status": "ready"
},
{
"index": 1,
"profile": "small",
"filename": "load-01.png",
"width": 1000,
"height": 700,
"pixels": 700000,
"bytes": 2101403,
"sha256": "56ff9e9df4640588383f1f3697e63fc47786486287765a6ec046692e792b3248",
"started_at": "2026-12-04T11:34:56.517488Z",
"finished_at": "2026-12-04T11:34:56.764786Z",
"started_monotonic": 5.46010075,
"finished_monotonic": 5.707392291,
"duration_ms": 247.292,
"status": 201,
"instance_id": "255348db8382",
"attachment_id": "f787c937-07a5-4cf5-a04e-35dc05b5f9c3",
"server_sha256": "56ff9e9df4640588383f1f3697e63fc47786486287765a6ec046692e792b3248",
"server_size_bytes": 2101403,
"server_status": "ready"
},
{
"index": 2,
"profile": "small",
"filename": "load-02.png",
"width": 1000,
"height": 700,
"pixels": 700000,
"bytes": 2101403,
"sha256": "12e55905a3f9f4472750c35137b43d948a9d3e3091e7f3587b58869f4333885d",
"started_at": "2026-12-04T11:34:56.513663Z",
"finished_at": "2026-12-04T11:34:56.725265Z",
"started_monotonic": 5.456276791,
"finished_monotonic": 5.667872375,
"duration_ms": 211.596,
"status": 201,
"instance_id": "291762b7fcf7",
"attachment_id": "2e6dee21-0133-4726-b999-86d0a9c10207",
"server_sha256": "12e55905a3f9f4472750c35137b43d948a9d3e3091e7f3587b58869f4333885d",
"server_size_bytes": 2101403,
"server_status": "ready"
},
{
"index": 3,
"profile": "small",
"filename": "load-03.png",
"width": 1000,
"height": 700,
"pixels": 700000,
"bytes": 2101403,
"sha256": "f2b7dbdb007111bf6370726e98deeee88ad950678c131ecb33fbf1b81309ad27",
"started_at": "2026-12-04T11:34:56.517612Z",
"finished_at": "2026-12-04T11:34:56.840134Z",
"started_monotonic": 5.460225791,
"finished_monotonic": 5.782738166,
"duration_ms": 322.512,
"status": 201,
"instance_id": "291762b7fcf7",
"attachment_id": "51640d6a-e814-4878-b3f8-07688703ce6e",
"server_sha256": "f2b7dbdb007111bf6370726e98deeee88ad950678c131ecb33fbf1b81309ad27",
"server_size_bytes": 2101403,
"server_status": "ready"
},
{
"index": 4,
"profile": "small",
"filename": "load-04.png",
"width": 1000,
"height": 700,
"pixels": 700000,
"bytes": 2101403,
"sha256": "b1b3c5c004f2ad33a50a772c341754be7788e3a54182767b4593c3f07b384148",
"started_at": "2026-12-04T11:34:56.513982Z",
"finished_at": "2026-12-04T11:34:56.747263Z",
"started_monotonic": 5.456595958,
"finished_monotonic": 5.689869958,
"duration_ms": 233.274,
"status": 201,
"instance_id": "255348db8382",
"attachment_id": "58516465-016c-471c-8576-b2c1dd033aa2",
"server_sha256": "b1b3c5c004f2ad33a50a772c341754be7788e3a54182767b4593c3f07b384148",
"server_size_bytes": 2101403,
"server_status": "ready"
},
{
"index": 5,
"profile": "small",
"filename": "load-05.png",
"width": 1000,
"height": 700,
"pixels": 700000,
"bytes": 2101403,
"sha256": "4d4db37b1cd3144cb7c136ef6c9e210c556e298401cb0f7c87068732bdee1d24",
"started_at": "2026-12-04T11:34:56.513749Z",
"finished_at": "2026-12-04T11:34:56.937698Z",
"started_monotonic": 5.456362,
"finished_monotonic": 5.880304958,
"duration_ms": 423.943,
"status": 201,
"instance_id": "291762b7fcf7",
"attachment_id": "9f79c942-22bf-4e10-8991-9fa187d2e25e",
"server_sha256": "4d4db37b1cd3144cb7c136ef6c9e210c556e298401cb0f7c87068732bdee1d24",
"server_size_bytes": 2101403,
"server_status": "ready"
},
{
"index": 6,
"profile": "medium",
"filename": "load-06.png",
"width": 1500,
"height": 1100,
"pixels": 1650000,
"bytes": 4952673,
"sha256": "1b36c050abe85d2a1d183943ae0c8198080810c3e320defcbb54cc3ee9892de5",
"started_at": "2026-12-04T11:34:56.516942Z",
"finished_at": "2026-12-04T11:34:56.960201Z",
"started_monotonic": 5.459537875,
"finished_monotonic": 5.902805916,
"duration_ms": 443.268,
"status": 201,
"instance_id": "255348db8382",
"attachment_id": "13d3d726-9294-4567-a870-e259af693f6b",
"server_sha256": "1b36c050abe85d2a1d183943ae0c8198080810c3e320defcbb54cc3ee9892de5",
"server_size_bytes": 4952673,
"server_status": "ready"
},
{
"index": 7,
"profile": "medium",
"filename": "load-07.png",
"width": 1500,
"height": 1100,
"pixels": 1650000,
"bytes": 4952673,
"sha256": "fd35bb6ecf8257aab2696d8a7ee0dece9350d3e46371661a742a0e057cdd75df",
"started_at": "2026-12-04T11:34:56.513844Z",
"finished_at": "2026-12-04T11:34:57.358162Z",
"started_monotonic": 5.456458041,
"finished_monotonic": 6.300764791,
"duration_ms": 844.307,
"status": 201,
"instance_id": "255348db8382",
"attachment_id": "a3c063c4-9b5c-4799-8847-e5b79ec3ae55",
"server_sha256": "fd35bb6ecf8257aab2696d8a7ee0dece9350d3e46371661a742a0e057cdd75df",
"server_size_bytes": 4952673,
"server_status": "ready"
},
{
"index": 8,
"profile": "medium",
"filename": "load-08.png",
"width": 1500,
"height": 1100,
"pixels": 1650000,
"bytes": 4952673,
"sha256": "fae30be4f37e121952050d82c5952de321591845750a290321edb6fe094ba57f",
"started_at": "2026-12-04T11:34:56.513909Z",
"finished_at": "2026-12-04T11:34:57.058113Z",
"started_monotonic": 5.456522375,
"finished_monotonic": 6.000715375,
"duration_ms": 544.193,
"status": 201,
"instance_id": "291762b7fcf7",
"attachment_id": "6dfa35b8-ddf6-434a-9c0d-e26fa29cb7af",
"server_sha256": "fae30be4f37e121952050d82c5952de321591845750a290321edb6fe094ba57f",
"server_size_bytes": 4952673,
"server_status": "ready"
},
{
"index": 9,
"profile": "medium",
"filename": "load-09.png",
"width": 1500,
"height": 1100,
"pixels": 1650000,
"bytes": 4952673,
"sha256": "317bd264909822fb98f661324e660bcc8b2fb63fb4c4aca5d0f930799234b975",
"started_at": "2026-12-04T11:34:56.517888Z",
"finished_at": "2026-12-04T11:34:57.148109Z",
"started_monotonic": 5.460501166,
"finished_monotonic": 6.090713666,
"duration_ms": 630.212,
"status": 201,
"instance_id": "255348db8382",
"attachment_id": "14b024b4-b84b-42f3-a4c6-e9ee9382dec5",
"server_sha256": "317bd264909822fb98f661324e660bcc8b2fb63fb4c4aca5d0f930799234b975",
"server_size_bytes": 4952673,
"server_status": "ready"
},
{
"index": 10,
"profile": "near-max-bytes",
"filename": "load-10.png",
"width": 1600,
"height": 2167,
"pixels": 3467200,
"bytes": 10406995,
"sha256": "323d49ae0c9e62d43be080d4c521db8ad08e59975d162c730bf544e5bf1bc673",
"started_at": "2026-12-04T11:34:56.517768Z",
"finished_at": "2026-12-04T11:34:57.559424Z",
"started_monotonic": 5.46038125,
"finished_monotonic": 6.502022583,
"duration_ms": 1041.641,
"status": 201,
"instance_id": "255348db8382",
"attachment_id": "6ccc80b0-bd6d-42bf-a2ec-52d238854786",
"server_sha256": "323d49ae0c9e62d43be080d4c521db8ad08e59975d162c730bf544e5bf1bc673",
"server_size_bytes": 10406995,
"server_status": "ready"
},
{
"index": 11,
"profile": "near-max-bytes",
"filename": "load-11.png",
"width": 1600,
"height": 2167,
"pixels": 3467200,
"bytes": 10406995,
"sha256": "4996193b58d3cfa1a9be97f0326a1747022984d7ff5cc04d257dad92e7bb3c09",
"started_at": "2026-12-04T11:34:56.513426Z",
"finished_at": "2026-12-04T11:34:57.353921Z",
"started_monotonic": 5.456032791,
"finished_monotonic": 6.296522583,
"duration_ms": 840.49,
"status": 201,
"instance_id": "291762b7fcf7",
"attachment_id": "75ee3ed2-7f9a-4520-90b3-275394864f86",
"server_sha256": "4996193b58d3cfa1a9be97f0326a1747022984d7ff5cc04d257dad92e7bb3c09",
"server_size_bytes": 10406995,
"server_status": "ready"
}
],
"result": "PASS",
"limitations": [
"One local stand: RSS includes Go runtime and handler state, not a production profile.",
"The sampler uses docker exec every 200 ms; a shorter allocation spike between samples is bounded by VmHWM, which is also reported.",
"cgroup memory.current includes page cache and is not process RSS."
]
}
+254
View File
@@ -0,0 +1,254 @@
[
{
"index": 0,
"profile": "small",
"filename": "load-00.png",
"width": 1000,
"height": 700,
"pixels": 700000,
"bytes": 2101403,
"sha256": "79cbb720f624ede46a0cfa457295be4d59a01c89d5655eee9fec1c20709a9192",
"started_at": "2026-12-04T11:34:56.513575Z",
"finished_at": "2026-12-04T11:34:56.747488Z",
"started_monotonic": 5.4561885,
"finished_monotonic": 5.690098791,
"duration_ms": 233.91,
"status": 201,
"instance_id": "291762b7fcf7",
"attachment_id": "762a1f02-1f07-4491-afc6-d91048e6fe6f",
"server_sha256": "79cbb720f624ede46a0cfa457295be4d59a01c89d5655eee9fec1c20709a9192",
"server_size_bytes": 2101403,
"server_status": "ready"
},
{
"index": 1,
"profile": "small",
"filename": "load-01.png",
"width": 1000,
"height": 700,
"pixels": 700000,
"bytes": 2101403,
"sha256": "56ff9e9df4640588383f1f3697e63fc47786486287765a6ec046692e792b3248",
"started_at": "2026-12-04T11:34:56.517488Z",
"finished_at": "2026-12-04T11:34:56.764786Z",
"started_monotonic": 5.46010075,
"finished_monotonic": 5.707392291,
"duration_ms": 247.292,
"status": 201,
"instance_id": "255348db8382",
"attachment_id": "f787c937-07a5-4cf5-a04e-35dc05b5f9c3",
"server_sha256": "56ff9e9df4640588383f1f3697e63fc47786486287765a6ec046692e792b3248",
"server_size_bytes": 2101403,
"server_status": "ready"
},
{
"index": 2,
"profile": "small",
"filename": "load-02.png",
"width": 1000,
"height": 700,
"pixels": 700000,
"bytes": 2101403,
"sha256": "12e55905a3f9f4472750c35137b43d948a9d3e3091e7f3587b58869f4333885d",
"started_at": "2026-12-04T11:34:56.513663Z",
"finished_at": "2026-12-04T11:34:56.725265Z",
"started_monotonic": 5.456276791,
"finished_monotonic": 5.667872375,
"duration_ms": 211.596,
"status": 201,
"instance_id": "291762b7fcf7",
"attachment_id": "2e6dee21-0133-4726-b999-86d0a9c10207",
"server_sha256": "12e55905a3f9f4472750c35137b43d948a9d3e3091e7f3587b58869f4333885d",
"server_size_bytes": 2101403,
"server_status": "ready"
},
{
"index": 3,
"profile": "small",
"filename": "load-03.png",
"width": 1000,
"height": 700,
"pixels": 700000,
"bytes": 2101403,
"sha256": "f2b7dbdb007111bf6370726e98deeee88ad950678c131ecb33fbf1b81309ad27",
"started_at": "2026-12-04T11:34:56.517612Z",
"finished_at": "2026-12-04T11:34:56.840134Z",
"started_monotonic": 5.460225791,
"finished_monotonic": 5.782738166,
"duration_ms": 322.512,
"status": 201,
"instance_id": "291762b7fcf7",
"attachment_id": "51640d6a-e814-4878-b3f8-07688703ce6e",
"server_sha256": "f2b7dbdb007111bf6370726e98deeee88ad950678c131ecb33fbf1b81309ad27",
"server_size_bytes": 2101403,
"server_status": "ready"
},
{
"index": 4,
"profile": "small",
"filename": "load-04.png",
"width": 1000,
"height": 700,
"pixels": 700000,
"bytes": 2101403,
"sha256": "b1b3c5c004f2ad33a50a772c341754be7788e3a54182767b4593c3f07b384148",
"started_at": "2026-12-04T11:34:56.513982Z",
"finished_at": "2026-12-04T11:34:56.747263Z",
"started_monotonic": 5.456595958,
"finished_monotonic": 5.689869958,
"duration_ms": 233.274,
"status": 201,
"instance_id": "255348db8382",
"attachment_id": "58516465-016c-471c-8576-b2c1dd033aa2",
"server_sha256": "b1b3c5c004f2ad33a50a772c341754be7788e3a54182767b4593c3f07b384148",
"server_size_bytes": 2101403,
"server_status": "ready"
},
{
"index": 5,
"profile": "small",
"filename": "load-05.png",
"width": 1000,
"height": 700,
"pixels": 700000,
"bytes": 2101403,
"sha256": "4d4db37b1cd3144cb7c136ef6c9e210c556e298401cb0f7c87068732bdee1d24",
"started_at": "2026-12-04T11:34:56.513749Z",
"finished_at": "2026-12-04T11:34:56.937698Z",
"started_monotonic": 5.456362,
"finished_monotonic": 5.880304958,
"duration_ms": 423.943,
"status": 201,
"instance_id": "291762b7fcf7",
"attachment_id": "9f79c942-22bf-4e10-8991-9fa187d2e25e",
"server_sha256": "4d4db37b1cd3144cb7c136ef6c9e210c556e298401cb0f7c87068732bdee1d24",
"server_size_bytes": 2101403,
"server_status": "ready"
},
{
"index": 6,
"profile": "medium",
"filename": "load-06.png",
"width": 1500,
"height": 1100,
"pixels": 1650000,
"bytes": 4952673,
"sha256": "1b36c050abe85d2a1d183943ae0c8198080810c3e320defcbb54cc3ee9892de5",
"started_at": "2026-12-04T11:34:56.516942Z",
"finished_at": "2026-12-04T11:34:56.960201Z",
"started_monotonic": 5.459537875,
"finished_monotonic": 5.902805916,
"duration_ms": 443.268,
"status": 201,
"instance_id": "255348db8382",
"attachment_id": "13d3d726-9294-4567-a870-e259af693f6b",
"server_sha256": "1b36c050abe85d2a1d183943ae0c8198080810c3e320defcbb54cc3ee9892de5",
"server_size_bytes": 4952673,
"server_status": "ready"
},
{
"index": 7,
"profile": "medium",
"filename": "load-07.png",
"width": 1500,
"height": 1100,
"pixels": 1650000,
"bytes": 4952673,
"sha256": "fd35bb6ecf8257aab2696d8a7ee0dece9350d3e46371661a742a0e057cdd75df",
"started_at": "2026-12-04T11:34:56.513844Z",
"finished_at": "2026-12-04T11:34:57.358162Z",
"started_monotonic": 5.456458041,
"finished_monotonic": 6.300764791,
"duration_ms": 844.307,
"status": 201,
"instance_id": "255348db8382",
"attachment_id": "a3c063c4-9b5c-4799-8847-e5b79ec3ae55",
"server_sha256": "fd35bb6ecf8257aab2696d8a7ee0dece9350d3e46371661a742a0e057cdd75df",
"server_size_bytes": 4952673,
"server_status": "ready"
},
{
"index": 8,
"profile": "medium",
"filename": "load-08.png",
"width": 1500,
"height": 1100,
"pixels": 1650000,
"bytes": 4952673,
"sha256": "fae30be4f37e121952050d82c5952de321591845750a290321edb6fe094ba57f",
"started_at": "2026-12-04T11:34:56.513909Z",
"finished_at": "2026-12-04T11:34:57.058113Z",
"started_monotonic": 5.456522375,
"finished_monotonic": 6.000715375,
"duration_ms": 544.193,
"status": 201,
"instance_id": "291762b7fcf7",
"attachment_id": "6dfa35b8-ddf6-434a-9c0d-e26fa29cb7af",
"server_sha256": "fae30be4f37e121952050d82c5952de321591845750a290321edb6fe094ba57f",
"server_size_bytes": 4952673,
"server_status": "ready"
},
{
"index": 9,
"profile": "medium",
"filename": "load-09.png",
"width": 1500,
"height": 1100,
"pixels": 1650000,
"bytes": 4952673,
"sha256": "317bd264909822fb98f661324e660bcc8b2fb63fb4c4aca5d0f930799234b975",
"started_at": "2026-12-04T11:34:56.517888Z",
"finished_at": "2026-12-04T11:34:57.148109Z",
"started_monotonic": 5.460501166,
"finished_monotonic": 6.090713666,
"duration_ms": 630.212,
"status": 201,
"instance_id": "255348db8382",
"attachment_id": "14b024b4-b84b-42f3-a4c6-e9ee9382dec5",
"server_sha256": "317bd264909822fb98f661324e660bcc8b2fb63fb4c4aca5d0f930799234b975",
"server_size_bytes": 4952673,
"server_status": "ready"
},
{
"index": 10,
"profile": "near-max-bytes",
"filename": "load-10.png",
"width": 1600,
"height": 2167,
"pixels": 3467200,
"bytes": 10406995,
"sha256": "323d49ae0c9e62d43be080d4c521db8ad08e59975d162c730bf544e5bf1bc673",
"started_at": "2026-12-04T11:34:56.517768Z",
"finished_at": "2026-12-04T11:34:57.559424Z",
"started_monotonic": 5.46038125,
"finished_monotonic": 6.502022583,
"duration_ms": 1041.641,
"status": 201,
"instance_id": "255348db8382",
"attachment_id": "6ccc80b0-bd6d-42bf-a2ec-52d238854786",
"server_sha256": "323d49ae0c9e62d43be080d4c521db8ad08e59975d162c730bf544e5bf1bc673",
"server_size_bytes": 10406995,
"server_status": "ready"
},
{
"index": 11,
"profile": "near-max-bytes",
"filename": "load-11.png",
"width": 1600,
"height": 2167,
"pixels": 3467200,
"bytes": 10406995,
"sha256": "4996193b58d3cfa1a9be97f0326a1747022984d7ff5cc04d257dad92e7bb3c09",
"started_at": "2026-12-04T11:34:56.513426Z",
"finished_at": "2026-12-04T11:34:57.353921Z",
"started_monotonic": 5.456032791,
"finished_monotonic": 6.296522583,
"duration_ms": 840.49,
"status": 201,
"instance_id": "291762b7fcf7",
"attachment_id": "75ee3ed2-7f9a-4520-90b3-275394864f86",
"server_sha256": "4996193b58d3cfa1a9be97f0326a1747022984d7ff5cc04d257dad92e7bb3c09",
"server_size_bytes": 10406995,
"server_status": "ready"
}
]
+34
View File
@@ -0,0 +1,34 @@
{
"checked_at": "2026-12-04T11:34:02.559955Z",
"base_url": "http://127.0.0.1:8084",
"git_revision": "02fc97b78aff9a1890bd2bade40f6cd8654e2000",
"attachment_id": "df90e020-bdc2-4828-96ba-951547f457c3",
"content_bytes": 4202343,
"sha256": "0011ea7e58f4f61aa50c4e0e9ab3336b9b6e8cea425367d3169e17dc54840cbb",
"instances_before": [
"255348db8382",
"291762b7fcf7"
],
"upload_instance": "255348db8382",
"stopped_container_id": "255348db8382142b6cd8f6c4dc583ee850150633a1278db3d97a37d09191409f",
"stopped_container_state": "exited",
"stop_started_at": "2026-12-04T11:33:57.944242Z",
"stop_finished_at": "2026-12-04T11:34:01.092562Z",
"download_instance": "291762b7fcf7",
"download_instances_seen": [
"291762b7fcf7"
],
"download_sha256": "0011ea7e58f4f61aa50c4e0e9ab3336b9b6e8cea425367d3169e17dc54840cbb",
"restored_at": "2026-12-04T11:34:01.329817Z",
"restored_instances": [
"255348db8382",
"291762b7fcf7"
],
"result": "PASS",
"notes": [
"The upload response X-Instance-Id was mapped to the exact Docker hostname.",
"scripts/stop-one.sh left that container exited; the hook is not a restart helper.",
"The download was served by the remaining replica and matched the original bytes.",
"The stopped replica was restored explicitly with docker compose up -d api; Compose may recreate it with a new hostname."
]
}
+156
View File
@@ -0,0 +1,156 @@
{
"checked_at": "2026-12-04T11:33:37.147875Z",
"base_url": "http://127.0.0.1:8084",
"git_revision": "02fc97b78aff9a1890bd2bade40f6cd8654e2000",
"restart_started_at": "2026-12-04T11:32:44.284987Z",
"restart_finished_at": "2026-12-04T11:33:36.807525Z",
"hook_exit_code": 0,
"hook_stdout": "restart.sh: restarting shared postgres, valkey and the private S3 store (volumes kept)\nrestart.sh: restarting every api replica\nrestart.sh: all lab4 services restarted; volumes preserved\n",
"hook_stderr": " Container mtusi-lab4-melnikov-s3-1 Restarting\n Container mtusi-lab4-melnikov-valkey-1 Restarting\n Container mtusi-lab4-melnikov-postgres-1 Restarting\n Container mtusi-lab4-melnikov-postgres-1 Started\n Container mtusi-lab4-melnikov-valkey-1 Started\n Container mtusi-lab4-melnikov-s3-1 Started\n Container mtusi-lab4-melnikov-api-1 Restarting\n Container mtusi-lab4-melnikov-api-2 Restarting\n Container mtusi-lab4-melnikov-api-1 Started\n Container mtusi-lab4-melnikov-api-2 Started\n",
"before": {
"services": {
"api": [
{
"container_id": "40fdc2d47091042ef2a186443aafe92ae0d829d808cfb892a6373c53c73e0af6",
"name": "mtusi-lab4-melnikov-api-1",
"started_at": "2026-12-04T11:32:38.333962367Z",
"restart_count": 0,
"image_id": "sha256:9f46ec2a6cf007f77202d3ae97afc0f710ee3cd191b8c620405f397b193932ce",
"volumes": []
},
{
"container_id": "3e58d4b42901e9c633d957c6085301d633c58becf2e1d96b5e75b9737456be95",
"name": "mtusi-lab4-melnikov-api-2",
"started_at": "2026-12-04T11:32:38.338890061Z",
"restart_count": 0,
"image_id": "sha256:9f46ec2a6cf007f77202d3ae97afc0f710ee3cd191b8c620405f397b193932ce",
"volumes": []
}
],
"postgres": [
{
"container_id": "1cceda94e49acfff850e313b74f7203cd24c9566f2b61d7e4b10c760223d360b",
"name": "mtusi-lab4-melnikov-postgres-1",
"started_at": "2026-12-04T11:31:54.592809804Z",
"restart_count": 0,
"image_id": "sha256:a710cb729803496a1c36335b6b519899fc3b0f332bbe16387a4d35c3e69cb5b1",
"volumes": [
"mtusi-lab4-melnikov-pgdata"
]
}
],
"valkey": [
{
"container_id": "a3b1965c62a6a49b21c662b182c21cbfe49c1b4b25c7be5e488e28dcb77b01cd",
"name": "mtusi-lab4-melnikov-valkey-1",
"started_at": "2026-12-04T11:31:54.591085293Z",
"restart_count": 0,
"image_id": "sha256:7b2072cf1b86d58fee110f4da8dc3b0e1444b22ab64f58d7f61e822e0761f866",
"volumes": [
"mtusi-lab4-melnikov-valkeydata"
]
}
],
"s3": [
{
"container_id": "c7aae8aa24a7b27d5ffed4bac70b0a5029c0028b2b94923771adf5987b3b1a05",
"name": "mtusi-lab4-melnikov-s3-1",
"started_at": "2026-12-04T11:32:14.574394829Z",
"restart_count": 0,
"image_id": "sha256:0513e5e469b80438fcb8961e4b7c422e782251114d4930ac17cd9fbe508ad5ba",
"volumes": [
"mtusi-lab4-melnikov-s3data"
]
}
]
},
"volumes": [
"mtusi-lab4-melnikov-pgdata",
"mtusi-lab4-melnikov-s3data",
"mtusi-lab4-melnikov-valkeydata"
],
"captured_at": "2026-12-04T11:32:43.945264Z"
},
"after": {
"services": {
"api": [
{
"container_id": "40fdc2d47091042ef2a186443aafe92ae0d829d808cfb892a6373c53c73e0af6",
"name": "mtusi-lab4-melnikov-api-1",
"started_at": "2026-12-04T11:33:31.552252477Z",
"restart_count": 0,
"image_id": "sha256:9f46ec2a6cf007f77202d3ae97afc0f710ee3cd191b8c620405f397b193932ce",
"volumes": []
},
{
"container_id": "3e58d4b42901e9c633d957c6085301d633c58becf2e1d96b5e75b9737456be95",
"name": "mtusi-lab4-melnikov-api-2",
"started_at": "2026-12-04T11:33:31.549676338Z",
"restart_count": 0,
"image_id": "sha256:9f46ec2a6cf007f77202d3ae97afc0f710ee3cd191b8c620405f397b193932ce",
"volumes": []
}
],
"postgres": [
{
"container_id": "1cceda94e49acfff850e313b74f7203cd24c9566f2b61d7e4b10c760223d360b",
"name": "mtusi-lab4-melnikov-postgres-1",
"started_at": "2026-12-04T11:32:44.569865075Z",
"restart_count": 0,
"image_id": "sha256:a710cb729803496a1c36335b6b519899fc3b0f332bbe16387a4d35c3e69cb5b1",
"volumes": [
"mtusi-lab4-melnikov-pgdata"
]
}
],
"valkey": [
{
"container_id": "a3b1965c62a6a49b21c662b182c21cbfe49c1b4b25c7be5e488e28dcb77b01cd",
"name": "mtusi-lab4-melnikov-valkey-1",
"started_at": "2026-12-04T11:32:44.623100334Z",
"restart_count": 0,
"image_id": "sha256:7b2072cf1b86d58fee110f4da8dc3b0e1444b22ab64f58d7f61e822e0761f866",
"volumes": [
"mtusi-lab4-melnikov-valkeydata"
]
}
],
"s3": [
{
"container_id": "c7aae8aa24a7b27d5ffed4bac70b0a5029c0028b2b94923771adf5987b3b1a05",
"name": "mtusi-lab4-melnikov-s3-1",
"started_at": "2026-12-04T11:33:04.576327372Z",
"restart_count": 0,
"image_id": "sha256:0513e5e469b80438fcb8961e4b7c422e782251114d4930ac17cd9fbe508ad5ba",
"volumes": [
"mtusi-lab4-melnikov-s3data"
]
}
]
},
"volumes": [
"mtusi-lab4-melnikov-pgdata",
"mtusi-lab4-melnikov-s3data",
"mtusi-lab4-melnikov-valkeydata"
],
"captured_at": "2026-12-04T11:33:36.809395Z"
},
"checks": {
"same_container_ids": true,
"started_at_changed": true,
"all_services_restarted": true,
"volumes_unchanged": true,
"same_token_still_valid": true,
"message_survived": true,
"attachment_metadata_survived": true,
"attachment_bytes_survived": true
},
"result": "PASS",
"failed": [],
"notes": [
"Container ids are unchanged: compose restarted real containers, it did not recreate them.",
"StartedAt changed for every API/PostgreSQL/Valkey/S3 container.",
"Named volumes were preserved; no volume was removed or re-created.",
"The public make test-persistence additionally checks the contract with the old token."
]
}
File diff suppressed because it is too large Load Diff
+65
View File
@@ -0,0 +1,65 @@
{
"generated_at": "2026-12-04T11:34:50.517904841Z",
"mode": "apply",
"bucket": "messenger-attachments",
"prefix": "attachments/",
"grace_seconds": 20,
"database": {
"rows": 328,
"ready": 328,
"pending": 0
},
"object_store": {
"objects": 327
},
"findings": {
"ok": 326,
"orphan_objects": [
{
"object_key": "attachments/orphan-fresh-ad3995ebaf9b4b3dbbfb2830a082347e",
"age_seconds": 22
}
],
"protected_recent_objects": null,
"missing_objects": [
{
"id": "a98d0387-d643-48fd-89a9-c7bc232229a5",
"object_key": "attachments/a98d0387-d643-48fd-89a9-c7bc232229a5",
"status": "ready",
"age_seconds": 46
},
{
"id": "fd7a4709-63a6-45ed-b464-a9ceef082efc",
"object_key": "attachments/fd7a4709-63a6-45ed-b464-a9ceef082efc",
"status": "ready",
"age_seconds": 47
}
],
"stale_pending": null,
"protected_pending": null
},
"actions": {
"deleted_objects": [
"attachments/orphan-fresh-ad3995ebaf9b4b3dbbfb2830a082347e"
],
"deleted_pending_rows": null,
"skipped": null,
"unresolved_missing": [
"a98d0387-d643-48fd-89a9-c7bc232229a5",
"fd7a4709-63a6-45ed-b464-a9ceef082efc"
],
"errors": null
},
"timing": {
"db_scan_ms": 4,
"s3_list_ms": 6,
"total_ms": 12,
"db_rows": 328,
"s3_objects": 327
},
"_invocation": {
"command": "/Users/ivanmuller/Desktop/oh_my_life/highload/lab4/scripts/compose.sh --env-file .env run --rm --no-deps -T --entrypoint /app/reconciler api -prefix attachments/ -grace 20s -apply",
"started_at": "2026-12-04T11:34:50.114671Z",
"finished_at": "2026-12-04T11:34:50.554448Z"
}
}
+96
View File
@@ -0,0 +1,96 @@
{
"generated_at": "2026-12-04T11:34:29.669483539Z",
"mode": "apply",
"bucket": "messenger-attachments",
"prefix": "attachments/",
"grace_seconds": 20,
"database": {
"rows": 330,
"ready": 327,
"pending": 3
},
"object_store": {
"objects": 329
},
"findings": {
"ok": 325,
"orphan_objects": [
{
"object_key": "attachments/orphan-stale-579892ade5e640889f0fa061f08ed330",
"age_seconds": 23
}
],
"protected_recent_objects": [
{
"object_key": "attachments/orphan-fresh-ad3995ebaf9b4b3dbbfb2830a082347e",
"age_seconds": 1
}
],
"missing_objects": [
{
"id": "a98d0387-d643-48fd-89a9-c7bc232229a5",
"object_key": "attachments/a98d0387-d643-48fd-89a9-c7bc232229a5",
"status": "ready",
"age_seconds": 25
},
{
"id": "fd7a4709-63a6-45ed-b464-a9ceef082efc",
"object_key": "attachments/fd7a4709-63a6-45ed-b464-a9ceef082efc",
"status": "ready",
"age_seconds": 26
}
],
"stale_pending": [
{
"id": "a8f2fcc3-f2c4-4d95-9bd4-a2f55398016a",
"object_key": "attachments/a8f2fcc3-f2c4-4d95-9bd4-a2f55398016a",
"status": "pending",
"age_seconds": 83,
"object_present": true
},
{
"id": "beb1acd6-4fe9-4306-a157-061dcab78deb",
"object_key": "attachments/beb1acd6-4fe9-4306-a157-061dcab78deb",
"status": "pending",
"age_seconds": 82
}
],
"protected_pending": [
{
"id": "5cec0cdd-80f2-415c-9a0e-01e28703878a",
"object_key": "attachments/5cec0cdd-80f2-415c-9a0e-01e28703878a",
"status": "pending",
"age_seconds": 1,
"object_present": true
}
]
},
"actions": {
"deleted_objects": [
"attachments/orphan-stale-579892ade5e640889f0fa061f08ed330",
"attachments/a8f2fcc3-f2c4-4d95-9bd4-a2f55398016a"
],
"deleted_pending_rows": [
"a8f2fcc3-f2c4-4d95-9bd4-a2f55398016a",
"beb1acd6-4fe9-4306-a157-061dcab78deb"
],
"skipped": null,
"unresolved_missing": [
"a98d0387-d643-48fd-89a9-c7bc232229a5",
"fd7a4709-63a6-45ed-b464-a9ceef082efc"
],
"errors": null
},
"timing": {
"db_scan_ms": 4,
"s3_list_ms": 6,
"total_ms": 14,
"db_rows": 330,
"s3_objects": 329
},
"_invocation": {
"command": "/Users/ivanmuller/Desktop/oh_my_life/highload/lab4/scripts/compose.sh --env-file .env run --rm --no-deps -T --entrypoint /app/reconciler api -prefix attachments/ -grace 20s -apply",
"started_at": "2026-12-04T11:34:29.492131Z",
"finished_at": "2026-12-04T11:34:29.703663Z"
}
}
+42
View File
@@ -0,0 +1,42 @@
{
"generated_at": "2026-12-04T11:34:05.466600056Z",
"mode": "apply",
"bucket": "messenger-attachments",
"prefix": "attachments/",
"grace_seconds": 20,
"database": {
"rows": 321,
"ready": 321,
"pending": 0
},
"object_store": {
"objects": 321
},
"findings": {
"ok": 321,
"orphan_objects": null,
"protected_recent_objects": null,
"missing_objects": null,
"stale_pending": null,
"protected_pending": null
},
"actions": {
"deleted_objects": null,
"deleted_pending_rows": null,
"skipped": null,
"unresolved_missing": null,
"errors": null
},
"timing": {
"db_scan_ms": 4,
"s3_list_ms": 6,
"total_ms": 10,
"db_rows": 321,
"s3_objects": 321
},
"_invocation": {
"command": "/Users/ivanmuller/Desktop/oh_my_life/highload/lab4/scripts/compose.sh --env-file .env run --rm --no-deps -T --entrypoint /app/reconciler api -prefix attachments/ -grace 20s -apply",
"started_at": "2026-12-04T11:34:05.269839Z",
"finished_at": "2026-12-04T11:34:05.491926Z"
}
}
+42
View File
@@ -0,0 +1,42 @@
{
"generated_at": "2026-12-04T11:34:05.681178412Z",
"mode": "dry-run",
"bucket": "messenger-attachments",
"prefix": "attachments/",
"grace_seconds": 3600,
"database": {
"rows": 321,
"ready": 321,
"pending": 0
},
"object_store": {
"objects": 321
},
"findings": {
"ok": 321,
"orphan_objects": null,
"protected_recent_objects": null,
"missing_objects": null,
"stale_pending": null,
"protected_pending": null
},
"actions": {
"deleted_objects": null,
"deleted_pending_rows": null,
"skipped": null,
"unresolved_missing": null,
"errors": null
},
"timing": {
"db_scan_ms": 4,
"s3_list_ms": 6,
"total_ms": 11,
"db_rows": 321,
"s3_objects": 321
},
"_invocation": {
"command": "/Users/ivanmuller/Desktop/oh_my_life/highload/lab4/scripts/compose.sh --env-file .env run --rm --no-deps -T --entrypoint /app/reconciler api -prefix attachments/ -grace 3600s",
"started_at": "2026-12-04T11:34:05.492582Z",
"finished_at": "2026-12-04T11:34:05.709664Z"
}
}
+42
View File
@@ -0,0 +1,42 @@
{
"generated_at": "2026-12-04T11:34:05.901179461Z",
"mode": "dry-run",
"bucket": "messenger-attachments",
"prefix": "attachments/",
"grace_seconds": 3600,
"database": {
"rows": 321,
"ready": 321,
"pending": 0
},
"object_store": {
"objects": 321
},
"findings": {
"ok": 321,
"orphan_objects": null,
"protected_recent_objects": null,
"missing_objects": null,
"stale_pending": null,
"protected_pending": null
},
"actions": {
"deleted_objects": null,
"deleted_pending_rows": null,
"skipped": null,
"unresolved_missing": null,
"errors": null
},
"timing": {
"db_scan_ms": 4,
"s3_list_ms": 6,
"total_ms": 11,
"db_rows": 321,
"s3_objects": 321
},
"_invocation": {
"command": "/Users/ivanmuller/Desktop/oh_my_life/highload/lab4/scripts/compose.sh --env-file .env run --rm --no-deps -T --entrypoint /app/reconciler api -prefix attachments/ -grace 3600s",
"started_at": "2026-12-04T11:34:05.710133Z",
"finished_at": "2026-12-04T11:34:05.926249Z"
}
}
+42
View File
@@ -0,0 +1,42 @@
{
"generated_at": "2026-12-04T11:34:06.113391388Z",
"mode": "dry-run",
"bucket": "messenger-attachments",
"prefix": "attachments/",
"grace_seconds": 3600,
"database": {
"rows": 321,
"ready": 321,
"pending": 0
},
"object_store": {
"objects": 321
},
"findings": {
"ok": 321,
"orphan_objects": null,
"protected_recent_objects": null,
"missing_objects": null,
"stale_pending": null,
"protected_pending": null
},
"actions": {
"deleted_objects": null,
"deleted_pending_rows": null,
"skipped": null,
"unresolved_missing": null,
"errors": null
},
"timing": {
"db_scan_ms": 4,
"s3_list_ms": 6,
"total_ms": 10,
"db_rows": 321,
"s3_objects": 321
},
"_invocation": {
"command": "/Users/ivanmuller/Desktop/oh_my_life/highload/lab4/scripts/compose.sh --env-file .env run --rm --no-deps -T --entrypoint /app/reconciler api -prefix attachments/ -grace 3600s",
"started_at": "2026-12-04T11:34:05.926741Z",
"finished_at": "2026-12-04T11:34:06.144141Z"
}
}
+95
View File
@@ -0,0 +1,95 @@
{
"generated_at": "2026-12-04T11:34:28.92702416Z",
"mode": "dry-run",
"bucket": "messenger-attachments",
"prefix": "attachments/",
"grace_seconds": 20,
"database": {
"rows": 324,
"ready": 321,
"pending": 3
},
"object_store": {
"objects": 323
},
"findings": {
"ok": 319,
"orphan_objects": [
{
"object_key": "attachments/orphan-stale-579892ade5e640889f0fa061f08ed330",
"age_seconds": 22
}
],
"protected_recent_objects": [
{
"object_key": "attachments/orphan-fresh-ad3995ebaf9b4b3dbbfb2830a082347e",
"age_seconds": 0
}
],
"missing_objects": [
{
"id": "a98d0387-d643-48fd-89a9-c7bc232229a5",
"object_key": "attachments/a98d0387-d643-48fd-89a9-c7bc232229a5",
"status": "ready",
"age_seconds": 24
},
{
"id": "fd7a4709-63a6-45ed-b464-a9ceef082efc",
"object_key": "attachments/fd7a4709-63a6-45ed-b464-a9ceef082efc",
"status": "ready",
"age_seconds": 25
}
],
"stale_pending": [
{
"id": "a8f2fcc3-f2c4-4d95-9bd4-a2f55398016a",
"object_key": "attachments/a8f2fcc3-f2c4-4d95-9bd4-a2f55398016a",
"status": "pending",
"age_seconds": 82,
"object_present": true
},
{
"id": "beb1acd6-4fe9-4306-a157-061dcab78deb",
"object_key": "attachments/beb1acd6-4fe9-4306-a157-061dcab78deb",
"status": "pending",
"age_seconds": 82
}
],
"protected_pending": [
{
"id": "5cec0cdd-80f2-415c-9a0e-01e28703878a",
"object_key": "attachments/5cec0cdd-80f2-415c-9a0e-01e28703878a",
"status": "pending",
"age_seconds": 0,
"object_present": true
}
]
},
"actions": {
"planned_deletes": [
"attachments/orphan-stale-579892ade5e640889f0fa061f08ed330",
"attachments/a8f2fcc3-f2c4-4d95-9bd4-a2f55398016a",
"attachments/beb1acd6-4fe9-4306-a157-061dcab78deb"
],
"deleted_objects": null,
"deleted_pending_rows": null,
"skipped": null,
"unresolved_missing": [
"a98d0387-d643-48fd-89a9-c7bc232229a5",
"fd7a4709-63a6-45ed-b464-a9ceef082efc"
],
"errors": null
},
"timing": {
"db_scan_ms": 5,
"s3_list_ms": 8,
"total_ms": 13,
"db_rows": 324,
"s3_objects": 323
},
"_invocation": {
"command": "/Users/ivanmuller/Desktop/oh_my_life/highload/lab4/scripts/compose.sh --env-file .env run --rm --no-deps -T --entrypoint /app/reconciler api -prefix attachments/ -grace 20s",
"started_at": "2026-12-04T11:34:28.740278Z",
"finished_at": "2026-12-04T11:34:28.967591Z"
}
}
+63
View File
@@ -0,0 +1,63 @@
{
"generated_at": "2026-12-04T11:34:30.769482909Z",
"mode": "apply",
"bucket": "messenger-attachments",
"prefix": "attachments/",
"grace_seconds": 20,
"database": {
"rows": 328,
"ready": 328,
"pending": 0
},
"object_store": {
"objects": 327
},
"findings": {
"ok": 326,
"orphan_objects": null,
"protected_recent_objects": [
{
"object_key": "attachments/orphan-fresh-ad3995ebaf9b4b3dbbfb2830a082347e",
"age_seconds": 2
}
],
"missing_objects": [
{
"id": "a98d0387-d643-48fd-89a9-c7bc232229a5",
"object_key": "attachments/a98d0387-d643-48fd-89a9-c7bc232229a5",
"status": "ready",
"age_seconds": 26
},
{
"id": "fd7a4709-63a6-45ed-b464-a9ceef082efc",
"object_key": "attachments/fd7a4709-63a6-45ed-b464-a9ceef082efc",
"status": "ready",
"age_seconds": 27
}
],
"stale_pending": null,
"protected_pending": null
},
"actions": {
"deleted_objects": null,
"deleted_pending_rows": null,
"skipped": null,
"unresolved_missing": [
"a98d0387-d643-48fd-89a9-c7bc232229a5",
"fd7a4709-63a6-45ed-b464-a9ceef082efc"
],
"errors": null
},
"timing": {
"db_scan_ms": 4,
"s3_list_ms": 6,
"total_ms": 10,
"db_rows": 328,
"s3_objects": 327
},
"_invocation": {
"command": "/Users/ivanmuller/Desktop/oh_my_life/highload/lab4/scripts/compose.sh --env-file .env run --rm --no-deps -T --entrypoint /app/reconciler api -prefix attachments/ -grace 20s -apply",
"started_at": "2026-12-04T11:34:30.590518Z",
"finished_at": "2026-12-04T11:34:30.798386Z"
}
}
+406
View File
@@ -0,0 +1,406 @@
{
"track": "Track 2: consistency of two stores",
"hypothesis": "A grace-protected, re-checked reconciler removes only stale orphan objects and stale upload intents, and never deletes ready/used/fresh attachments or invents missing bytes.",
"generated_at": "2026-12-04T11:34:50.994535Z",
"git_revision": "02fc97b78aff9a1890bd2bade40f6cd8654e2000",
"api_image_id": "sha256:9f46ec2a6cf007f77202d3ae97afc0f710ee3cd191b8c620405f397b193932ce",
"database_rows_base": 300,
"object_store_objects_base": 300,
"message_attachment_links_base": 160,
"base_profile": {
"attachments": 300,
"linked_attachments": 150,
"unlinked_ready_attachments": 150,
"bytes_per_attachment": 111817,
"total_attachment_bytes": 33545100,
"image_profile": "tests/fixtures/sample.png 320x200, identical synthetic bytes"
},
"grace_seconds": 20,
"cost_runs": [
{
"run": 1,
"generated_at": "2026-12-04T11:34:05.681178412Z",
"db_scan_ms": 4,
"s3_list_ms": 6,
"total_ms": 11,
"db_rows": 321,
"s3_objects": 321
},
{
"run": 2,
"generated_at": "2026-12-04T11:34:05.901179461Z",
"db_scan_ms": 4,
"s3_list_ms": 6,
"total_ms": 11,
"db_rows": 321,
"s3_objects": 321
},
{
"run": 3,
"generated_at": "2026-12-04T11:34:06.113391388Z",
"db_scan_ms": 4,
"s3_list_ms": 6,
"total_ms": 10,
"db_rows": 321,
"s3_objects": 321
}
],
"cost_summary": {
"runs": 3,
"db_scan_ms_median": 4,
"s3_list_ms_median": 6,
"total_ms_median": 11,
"note": "traversal cost is O(rows + objects); timings are wall-clock milliseconds reported by the reconciler process on this local stand"
},
"injected": {
"stale_orphan_object": "attachments/orphan-stale-579892ade5e640889f0fa061f08ed330",
"stale_pending_with_object": {
"id": "a8f2fcc3-f2c4-4d95-9bd4-a2f55398016a",
"object_key": "attachments/a8f2fcc3-f2c4-4d95-9bd4-a2f55398016a"
},
"stale_pending_without_object": {
"id": "beb1acd6-4fe9-4306-a157-061dcab78deb",
"object_key": "attachments/beb1acd6-4fe9-4306-a157-061dcab78deb"
},
"missing_used_attachment": {
"id": "fd7a4709-63a6-45ed-b464-a9ceef082efc",
"object_key": "attachments/fd7a4709-63a6-45ed-b464-a9ceef082efc"
},
"missing_unused_attachment": {
"id": "a98d0387-d643-48fd-89a9-c7bc232229a5",
"object_key": "attachments/a98d0387-d643-48fd-89a9-c7bc232229a5"
},
"fresh_orphan_object": "attachments/orphan-fresh-ad3995ebaf9b4b3dbbfb2830a082347e",
"active_upload_intent": {
"id": "5cec0cdd-80f2-415c-9a0e-01e28703878a",
"object_key": "attachments/5cec0cdd-80f2-415c-9a0e-01e28703878a"
}
},
"dry_run": {
"orphan_objects": [
"attachments/orphan-stale-579892ade5e640889f0fa061f08ed330"
],
"protected_recent_objects": [
"attachments/orphan-fresh-ad3995ebaf9b4b3dbbfb2830a082347e"
],
"stale_pending": [
"a8f2fcc3-f2c4-4d95-9bd4-a2f55398016a",
"beb1acd6-4fe9-4306-a157-061dcab78deb"
],
"protected_pending": [
"5cec0cdd-80f2-415c-9a0e-01e28703878a"
],
"missing_objects": [
"a98d0387-d643-48fd-89a9-c7bc232229a5",
"fd7a4709-63a6-45ed-b464-a9ceef082efc"
],
"deleted_objects": [],
"deleted_pending_rows": []
},
"apply": {
"deleted_objects": [
"attachments/a8f2fcc3-f2c4-4d95-9bd4-a2f55398016a",
"attachments/orphan-stale-579892ade5e640889f0fa061f08ed330"
],
"deleted_pending_rows": [
"a8f2fcc3-f2c4-4d95-9bd4-a2f55398016a",
"beb1acd6-4fe9-4306-a157-061dcab78deb"
],
"unresolved_missing": [
"a98d0387-d643-48fd-89a9-c7bc232229a5",
"fd7a4709-63a6-45ed-b464-a9ceef082efc"
]
},
"rerun": {
"deleted_objects": [],
"deleted_pending_rows": []
},
"after_grace": {
"deleted_objects": [
"attachments/orphan-fresh-ad3995ebaf9b4b3dbbfb2830a082347e"
],
"deleted_pending_rows": []
},
"assertions": [
{
"check": "base attachment set is incomplete",
"passed": true
},
{
"check": "message attachments were reordered",
"passed": true
},
{
"check": "base rows/objects were not exactly the 300 uploads",
"passed": true
},
{
"check": "cost run did not scan the full base set",
"passed": true
},
{
"check": "missing objects were not removed from S3",
"passed": true
},
{
"check": "stale orphan object not detected",
"passed": true
},
{
"check": "fresh orphan object not protected",
"passed": true
},
{
"check": "stale upload intents not detected",
"passed": true
},
{
"check": "fresh upload intent not protected",
"passed": true
},
{
"check": "missing objects not detected",
"passed": true
},
{
"check": "dry run deleted objects",
"passed": true
},
{
"check": "dry run deleted rows",
"passed": true
},
{
"check": "dry run mutated either store",
"passed": true
},
{
"check": "dry run removed an object",
"passed": true
},
{
"check": "dry run removed an active upload object",
"passed": true
},
{
"check": "concurrent upload during reconcile did not finish ready",
"passed": true
},
{
"check": "stale orphan object was not removed",
"passed": true
},
{
"check": "stale pending rows were not removed",
"passed": true
},
{
"check": "stale pending object was not removed",
"passed": true
},
{
"check": "stale S3 objects survived apply",
"passed": true
},
{
"check": "stale pending rows survived apply",
"passed": true
},
{
"check": "fresh orphan object was deleted inside grace",
"passed": true
},
{
"check": "active upload, concurrent upload or active row was deleted",
"passed": true
},
{
"check": "missing objects were not left for manual recovery",
"passed": true
},
{
"check": "apply changed message attachment links",
"passed": true
},
{
"check": "active upload intent changed state unexpectedly",
"passed": true
},
{
"check": "protected upload cannot be attached after completion",
"passed": true
},
{
"check": "protected upload bytes changed",
"passed": true
},
{
"check": "rerun deleted objects",
"passed": true
},
{
"check": "rerun deleted rows",
"passed": true
},
{
"check": "fresh orphan lost protection on rerun",
"passed": true
},
{
"check": "fresh orphan removed on rerun",
"passed": true
},
{
"check": "aged orphan was not removed after grace",
"passed": true
},
{
"check": "aged orphan object still exists",
"passed": true
},
{
"check": "grace expiry deleted a metadata row",
"passed": true
},
{
"check": "completed protected attachment lost after grace expiry",
"passed": true
},
{
"check": "used message disappeared from history",
"passed": true
},
{
"check": "used message lost or reordered its attachment links",
"passed": true
},
{
"check": "used message disappeared from history",
"passed": true
},
{
"check": "used message lost or reordered its attachment links",
"passed": true
},
{
"check": "used message disappeared from history",
"passed": true
},
{
"check": "used message lost or reordered its attachment links",
"passed": true
},
{
"check": "used message disappeared from history",
"passed": true
},
{
"check": "used message lost or reordered its attachment links",
"passed": true
},
{
"check": "used message disappeared from history",
"passed": true
},
{
"check": "used message lost or reordered its attachment links",
"passed": true
},
{
"check": "used message disappeared from history",
"passed": true
},
{
"check": "used message lost or reordered its attachment links",
"passed": true
},
{
"check": "used message disappeared from history",
"passed": true
},
{
"check": "used message lost or reordered its attachment links",
"passed": true
},
{
"check": "used message disappeared from history",
"passed": true
},
{
"check": "used message lost or reordered its attachment links",
"passed": true
},
{
"check": "used message disappeared from history",
"passed": true
},
{
"check": "used message lost or reordered its attachment links",
"passed": true
},
{
"check": "used message disappeared from history",
"passed": true
},
{
"check": "used message lost or reordered its attachment links",
"passed": true
},
{
"check": "used message disappeared from history",
"passed": true
},
{
"check": "used message lost or reordered its attachment links",
"passed": true
},
{
"check": "used message disappeared from history",
"passed": true
},
{
"check": "used message lost or reordered its attachment links",
"passed": true
},
{
"check": "used message disappeared from history",
"passed": true
},
{
"check": "used message lost or reordered its attachment links",
"passed": true
},
{
"check": "used message disappeared from history",
"passed": true
},
{
"check": "used message lost or reordered its attachment links",
"passed": true
},
{
"check": "used message disappeared from history",
"passed": true
},
{
"check": "used message lost or reordered its attachment links",
"passed": true
},
{
"check": "used attachment bytes changed or disappeared",
"passed": true
},
{
"check": "new upload after reconciliation failed",
"passed": true
}
],
"assertions_failed": 0,
"result": "PASS",
"limitations": [
"The reconciler never deletes or fabricates a missing original: bytes cannot be restored automatically, so those rows are reported as unresolved for operator recovery.",
"A simulated in-flight upload row is used as the deterministic active state; real concurrent uploads are additionally exercised and must finish ready.",
"Cost is measured on this 2 vCPU / ~2 GiB Colima stand and does not extrapolate to production.",
"The S3 ListObjects scan is not a snapshot: concurrent uploads are protected by the grace period and by the immediate database re-check before each delete."
]
}
+30
View File
@@ -0,0 +1,30 @@
module mtusi.ru/messenger-lab4
go 1.25.1
require (
github.com/jackc/pgx/v5 v5.7.2
github.com/jackc/puddle/v2 v2.2.2
github.com/minio/minio-go/v7 v7.0.82
github.com/redis/go-redis/v9 v9.7.0
golang.org/x/crypto v0.31.0
)
require (
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-ini/ini v1.67.0 // indirect
github.com/goccy/go-json v0.10.3 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/klauspost/compress v1.17.11 // indirect
github.com/klauspost/cpuid/v2 v2.2.8 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
github.com/rs/xid v1.6.0 // indirect
golang.org/x/net v0.30.0 // indirect
golang.org/x/sync v0.10.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/text v0.21.0 // indirect
)
+62
View File
@@ -0,0 +1,62 @@
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.7.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI=
github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.8 h1:+StwCXwm9PdpiEkPyzBXIy+M9KUb4ODm0Zarf1kS5BM=
github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
github.com/minio/minio-go/v7 v7.0.82 h1:tWfICLhmp2aFPXL8Tli0XDTHj2VB/fNf0PC1f/i1gRo=
github.com/minio/minio-go/v7 v7.0.82/go.mod h1:84gmIilaX4zcvAWWzJ5Z1WI5axN+hAbM5w25xf8xvC0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E=
github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw=
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4=
golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+64
View File
@@ -0,0 +1,64 @@
# Lab3 public entrypoint. HAProxy discovers API replicas through Docker's
# embedded DNS and actively probes /health/ready. There is no sticky session:
# every request is balanced independently, and a backend that fails two
# consecutive probes is removed within roughly two probe intervals.
#
# The stats endpoint is bound to loopback inside the container only. It is not
# published and is used by the experiment scripts through `docker exec`.
global
log stdout format raw local0
maxconn 8192
stats socket /tmp/haproxy.sock mode 600 level admin
defaults
mode http
log global
option httplog
option dontlognull
# Per-request access logging is intentionally disabled: at thousands of
# requests per second it moves the LB bottleneck into stdout and hides the
# component under study. Errors are still logged.
option dontlog-normal
option redispatch
retries 2
timeout connect 1s
timeout client 15s
timeout server 15s
timeout http-request 5s
timeout http-keep-alive 5s
default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 1
frontend public
bind :8080
mode http
default_backend api
backend api
mode http
balance roundrobin
option httpchk GET /health/ready
http-check expect status 200
# One template slot per A record returned for the compose service name.
# Docker DNS adds/removes records on scale/stop; `hold valid 1s` keeps the
# backend list current instead of caching the first resolution.
server-template api 1-10 api:8080 check resolvers docker init-addr none
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold refused 1s
hold nx 1s
hold timeout 1s
hold obsolete 1s
frontend stats
bind 127.0.0.1:8404
mode http
stats enable
stats uri /stats
stats refresh 1s
stats show-legends
+286
View File
@@ -0,0 +1,286 @@
package api
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"strings"
"sync/atomic"
"time"
"mtusi.ru/messenger-lab4/internal/auth"
"mtusi.ru/messenger-lab4/internal/model"
"mtusi.ru/messenger-lab4/internal/objectstore"
"mtusi.ru/messenger-lab4/internal/session"
"mtusi.ru/messenger-lab4/internal/store"
)
const maxBodyBytes = 1 << 20 // far above the 4000-character message limit
type healthResponse struct {
Status string `json:"status"`
}
// identity is the authenticated principal derived only from the Bearer
// session. X-User-Id is not consulted anywhere in this package.
type identity struct {
user model.User
token string
}
// App is the HTTP layer. PostgreSQL is the source of truth for users, chats
// and messages; Valkey is the source of truth for sessions. App adds request
// validation, authentication and contract mapping.
type App struct {
store *store.Store
sessions *session.Store
objects *objectstore.Store
log *slog.Logger
ready atomic.Bool
maxBody int64
instanceID string
version string
startedAt time.Time
dummyHash string
maxUpload int64
maxPixels int64
tempDir string
decodeSem chan struct{}
putSem chan struct{}
createdMessages atomic.Uint64
replayedMessages atomic.Uint64
conflictMessages atomic.Uint64
}
// Options carries the upload limits and concurrency bound. Values are
// validated by config.Load before the application starts.
type Options struct {
MaxUploadBytes int64
MaxImagePixels int64
DecodeConcurrency int
PutConcurrency int
TempDir string
}
// New creates the HTTP application. The dummy Argon2id hash is generated once
// so login can spend the same work for an unknown username as for a known one.
func New(repository *store.Store, sessions *session.Store, objects *objectstore.Store, logger *slog.Logger, instanceID, version string, options Options) (*App, error) {
dummy, err := auth.Hash("dummy-password-never-used-for-login")
if err != nil {
return nil, err
}
if options.MaxUploadBytes <= 0 {
options.MaxUploadBytes = 10 * 1024 * 1024
}
if options.MaxImagePixels <= 0 {
options.MaxImagePixels = 40_000_000
}
if options.DecodeConcurrency <= 0 {
options.DecodeConcurrency = 1
}
if options.PutConcurrency <= 0 {
options.PutConcurrency = 1
}
app := &App{
store: repository,
sessions: sessions,
objects: objects,
log: logger,
maxBody: maxBodyBytes,
instanceID: instanceID,
version: version,
startedAt: time.Now(),
dummyHash: dummy,
maxUpload: options.MaxUploadBytes,
maxPixels: options.MaxImagePixels,
tempDir: options.TempDir,
decodeSem: make(chan struct{}, options.DecodeConcurrency),
putSem: make(chan struct{}, options.PutConcurrency),
}
app.ready.Store(true)
return app, nil
}
// SetReady flips readiness. The main process clears it as soon as SIGTERM is
// received and before http.Server.Shutdown stops accepting connections.
func (a *App) SetReady(ready bool) { a.ready.Store(ready) }
// Handler returns the fully instrumented handler.
func (a *App) Handler() http.Handler {
return a.withObservability(a)
}
// ServeHTTP routes the lab3 API. Method mismatches become 404 in the contract
// error shape because the public error enum has no method_not_allowed code.
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/health/live":
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.writeJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
case "/health/ready":
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.readiness(w, r)
case "/api/v1/users":
if r.Method != http.MethodPost {
a.notFound(w, r)
return
}
a.createUser(w, r)
case "/api/v1/auth/sessions":
if r.Method != http.MethodPost {
a.notFound(w, r)
return
}
a.createSession(w, r)
case "/api/v1/auth/sessions/current":
if r.Method != http.MethodDelete {
a.notFound(w, r)
return
}
a.withAuth(a.logout).ServeHTTP(w, r)
case "/api/v1/users/me":
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.withAuth(a.currentUser).ServeHTTP(w, r)
case "/api/v1/chats":
switch r.Method {
case http.MethodGet:
a.withAuth(a.listChats).ServeHTTP(w, r)
case http.MethodPost:
a.withAuth(a.createChat).ServeHTTP(w, r)
default:
a.notFound(w, r)
}
default:
if rest, ok := trimPathPrefix(r.URL.Path, "/api/v1/attachments/"); ok {
a.withAuth(func(w http.ResponseWriter, r *http.Request, actor identity) {
a.attachmentRoutes(w, r, rest, actor)
}).ServeHTTP(w, r)
return
}
if rest, ok := trimPathPrefix(r.URL.Path, "/api/v1/chats/"); ok {
// Authentication runs before resource resolution: an anonymous
// request must not learn whether a chat id exists.
a.withAuth(func(w http.ResponseWriter, r *http.Request, actor identity) {
a.chatRoutes(w, r, rest, actor)
}).ServeHTTP(w, r)
return
}
a.notFound(w, r)
}
}
func (a *App) chatRoutes(w http.ResponseWriter, r *http.Request, rest string, actor identity) {
parts := splitPath(rest)
if len(parts) == 1 {
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.getChat(w, r, parts[0], actor)
return
}
if len(parts) == 2 && parts[1] == "attachments" {
if r.Method != http.MethodPost {
a.notFound(w, r)
return
}
a.createAttachment(w, r, parts[0], actor)
return
}
if len(parts) == 2 && parts[1] == "messages" {
switch r.Method {
case http.MethodGet:
a.listMessages(w, r, parts[0], actor)
case http.MethodPost:
a.createMessage(w, r, parts[0], actor)
default:
a.notFound(w, r)
}
return
}
a.notFound(w, r)
}
// withAuth resolves the Bearer session before the wrapped handler runs.
func (a *App) withAuth(next func(http.ResponseWriter, *http.Request, identity)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
actor, problem := a.authenticate(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
next(w, r, actor)
}
}
// readiness reports whether the mandatory synchronous path can be served.
// Both PostgreSQL and Valkey are critical: without PostgreSQL the API cannot
// answer, and without Valkey it cannot authenticate a single protected call.
func (a *App) readiness(w http.ResponseWriter, r *http.Request) {
if !a.ready.Load() {
a.writeError(w, r, statusUnavailable)
return
}
dbCtx, dbCancel := context.WithTimeout(r.Context(), 900*time.Millisecond)
dbErr := a.store.Ping(dbCtx)
dbCancel()
if dbErr != nil {
a.log.Warn("readiness probe failed", "request_id", requestIDFromContext(r.Context()), "dependency", "postgres", "error", dbErr)
a.writeError(w, r, statusUnavailable)
return
}
cacheCtx, cacheCancel := context.WithTimeout(r.Context(), 900*time.Millisecond)
cacheErr := a.sessions.Ping(cacheCtx)
cacheCancel()
if cacheErr != nil {
a.log.Warn("readiness probe failed", "request_id", requestIDFromContext(r.Context()), "dependency", "valkey", "error", cacheErr)
a.writeError(w, r, statusUnavailable)
return
}
a.writeJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
}
// writeJSON encodes a success response. X-Request-Id is set by middleware
// before the handler runs, so even a marshal-time 500 keeps the header.
func (a *App) writeJSON(w http.ResponseWriter, r *http.Request, status int, value any) {
data, err := json.Marshal(value)
if err != nil {
a.log.Error("response encoding failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if _, err := w.Write(data); err != nil {
a.log.Debug("response write failed", "request_id", requestIDFromContext(r.Context()), "error", err)
}
}
func trimPathPrefix(value, prefix string) (string, bool) {
if !strings.HasPrefix(value, prefix) || len(value) == len(prefix) {
return "", false
}
return value[len(prefix):], true
}
func splitPath(value string) []string {
parts := strings.Split(value, "/")
for _, part := range parts {
if part == "" {
return nil
}
}
return parts
}
+458
View File
@@ -0,0 +1,458 @@
package api
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
_ "image/jpeg" // register the JPEG decoder used by image.DecodeConfig/Decode
_ "image/png" // register the PNG decoder used by image.DecodeConfig/Decode
"io"
"mime"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"syscall"
"time"
"unicode"
"unicode/utf8"
"mtusi.ru/messenger-lab4/internal/model"
"mtusi.ru/messenger-lab4/internal/objectstore"
"mtusi.ru/messenger-lab4/internal/store"
"mtusi.ru/messenger-lab4/internal/uuid"
)
const (
objectPrefix = "attachments/"
decodeWaitTimeout = 30 * time.Second
putWaitTimeout = 10 * time.Second
maxFilenameCodePoints = 255
imagePNG = "image/png"
imageJPEG = "image/jpeg"
attachmentStateReady = "ready"
attachmentStatePending = "pending"
maxImageDimensionProduct = int64(40_000_000)
)
// attachmentRoutes handles /api/v1/attachments/{id} and .../content. The
// caller has already been authenticated by withAuth.
func (a *App) attachmentRoutes(w http.ResponseWriter, r *http.Request, rest string, actor identity) {
parts := splitPath(rest)
if len(parts) == 1 {
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.getAttachment(w, r, parts[0], actor)
return
}
if len(parts) == 2 && parts[1] == "content" {
if r.Method != http.MethodGet {
a.notFound(w, r)
return
}
a.downloadAttachment(w, r, parts[0], actor)
return
}
a.notFound(w, r)
}
// createAttachment performs a synchronous binary upload. The body is streamed
// to a bounded temporary file while its SHA-256 is computed; the image is
// validated before any S3 or database write. Only a validated image can create
// a pending row, so an invalid request never leaves an accounted object behind.
func (a *App) createAttachment(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
filename, problem := uploadFilename(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
declared, problem := uploadMediaType(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
if err != nil {
a.log.Error("attachment membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
if errors.Is(err, store.ErrUnavailable) {
a.writeError(w, r, statusUnavailable)
return
}
a.writeError(w, r, statusInternal)
return
}
if !member {
a.writeError(w, r, statusNotFound)
return
}
if r.ContentLength > a.maxUpload {
a.writeError(w, r, statusPayloadTooLarge)
return
}
temp, err := os.CreateTemp(a.tempDir, "lab4-upload-*")
if err != nil {
a.log.Error("could not create upload temp file", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
tempName := temp.Name()
defer func() {
_ = temp.Close()
_ = os.Remove(tempName)
}()
hasher := sha256.New()
body := http.MaxBytesReader(w, r.Body, a.maxUpload)
written, err := io.Copy(io.MultiWriter(temp, hasher), body)
if err != nil {
var tooLarge *http.MaxBytesError
switch {
case errors.As(err, &tooLarge):
a.writeError(w, r, statusPayloadTooLarge)
case errors.Is(err, syscall.ENOSPC):
a.log.Error("upload temp file is full", "request_id", requestIDFromContext(r.Context()))
a.writeError(w, r, statusUnavailable)
default:
a.writeError(w, r, invalidRequest("could not read the upload body"))
}
return
}
if written > a.maxUpload {
a.writeError(w, r, statusPayloadTooLarge)
return
}
if written == 0 {
a.writeError(w, r, unsupportedMediaType("the upload body is empty"))
return
}
detected, width, height, problem := a.validateImage(r.Context(), temp, declared)
if problem != nil {
a.writeError(w, r, problem)
return
}
sum := hex.EncodeToString(hasher.Sum(nil))
attachmentID := uuid.New()
objectKey := objectPrefix + attachmentID
createdAt := time.Now().UTC()
record := store.AttachmentRecord{
Attachment: model.Attachment{
ID: attachmentID,
ChatID: chatID,
OwnerID: actor.user.ID,
Filename: filename,
ContentType: detected,
SizeBytes: written,
SHA256: sum,
Status: attachmentStatePending,
Variants: []model.Variant{},
ErrorCode: nil,
CreatedAt: model.Time{Time: createdAt},
UpdatedAt: model.Time{Time: createdAt},
},
ObjectKey: objectKey,
}
if err := a.store.CreatePendingAttachment(r.Context(), record, createdAt); err != nil {
a.log.Error("could not record attachment intent", "request_id", requestIDFromContext(r.Context()), "error", err)
if errors.Is(err, store.ErrUnavailable) {
a.writeError(w, r, statusUnavailable)
return
}
a.writeError(w, r, statusInternal)
return
}
if _, err := temp.Seek(0, io.SeekStart); err != nil {
_ = a.store.DeleteAttachmentRow(context.Background(), attachmentID)
a.writeError(w, r, statusInternal)
return
}
// Bound the number of simultaneous object writes per API replica. A queued
// upload has already been streamed to a bounded temporary file and is not
// holding a decoded image, so waiting here does not add unbounded RAM.
select {
case a.putSem <- struct{}{}:
err = a.objects.Put(r.Context(), objectKey, temp, written, detected)
<-a.putSem
case <-time.After(putWaitTimeout):
a.compensatePending(attachmentID)
a.log.Warn("S3 upload queue timed out", "request_id", requestIDFromContext(r.Context()),
"attachment_id", attachmentID)
a.writeError(w, r, statusUnavailable)
return
case <-r.Context().Done():
a.compensatePending(attachmentID)
a.writeError(w, r, statusUnavailable)
return
}
if err != nil {
// Compensation for a failed PUT: the pending row is removed. If this
// best-effort delete also fails, the reconciler removes the stale row
// and any object after the grace period.
a.compensatePending(attachmentID)
a.log.Error("S3 upload failed", "request_id", requestIDFromContext(r.Context()), "attachment_id", attachmentID, "error", err)
if errors.Is(err, objectstore.ErrUnavailable) || errors.Is(err, objectstore.ErrNotFound) {
a.writeError(w, r, statusUnavailable)
return
}
a.writeError(w, r, statusInternal)
return
}
updatedAt, err := a.store.MarkAttachmentReady(r.Context(), attachmentID, time.Now().UTC())
if err != nil {
// The object and the pending row are both durable. Never delete the
// object here: an ambiguous COMMIT could have promoted the row already,
// and deleting a ready original is worse than a reconciler pass.
a.log.Error("could not promote attachment after S3 upload", "request_id", requestIDFromContext(r.Context()), "attachment_id", attachmentID, "error", err)
if errors.Is(err, store.ErrUnavailable) {
a.writeError(w, r, statusUnavailable)
return
}
a.writeError(w, r, statusInternal)
return
}
record.Status = attachmentStateReady
record.UpdatedAt = model.Time{Time: updatedAt}
a.log.Info("attachment ready",
"request_id", requestIDFromContext(r.Context()),
"attachment_id", attachmentID,
"chat_id", chatID,
"size_bytes", written,
"content_type", detected,
"image_width", width,
"image_height", height,
)
a.writeJSON(w, r, http.StatusCreated, record.Attachment)
}
// compensatePending removes the upload intent after a failed or abandoned S3
// write. A failed best-effort delete is intentionally left to the reconciler:
// deleting a possibly committed row here would be worse than a stale pending row.
func (a *App) compensatePending(attachmentID string) {
cleanupCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
_ = a.store.DeleteAttachmentRow(cleanupCtx, attachmentID)
cancel()
}
// validateImage applies every content rule before S3 or PostgreSQL is touched.
// The declared media type must match the bytes; the decoded pixel count is
// checked from the header before a potentially large full decode.
func (a *App) validateImage(ctx context.Context, temp *os.File, declared string) (detected string, width, height int, problem *apiError) {
if _, err := temp.Seek(0, io.SeekStart); err != nil {
return "", 0, 0, statusInternal
}
header := make([]byte, 512)
n, err := io.ReadFull(temp, header)
if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) {
return "", 0, 0, unsupportedMediaType("the upload body is not a valid image")
}
detected = http.DetectContentType(header[:n])
if detected != imagePNG && detected != imageJPEG {
return "", 0, 0, unsupportedMediaType("only PNG and JPEG images are accepted")
}
if declared != detected {
return "", 0, 0, unsupportedMediaType("Content-Type does not match the image bytes")
}
if _, err := temp.Seek(0, io.SeekStart); err != nil {
return "", 0, 0, statusInternal
}
config, format, err := image.DecodeConfig(temp)
if err != nil || (format != "png" && format != "jpeg") {
return "", 0, 0, unsupportedMediaType("the image header is corrupt or unsupported")
}
if config.Width < 1 || config.Height < 1 {
return "", 0, 0, unsupportedMediaType("the image has invalid dimensions")
}
pixels := int64(config.Width) * int64(config.Height)
if pixels > a.maxPixels || pixels > maxImageDimensionProduct {
return "", 0, 0, statusPayloadTooLarge
}
select {
case a.decodeSem <- struct{}{}:
defer func() { <-a.decodeSem }()
case <-time.After(decodeWaitTimeout):
return "", 0, 0, statusUnavailable
case <-ctx.Done():
return "", 0, 0, statusUnavailable
}
if _, err := temp.Seek(0, io.SeekStart); err != nil {
return "", 0, 0, statusInternal
}
decoded, _, err := image.Decode(temp)
if err != nil {
return "", 0, 0, unsupportedMediaType("the image is corrupt or truncated")
}
bounds := decoded.Bounds()
if bounds.Dx() < 1 || bounds.Dy() < 1 {
return "", 0, 0, unsupportedMediaType("the image has invalid dimensions")
}
return detected, bounds.Dx(), bounds.Dy(), nil
}
// uploadMediaType parses the declared Content-Type strictly. Parameters are
// accepted; any other media type is rejected before the body is read.
func uploadMediaType(r *http.Request) (string, *apiError) {
raw := strings.TrimSpace(r.Header.Get("Content-Type"))
if raw == "" {
return "", unsupportedMediaType("Content-Type must be image/png or image/jpeg")
}
mediaType, _, err := mime.ParseMediaType(raw)
if err != nil || (mediaType != imagePNG && mediaType != imageJPEG) {
return "", unsupportedMediaType("Content-Type must be image/png or image/jpeg")
}
return mediaType, nil
}
// uploadFilename validates the display-only filename query parameter. The
// value is never used as a path or an object key.
func uploadFilename(r *http.Request) (string, *apiError) {
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return "", invalidRequest("query string is not valid")
}
values, present := query["filename"]
if !present || len(values) != 1 || values[0] == "" {
return "", invalidRequest("filename query parameter is required exactly once")
}
name := values[0]
if !utf8.ValidString(name) {
return "", invalidRequest("filename must be valid UTF-8")
}
if count := utf8.RuneCountInString(name); count < 1 || count > maxFilenameCodePoints {
return "", invalidRequest("filename must contain 1 to 255 Unicode code points")
}
if name == "." || name == ".." {
return "", invalidRequest("filename must not be a path component")
}
for _, char := range name {
if char == '/' || char == '\\' || char == 0 || unicode.IsControl(char) {
return "", invalidRequest("filename must not contain path separators, NUL or control characters")
}
}
return name, nil
}
func (a *App) getAttachment(w http.ResponseWriter, r *http.Request, rawID string, actor identity) {
attachmentID, problem := normalizePathUUID(rawID, "attachment_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
record, err := a.store.ReadyAttachmentForUser(r.Context(), attachmentID, actor.user.ID)
if err != nil {
switch {
case errors.Is(err, store.ErrNotFound):
a.writeError(w, r, statusNotFound)
case errors.Is(err, store.ErrUnavailable):
a.log.Error("attachment metadata lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
default:
a.log.Error("attachment metadata lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
}
return
}
// The object is the source of truth for existence. A row whose bytes are
// gone must not be presented as a ready attachment.
if _, err := a.objects.Stat(r.Context(), record.ObjectKey); err != nil {
switch {
case errors.Is(err, objectstore.ErrNotFound):
a.writeError(w, r, statusNotFound)
case errors.Is(err, objectstore.ErrUnavailable):
a.log.Error("attachment object stat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
default:
a.log.Error("attachment object stat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
}
return
}
a.writeJSON(w, r, http.StatusOK, record.Attachment)
}
func (a *App) downloadAttachment(w http.ResponseWriter, r *http.Request, rawID string, actor identity) {
attachmentID, problem := normalizePathUUID(rawID, "attachment_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
if problem := requireOriginalVariant(r); problem != nil {
a.writeError(w, r, problem)
return
}
record, err := a.store.ReadyAttachmentForUser(r.Context(), attachmentID, actor.user.ID)
if err != nil {
switch {
case errors.Is(err, store.ErrNotFound):
a.writeError(w, r, statusNotFound)
case errors.Is(err, store.ErrUnavailable):
a.log.Error("attachment download lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
default:
a.log.Error("attachment download lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
}
return
}
body, info, err := a.objects.Get(r.Context(), record.ObjectKey)
if err != nil {
switch {
case errors.Is(err, objectstore.ErrNotFound):
a.writeError(w, r, statusNotFound)
case errors.Is(err, objectstore.ErrUnavailable):
a.log.Error("attachment object read failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
default:
a.log.Error("attachment object read failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
}
return
}
defer body.Close()
w.Header().Set("Content-Type", record.ContentType)
w.Header().Set("Content-Length", strconv.FormatInt(info.Size, 10))
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Cache-Control", "private, no-store")
w.WriteHeader(http.StatusOK)
if _, err := io.Copy(w, body); err != nil {
a.log.Warn("attachment stream interrupted", "request_id", requestIDFromContext(r.Context()), "attachment_id", attachmentID, "error", err)
}
}
// requireOriginalVariant accepts the optional variant parameter but lab4 has
// only the original. An unknown variant of a ready object is 404.
func requireOriginalVariant(r *http.Request) *apiError {
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return invalidRequest("query string is not valid")
}
values, present := query["variant"]
if !present {
return nil
}
if len(values) != 1 || values[0] == "" {
return invalidRequest("variant must be a non-empty string")
}
if values[0] == "original" {
return nil
}
return statusNotFound
}
+137
View File
@@ -0,0 +1,137 @@
package api
import (
"errors"
"net/http"
"mtusi.ru/messenger-lab4/internal/cursor"
"mtusi.ru/messenger-lab4/internal/store"
"mtusi.ru/messenger-lab4/internal/uuid"
)
type createChatRequest struct {
Title *string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
func (a *App) createChat(w http.ResponseWriter, r *http.Request, actor identity) {
var request createChatRequest
if problem := a.decodeJSON(r, &request, "title", "member_ids"); problem != nil {
a.writeError(w, r, problem)
return
}
if request.Title == nil {
a.writeError(w, r, invalidRequest("title is required"))
return
}
if problem := validateTitle(*request.Title); problem != nil {
a.writeError(w, r, problem)
return
}
if len(request.MemberIDs) < 1 || len(request.MemberIDs) > 100 {
a.writeError(w, r, invalidRequest("member_ids must contain 1 to 100 members"))
return
}
members := make([]string, 0, len(request.MemberIDs))
seen := make(map[string]struct{}, len(request.MemberIDs))
callerIncluded := false
for _, rawID := range request.MemberIDs {
id, ok := uuid.Normalize(rawID)
if !ok {
a.writeError(w, r, invalidRequest("every member_ids entry must be a UUID"))
return
}
if _, duplicate := seen[id]; duplicate {
a.writeError(w, r, invalidRequest("member_ids must not contain duplicates"))
return
}
seen[id] = struct{}{}
members = append(members, id)
if id == actor.user.ID {
callerIncluded = true
}
}
if !callerIncluded {
a.writeError(w, r, invalidRequest("caller must be present in member_ids"))
return
}
chat, err := a.store.CreateChat(r.Context(), *request.Title, members, actor.user.ID)
switch {
case errors.Is(err, store.ErrUnknownMember):
a.writeError(w, r, invalidRequest("every member_ids entry must reference an existing user"))
return
case errors.Is(err, store.ErrUnavailable):
a.log.Error("create chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Error("create chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusCreated, chat)
}
func (a *App) listChats(w http.ResponseWriter, r *http.Request, actor identity) {
limit, rawCursor, problem := a.pageParams(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
var position *cursor.Cursor
if rawCursor != "" {
decoded, err := cursor.Decode(rawCursor, cursor.ScopeChats, "")
if err != nil {
a.writeError(w, r, invalidRequest("cursor is invalid for this request"))
return
}
position = &decoded
}
page, err := a.store.Chats(r.Context(), actor.user.ID, position, limit)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
a.log.Error("list chats failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Error("list chats failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusOK, page)
}
func (a *App) getChat(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
chat, err := a.store.ChatForUser(r.Context(), chatID, actor.user.ID)
switch {
case errors.Is(err, store.ErrNotFound):
a.writeError(w, r, statusNotFound)
return
case errors.Is(err, store.ErrUnavailable):
a.log.Error("get chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Error("get chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusOK, chat)
}
// normalizePathUUID validates a path identifier before any database access.
func normalizePathUUID(raw, field string) (string, *apiError) {
id, ok := uuid.Normalize(raw)
if !ok {
return "", invalidRequest(field + " must be a UUID")
}
return id, nil
}
+184
View File
@@ -0,0 +1,184 @@
package api
import (
"context"
"log/slog"
"net/http"
"sync/atomic"
"time"
"mtusi.ru/messenger-lab4/internal/uuid"
)
// apiError is a contract-shaped error: HTTP status, machine-readable code, a
// safe human-readable message and an optional authentication challenge. The
// request id is filled from the request context at write time.
type apiError struct {
status int
code string
message string
challenge string
}
func (e *apiError) Error() string { return e.code + ": " + e.message }
const (
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
bearerChallenge = `Bearer realm="messenger"`
)
var (
statusInvalidRequest = &apiError{status: http.StatusBadRequest, code: "invalid_request", message: "request validation failed"}
statusNotFound = &apiError{status: http.StatusNotFound, code: "not_found", message: "object not found"}
statusConflict = &apiError{status: http.StatusConflict, code: "conflict", message: "object already exists"}
statusPayloadTooLarge = &apiError{status: http.StatusRequestEntityTooLarge, code: "payload_too_large", message: "request body is too large"}
statusUnsupportedMediaType = &apiError{status: http.StatusUnsupportedMediaType, code: "unsupported_media_type", message: "Content-Type must be application/json"}
statusUnavailable = &apiError{status: http.StatusServiceUnavailable, code: "unavailable", message: "a required dependency is unavailable"}
statusInternal = &apiError{status: http.StatusInternalServerError, code: "internal_error", message: "internal server error"}
)
func invalidRequest(message string) *apiError {
return &apiError{status: http.StatusBadRequest, code: "invalid_request", message: message}
}
func conflict(message string) *apiError {
return &apiError{status: http.StatusConflict, code: "conflict", message: message}
}
func unsupportedMediaType(message string) *apiError {
return &apiError{status: http.StatusUnsupportedMediaType, code: "unsupported_media_type", message: message}
}
func unauthorizedBasic() *apiError {
return &apiError{status: http.StatusUnauthorized, code: "unauthorized", message: "invalid username or password", challenge: basicChallenge}
}
func unauthorizedBearer() *apiError {
return &apiError{status: http.StatusUnauthorized, code: "unauthorized", message: "a valid bearer session is required", challenge: bearerChallenge}
}
type errorEnvelope struct {
Error errorBody `json:"error"`
}
type errorBody struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
// writeError writes a JSON error whose request_id matches X-Request-Id. The
// message never contains SQL, stack traces, credentials or object existence
// details for foreign resources.
func (a *App) writeError(w http.ResponseWriter, r *http.Request, problem *apiError) {
requestID := requestIDFromContext(r.Context())
if requestID == "" {
requestID = w.Header().Get("X-Request-Id")
}
if requestID == "" {
requestID = uuid.NewRandom(16)
w.Header().Set("X-Request-Id", requestID)
}
if problem.challenge != "" {
w.Header().Set("WWW-Authenticate", problem.challenge)
}
a.writeJSON(w, r, problem.status, errorEnvelope{Error: errorBody{
Code: problem.code,
Message: problem.message,
RequestID: requestID,
}})
}
func (a *App) notFound(w http.ResponseWriter, r *http.Request) {
a.writeError(w, r, statusNotFound)
}
type requestIDContextKey struct{}
func requestIDFromContext(ctx context.Context) string {
value, _ := ctx.Value(requestIDContextKey{}).(string)
return value
}
// statusWriter records the status code and byte count for logs and for the
// panic path, so a partially written response is not written twice.
type statusWriter struct {
http.ResponseWriter
status int
bytes int
wrote bool
}
func (w *statusWriter) WriteHeader(code int) {
if w.wrote {
return
}
w.wrote = true
w.status = code
w.ResponseWriter.WriteHeader(code)
}
func (w *statusWriter) Write(data []byte) (int, error) {
if !w.wrote {
w.WriteHeader(http.StatusOK)
}
written, err := w.ResponseWriter.Write(data)
w.bytes += written
return written, err
}
func (a *App) withObservability(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
requestID := uuid.NewRandom(16)
w.Header().Set("X-Request-Id", requestID)
// Stable for the life of the process and unique per container. lab3
// uses the container hostname: it is the actual process identity, so
// stop-one can map a response to exactly one container. lab7 will
// replace it with an opaque alias.
w.Header().Set("X-Instance-Id", a.instanceID)
// Extra, non-contract header used only to observe an image replacement
// during the rolling-update experiment. The mandatory contract does
// not define or require it.
w.Header().Set("X-App-Version", a.version)
r = r.WithContext(context.WithValue(r.Context(), requestIDContextKey{}, requestID))
writer := &statusWriter{ResponseWriter: w, status: http.StatusOK}
defer func() {
if recovered := recover(); recovered != nil {
a.log.Error("panic while handling request",
"request_id", requestID,
"instance_id", a.instanceID,
"method", r.Method,
"path", r.URL.Path,
"panic", recovered,
)
if !writer.wrote {
a.writeError(writer, r, statusInternal)
}
}
level := slog.LevelInfo
if r.URL.Path == "/health/live" || r.URL.Path == "/health/ready" {
level = slog.LevelDebug
}
a.log.Log(r.Context(), level, "http request",
"request_id", requestID,
"instance_id", a.instanceID,
"method", r.Method,
"path", r.URL.Path,
"status", writer.status,
"duration_ms", float64(time.Since(start).Microseconds())/1000.0,
"bytes", writer.bytes,
)
}()
next.ServeHTTP(writer, r)
})
}
// atomicBool keeps the readiness flag readable from the signal goroutine
// without importing sync/atomic into every handler file.
type atomicBool struct{ value atomic.Bool }
func (b *atomicBool) Store(value bool) { b.value.Store(value) }
func (b *atomicBool) Load() bool { return b.value.Load() }
+213
View File
@@ -0,0 +1,213 @@
package api
import (
"bytes"
"crypto/sha256"
"encoding/json"
"errors"
"net/http"
"unicode/utf8"
"mtusi.ru/messenger-lab4/internal/cursor"
"mtusi.ru/messenger-lab4/internal/store"
"mtusi.ru/messenger-lab4/internal/uuid"
)
const maxMessageAttachments = 10
type createMessageRequest struct {
Text *string `json:"text"`
AttachmentIDs json.RawMessage `json:"attachment_ids"`
}
// messageHash is the canonical semantic body used for idempotency. A missing
// attachment_ids is normalised to [], exactly as the contract requires, and
// JSON object key order never affects the hash. Array order is preserved: the
// response also preserves it.
type messageHashBody struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
func (a *App) createMessage(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
// The key is validated before the body, but after authentication and path
// validation: a malformed/missing key is always 400, while an outsider
// still cannot learn anything by replaying someone else's key.
idempotencyKey, problem := idempotencyKey(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
// Resource access is checked before the body is decoded so a foreign chat
// always looks like a missing chat, independent of the submitted payload.
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
if !member {
a.writeError(w, r, statusNotFound)
return
}
var request createMessageRequest
if problem := a.decodeJSON(r, &request, "text", "attachment_ids"); problem != nil {
a.writeError(w, r, problem)
return
}
if request.Text == nil {
a.writeError(w, r, invalidRequest("text is required"))
return
}
attachmentIDs, problem := parseAttachmentIDs(request.AttachmentIDs)
if problem != nil {
a.writeError(w, r, problem)
return
}
if utf8.RuneCountInString(*request.Text) > 4000 {
a.writeError(w, r, invalidRequest("text must contain at most 4000 Unicode code points"))
return
}
if isBlank(*request.Text) && len(attachmentIDs) == 0 {
a.writeError(w, r, invalidRequest("text must not be blank without attachments"))
return
}
canonical, err := json.Marshal(messageHashBody{Text: *request.Text, AttachmentIDs: attachmentIDs})
if err != nil {
a.writeError(w, r, statusInternal)
return
}
hash := sha256.Sum256(canonical)
message, replayed, err := a.store.CreateMessageIdempotent(
r.Context(), chatID, actor.user.ID, http.MethodPost, messagePath(chatID),
idempotencyKey, hash[:], *request.Text, attachmentIDs,
)
switch {
case errors.Is(err, store.ErrIdempotencyConflict):
a.conflictMessages.Add(1)
a.writeError(w, r, statusConflict)
return
case errors.Is(err, store.ErrAttachmentNotReady):
a.writeError(w, r, conflict("attachment is not ready"))
return
case errors.Is(err, store.ErrNotFound):
a.writeError(w, r, statusNotFound)
return
case errors.Is(err, store.ErrUnavailable):
a.log.Error("create message failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Error("create message failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
if replayed {
a.replayedMessages.Add(1)
} else {
a.createdMessages.Add(1)
}
a.writeJSON(w, r, http.StatusCreated, message)
}
// parseAttachmentIDs accepts an absent field as [], rejects null and every
// wrong JSON type, and enforces the UUID / uniqueness / count rules before any
// database access.
func parseAttachmentIDs(raw json.RawMessage) ([]string, *apiError) {
if len(bytes.TrimSpace(raw)) == 0 {
return []string{}, nil
}
if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
return nil, invalidRequest("attachment_ids must be an array, not null")
}
var values []string
if err := json.Unmarshal(raw, &values); err != nil {
return nil, invalidRequest("attachment_ids must be an array of UUID strings")
}
if len(values) > maxMessageAttachments {
return nil, invalidRequest("attachment_ids must contain at most 10 items")
}
result := make([]string, 0, len(values))
seen := make(map[string]struct{}, len(values))
for _, value := range values {
id, ok := uuid.Normalize(value)
if !ok {
return nil, invalidRequest("every attachment_ids entry must be a UUID")
}
if _, duplicate := seen[id]; duplicate {
return nil, invalidRequest("attachment_ids must not contain duplicates")
}
seen[id] = struct{}{}
result = append(result, id)
}
return result, nil
}
func messagePath(chatID string) string {
return "/api/v1/chats/" + chatID + "/messages"
}
func (a *App) listMessages(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
if problem != nil {
a.writeError(w, r, problem)
return
}
// A foreign/nonexistent chat is always 404, even if the query itself is
// malformed; this avoids making object existence observable.
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
if !member {
a.writeError(w, r, statusNotFound)
return
}
limit, rawCursor, problem := a.pageParams(r)
if problem != nil {
a.writeError(w, r, problem)
return
}
var position *cursor.Cursor
if rawCursor != "" {
decoded, err := cursor.Decode(rawCursor, cursor.ScopeMessages, chatID)
if err != nil {
a.writeError(w, r, invalidRequest("cursor is invalid for this chat"))
return
}
position = &decoded
}
page, err := a.store.Messages(r.Context(), chatID, position, limit)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
a.log.Error("list messages failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
}
a.log.Error("list messages failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusOK, page)
}
+91
View File
@@ -0,0 +1,91 @@
package api
import (
"encoding/json"
"net/http"
"runtime"
"time"
)
// InternalStats is the operator-only JSON document served on the loopback
// metrics listener inside each API container. It is deliberately not part of
// the public contract and is never routed through the load balancer; the
// experiment scripts read it with `docker exec` to attribute saturation to
// the connection pool versus PostgreSQL/CPU.
type InternalStats struct {
InstanceID string `json:"instance_id"`
Version string `json:"version"`
UptimeSeconds float64 `json:"uptime_seconds"`
Pool poolStats `json:"pool"`
Messages messageCounters `json:"messages"`
Runtime runtimeStats `json:"runtime"`
CollectedAt string `json:"collected_at"`
}
type poolStats struct {
MaxConns int32 `json:"max_conns"`
TotalConns int32 `json:"total_conns"`
AcquiredConns int32 `json:"acquired_conns"`
IdleConns int32 `json:"idle_conns"`
EmptyAcquireCount int64 `json:"empty_acquire_count"`
CanceledAcquireCount int64 `json:"canceled_acquire_count"`
AcquireCount int64 `json:"acquire_count"`
AcquireDurationMillis int64 `json:"acquire_duration_ms_total"`
NewConnsCount int64 `json:"new_conns_count"`
MaxLifetimeDestroyCount int64 `json:"max_lifetime_destroy_count"`
MaxIdleDestroyCount int64 `json:"max_idle_destroy_count"`
}
type messageCounters struct {
Created uint64 `json:"created"`
Replayed uint64 `json:"replayed"`
Conflicts uint64 `json:"conflicts"`
}
type runtimeStats struct {
Goroutines int `json:"goroutines"`
HeapAlloc uint64 `json:"heap_alloc_bytes"`
HeapSys uint64 `json:"heap_sys_bytes"`
TotalAlloc uint64 `json:"total_alloc_bytes"`
}
// InternalStatsHandler serves one snapshot. It is mounted only on the
// 127.0.0.1 listener started by cmd/messenger.
func (a *App) InternalStatsHandler(w http.ResponseWriter, _ *http.Request) {
pool := a.store.PoolStats()
var memory runtime.MemStats
runtime.ReadMemStats(&memory)
stats := InternalStats{
InstanceID: a.instanceID,
Version: a.version,
UptimeSeconds: time.Since(a.startedAt).Seconds(),
Pool: poolStats{
MaxConns: pool.MaxConns,
TotalConns: pool.TotalConns,
AcquiredConns: pool.AcquiredConns,
IdleConns: pool.IdleConns,
EmptyAcquireCount: pool.EmptyAcquireCount,
CanceledAcquireCount: pool.CanceledAcquireCount,
AcquireCount: pool.AcquireCount,
AcquireDurationMillis: pool.AcquireDurationMillis,
NewConnsCount: pool.NewConnsCount,
MaxLifetimeDestroyCount: pool.MaxLifetimeDestroyCount,
MaxIdleDestroyCount: pool.MaxIdleDestroyCount,
},
Messages: messageCounters{
Created: a.createdMessages.Load(),
Replayed: a.replayedMessages.Load(),
Conflicts: a.conflictMessages.Load(),
},
Runtime: runtimeStats{
Goroutines: runtime.NumGoroutine(),
HeapAlloc: memory.HeapAlloc,
HeapSys: memory.HeapSys,
TotalAlloc: memory.TotalAlloc,
},
CollectedAt: time.Now().UTC().Format(time.RFC3339Nano),
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(stats)
}
+157
View File
@@ -0,0 +1,157 @@
package api
import (
"errors"
"net/http"
"strings"
"unicode/utf8"
"mtusi.ru/messenger-lab4/internal/auth"
"mtusi.ru/messenger-lab4/internal/model"
"mtusi.ru/messenger-lab4/internal/session"
"mtusi.ru/messenger-lab4/internal/store"
)
// createSession is the only endpoint that accepts Basic credentials. It never
// accepts a JSON body and never reveals whether the username exists.
func (a *App) createSession(w http.ResponseWriter, r *http.Request) {
username, password, err := auth.ParseBasic(r.Header.Get("Authorization"))
if err != nil {
a.writeError(w, r, unauthorizedBasic())
return
}
// Reject values that could never have been registered before touching the
// database (invalid UTF-8 would otherwise become a 500 from PostgreSQL).
if !usernameAllowed(username) || !validLoginPassword(password) {
_, _ = auth.Verify(password, a.dummyHash)
a.writeError(w, r, unauthorizedBasic())
return
}
user, passwordHash, err := a.store.UserByUsername(r.Context(), username)
switch {
case errors.Is(err, store.ErrNotFound):
// Spend the same KDF work for an unknown username so response timing
// does not disclose account existence.
_, _ = auth.Verify(password, a.dummyHash)
a.writeError(w, r, unauthorizedBasic())
return
case errors.Is(err, store.ErrUnavailable):
a.log.Error("login database unavailable", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Error("login lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
match, err := auth.Verify(password, passwordHash)
if err != nil {
// A corrupt stored hash is an internal data problem, not a wrong
// password; do not silently lock the account out with a 401 log line.
a.log.Error("stored password hash is invalid", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
if !match {
a.writeError(w, r, unauthorizedBasic())
return
}
token, expiresAt, err := a.sessions.Create(r.Context(), user.ID)
if err != nil {
a.log.Error("session creation failed", "request_id", requestIDFromContext(r.Context()), "error", err)
if errors.Is(err, session.ErrUnavailable) {
a.writeError(w, r, statusUnavailable)
return
}
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusCreated, model.Session{
Token: token,
TokenType: "Bearer",
ExpiresAt: model.Time{Time: expiresAt},
User: user,
})
}
// authenticate accepts only "Authorization: Bearer <opaque token>". A Basic
// header on a business endpoint, a missing header and an X-User-Id header all
// produce the same 401 challenge.
func (a *App) authenticate(r *http.Request) (identity, *apiError) {
token, ok := bearerToken(r.Header.Get("Authorization"))
if !ok || !auth.ValidTokenShape(token) {
return identity{}, unauthorizedBearer()
}
userID, err := a.sessions.Get(r.Context(), token)
switch {
case errors.Is(err, session.ErrInvalid):
return identity{}, unauthorizedBearer()
case errors.Is(err, session.ErrUnavailable):
a.log.Error("session lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
return identity{}, statusUnavailable
case err != nil:
a.log.Error("session lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
return identity{}, statusInternal
}
user, err := a.store.UserByID(r.Context(), userID)
switch {
case errors.Is(err, store.ErrNotFound):
// A session pointing at a missing user is not usable. Deleting it is
// best effort; the response is the normal 401 either way.
_ = a.sessions.Delete(r.Context(), token)
return identity{}, unauthorizedBearer()
case errors.Is(err, store.ErrUnavailable):
a.log.Error("user lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
return identity{}, statusUnavailable
case err != nil:
a.log.Error("user lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
return identity{}, statusInternal
}
return identity{user: user, token: token}, nil
}
// logout revokes the current server-side session. The response has no body.
func (a *App) logout(w http.ResponseWriter, r *http.Request, actor identity) {
if err := a.sessions.Delete(r.Context(), actor.token); err != nil {
a.log.Error("logout failed", "request_id", requestIDFromContext(r.Context()), "error", err)
if errors.Is(err, session.ErrUnavailable) {
a.writeError(w, r, statusUnavailable)
return
}
a.writeError(w, r, statusInternal)
return
}
w.WriteHeader(http.StatusNoContent)
}
func bearerToken(header string) (string, bool) {
trimmed := strings.TrimSpace(header)
space := strings.IndexByte(trimmed, ' ')
if space <= 0 {
return "", false
}
if !strings.EqualFold(trimmed[:space], "Bearer") {
return "", false
}
token := trimmed[space+1:]
if token == "" || strings.ContainsAny(token, " \t") {
return "", false
}
return token, true
}
// validLoginPassword mirrors the registration policy. A login with an
// out-of-range password cannot match any stored hash and must still look like
// an ordinary 401.
func validLoginPassword(password string) bool {
if !utf8.ValidString(password) || isBlank(password) {
return false
}
count := utf8.RuneCountInString(password)
return count >= 12 && count <= 128
}
+74
View File
@@ -0,0 +1,74 @@
package api
import (
"errors"
"net/http"
"mtusi.ru/messenger-lab4/internal/auth"
"mtusi.ru/messenger-lab4/internal/store"
)
type createUserRequest struct {
Username *string `json:"username"`
DisplayName *string `json:"display_name"`
Password *string `json:"password"`
}
func (a *App) createUser(w http.ResponseWriter, r *http.Request) {
var request createUserRequest
if problem := a.decodeJSON(r, &request, "username", "display_name", "password"); problem != nil {
a.writeError(w, r, problem)
return
}
if request.Username == nil {
a.writeError(w, r, invalidRequest("username is required"))
return
}
if request.DisplayName == nil {
a.writeError(w, r, invalidRequest("display_name is required"))
return
}
if request.Password == nil {
a.writeError(w, r, invalidRequest("password is required"))
return
}
if problem := validateUsername(*request.Username); problem != nil {
a.writeError(w, r, problem)
return
}
if problem := validateDisplayName(*request.DisplayName); problem != nil {
a.writeError(w, r, problem)
return
}
if problem := validatePassword(*request.Password); problem != nil {
a.writeError(w, r, problem)
return
}
passwordHash, err := auth.Hash(*request.Password)
if err != nil {
a.log.Error("password hashing failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
user, err := a.store.CreateUser(r.Context(), *request.Username, *request.DisplayName, passwordHash)
switch {
case errors.Is(err, store.ErrUsernameTaken):
a.writeError(w, r, statusConflict)
return
case errors.Is(err, store.ErrUnavailable):
a.log.Error("create user failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusUnavailable)
return
case err != nil:
a.log.Error("create user failed", "request_id", requestIDFromContext(r.Context()), "error", err)
a.writeError(w, r, statusInternal)
return
}
a.writeJSON(w, r, http.StatusCreated, user)
}
func (a *App) currentUser(w http.ResponseWriter, r *http.Request, actor identity) {
a.writeJSON(w, r, http.StatusOK, actor.user)
}
+236
View File
@@ -0,0 +1,236 @@
package api
import (
"bytes"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"unicode/utf8"
)
// decodeJSON enforces the contract's JSON rules: application/json, strict
// UTF-8, exactly one object with exactly the documented top-level keys, no
// unknown/duplicate fields and a bounded body size.
//
// encoding/json matches struct fields case-insensitively even with
// DisallowUnknownFields, so the exact key set is checked separately on the
// token stream. That also rejects Unicode case-folding aliases and duplicates.
func (a *App) decodeJSON(r *http.Request, destination any, allowedKeys ...string) *apiError {
if raw := r.Header.Get("Content-Type"); raw != "" {
mediaType, _, err := mime.ParseMediaType(raw)
if err != nil || mediaType != "application/json" {
return statusUnsupportedMediaType
}
}
body, err := io.ReadAll(io.LimitReader(r.Body, a.maxBody+1))
if err != nil {
return invalidRequest("could not read request body")
}
if int64(len(body)) > a.maxBody {
return statusPayloadTooLarge
}
if len(bytes.TrimSpace(body)) == 0 {
return invalidRequest("request body must not be empty")
}
if !utf8.Valid(body) {
return invalidRequest("request body must be valid UTF-8")
}
if problem := validateTopLevelKeys(body, allowedKeys); problem != nil {
return problem
}
decoder := json.NewDecoder(bytes.NewReader(body))
decoder.DisallowUnknownFields()
if err := decoder.Decode(destination); err != nil {
return invalidRequest("request body does not match the documented schema")
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
return invalidRequest("request body must contain exactly one JSON value")
}
return nil
}
func validateTopLevelKeys(body []byte, allowedKeys []string) *apiError {
allowed := make(map[string]struct{}, len(allowedKeys))
for _, key := range allowedKeys {
allowed[key] = struct{}{}
}
decoder := json.NewDecoder(bytes.NewReader(body))
token, err := decoder.Token()
if err != nil {
return invalidRequest("request body must be valid JSON")
}
opening, ok := token.(json.Delim)
if !ok || opening != '{' {
return invalidRequest("request body must be a JSON object")
}
seen := make(map[string]struct{}, len(allowedKeys))
for decoder.More() {
token, err := decoder.Token()
if err != nil {
return invalidRequest("request body must be valid JSON")
}
key, ok := token.(string)
if !ok {
return invalidRequest("request body must contain string field names")
}
if _, duplicate := seen[key]; duplicate {
return invalidRequest("request body must not contain duplicate fields")
}
seen[key] = struct{}{}
if _, ok := allowed[key]; !ok {
return invalidRequest("request body contains an unknown field")
}
var value json.RawMessage
if err := decoder.Decode(&value); err != nil {
return invalidRequest("request body must be valid JSON")
}
}
if _, err := decoder.Token(); err != nil {
return invalidRequest("request body must be valid JSON")
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
return invalidRequest("request body must contain exactly one JSON value")
}
return nil
}
// pageParams parses limit/cursor. Cursor decoding happens after membership is
// verified so a foreign chat cannot be probed with a malformed cursor.
func (a *App) pageParams(r *http.Request) (int, string, *apiError) {
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return 0, "", invalidRequest("query string is not valid")
}
limit := 50
if values, present := query["limit"]; present {
if len(values) != 1 {
return 0, "", invalidRequest("limit must be specified once")
}
parsed, err := strconv.Atoi(values[0])
if err != nil || parsed < 1 || parsed > 100 {
return 0, "", invalidRequest("limit must be an integer between 1 and 100")
}
limit = parsed
}
cursor := ""
if values, present := query["cursor"]; present {
if len(values) != 1 || values[0] == "" {
return 0, "", invalidRequest("cursor must be a non-empty string")
}
cursor = values[0]
}
return limit, cursor, nil
}
func validateUsername(value string) *apiError {
if !usernameAllowed(value) {
return invalidRequest("username must match [a-z0-9_]{3,32}")
}
return nil
}
func validateDisplayName(value string) *apiError {
if isBlank(value) {
return invalidRequest("display_name must not be blank")
}
if count := utf8.RuneCountInString(value); count < 1 || count > 100 {
return invalidRequest("display_name must contain 1 to 100 Unicode code points")
}
return nil
}
func validateTitle(value string) *apiError {
if isBlank(value) {
return invalidRequest("title must not be blank")
}
if count := utf8.RuneCountInString(value); count < 1 || count > 100 {
return invalidRequest("title must contain 1 to 100 Unicode code points")
}
return nil
}
func validateMessageText(value string) *apiError {
if isBlank(value) {
return invalidRequest("text must not be blank")
}
if count := utf8.RuneCountInString(value); count < 1 || count > 4000 {
return invalidRequest("text must contain 1 to 4000 Unicode code points")
}
return nil
}
// validatePassword implements the registration rule: 12 to 128 Unicode code
// points, not only whitespace. The exact bytes are handed to Argon2id, so
// Unicode passwords are neither truncated nor normalized by the server.
func validatePassword(value string) *apiError {
if !utf8.ValidString(value) {
return invalidRequest("password must be valid UTF-8")
}
if isBlank(value) {
return invalidRequest("password must not be blank")
}
if count := utf8.RuneCountInString(value); count < 12 || count > 128 {
return invalidRequest("password must contain 12 to 128 Unicode code points")
}
return nil
}
func isBlank(value string) bool {
return strings.TrimSpace(value) == ""
}
// usernameAllowed is a byte-wise equivalent of the contract pattern
// ^[a-z0-9_]{3,32}$; non-ASCII bytes can never match.
func usernameAllowed(value string) bool {
if len(value) < 3 || len(value) > 32 {
return false
}
for i := 0; i < len(value); i++ {
c := value[i]
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' {
continue
}
return false
}
return true
}
// idempotencyKey enforces the contract's header rule exactly:
// ASCII [A-Za-z0-9._:-]{1,128}, present exactly once. No trimming: whitespace
// is outside the permitted alphabet, so a value with surrounding spaces is
// rejected rather than silently normalised into a different scope.
func idempotencyKey(r *http.Request) (string, *apiError) {
values := r.Header.Values("Idempotency-Key")
if len(values) != 1 {
return "", invalidRequest("Idempotency-Key header is required exactly once")
}
key := values[0]
if len(key) < 1 || len(key) > 128 {
return "", invalidRequest("Idempotency-Key must contain 1 to 128 ASCII characters")
}
for i := 0; i < len(key); i++ {
c := key[i]
switch {
case c >= 'A' && c <= 'Z':
case c >= 'a' && c <= 'z':
case c >= '0' && c <= '9':
case c == '.' || c == '_' || c == ':' || c == '-':
default:
return "", invalidRequest("Idempotency-Key may contain only A-Z a-z 0-9 . _ : -")
}
}
return key, nil
}
+203
View File
@@ -0,0 +1,203 @@
package api
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
type sampleRequest struct {
Username *string `json:"username"`
DisplayName *string `json:"display_name"`
Password *string `json:"password"`
}
func decodeTestApp() *App { return &App{maxBody: maxBodyBytes} }
func TestDecodeJSONAcceptsDocumentedObject(t *testing.T) {
app := decodeTestApp()
body := `{"username":"alice","display_name":"Алиса","password":"long-enough-secret"}`
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(body))
request.Header.Set("Content-Type", "application/json; charset=utf-8")
var destination sampleRequest
if problem := app.decodeJSON(request, &destination, "username", "display_name", "password"); problem != nil {
t.Fatalf("decodeJSON rejected a valid body: %v", problem)
}
if destination.Username == nil || *destination.Username != "alice" {
t.Fatalf("decoded value = %+v", destination)
}
}
func TestDecodeJSONRejectsContractViolations(t *testing.T) {
app := decodeTestApp()
cases := []struct {
name string
body string
contentType string
status int
}{
{"empty", "", "application/json", http.StatusBadRequest},
{"whitespace only", " \n", "application/json", http.StatusBadRequest},
{"malformed", `{"username":`, "application/json", http.StatusBadRequest},
{"array instead of object", `[]`, "application/json", http.StatusBadRequest},
{"string instead of object", `"x"`, "application/json", http.StatusBadRequest},
{"unknown field", `{"username":"a","display_name":"b","password":"c","extra":1}`, "application/json", http.StatusBadRequest},
{"duplicate field", `{"username":"a","username":"b","display_name":"c","password":"d"}`, "application/json", http.StatusBadRequest},
{"uppercase alias", `{"Username":"a","display_name":"b","password":"c"}`, "application/json", http.StatusBadRequest},
{"alias beside correct key", `{"username":"a","Username":"b","display_name":"c","password":"d"}`, "application/json", http.StatusBadRequest},
{"wrong type", `{"username":1,"display_name":"b","password":"c"}`, "application/json", http.StatusBadRequest},
{"two values", `{"username":"a","display_name":"b","password":"c"}{}`, "application/json", http.StatusBadRequest},
{"wrong content type", `{"username":"a","display_name":"b","password":"c"}`, "text/plain", http.StatusUnsupportedMediaType},
{"malformed content type", `{"username":"a","display_name":"b","password":"c"}`, "application/json; charset", http.StatusUnsupportedMediaType},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(tc.body))
request.Header.Set("Content-Type", tc.contentType)
var destination sampleRequest
problem := app.decodeJSON(request, &destination, "username", "display_name", "password")
if problem == nil {
t.Fatal("decodeJSON accepted an invalid body")
}
if problem.status != tc.status {
t.Fatalf("status = %d, want %d", problem.status, tc.status)
}
})
}
}
func TestDecodeJSONRejectsInvalidUTF8(t *testing.T) {
app := decodeTestApp()
body := append([]byte(`{"username":"`), 0xff, 0xfe)
body = append(body, []byte(`","display_name":"b","password":"c"}`)...)
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", bytes.NewReader(body))
request.Header.Set("Content-Type", "application/json")
var destination sampleRequest
if problem := app.decodeJSON(request, &destination, "username", "display_name", "password"); problem == nil || problem.status != http.StatusBadRequest {
t.Fatalf("invalid UTF-8 was not rejected with 400: %v", problem)
}
}
func TestDecodeJSONRejectsOversizedBody(t *testing.T) {
app := decodeTestApp()
app.maxBody = 16
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(`{"username":"`+strings.Repeat("x", 64)+`"}`))
request.Header.Set("Content-Type", "application/json")
var destination sampleRequest
if problem := app.decodeJSON(request, &destination, "username"); problem == nil || problem.status != http.StatusRequestEntityTooLarge {
t.Fatalf("oversized body = %v, want 413", problem)
}
}
func TestUsernameValidation(t *testing.T) {
valid := []string{"abc", "a_b9", strings.Repeat("a", 32)}
for _, value := range valid {
if problem := validateUsername(value); problem != nil {
t.Fatalf("validateUsername(%q) = %v", value, problem)
}
}
invalid := []string{"", "ab", strings.Repeat("a", 33), "Alice", "a-b", "a b", "aбв", "abc\n"}
for _, value := range invalid {
if problem := validateUsername(value); problem == nil {
t.Fatalf("validateUsername accepted %q", value)
}
}
}
func TestLengthValidationCountsCodePoints(t *testing.T) {
if problem := validateDisplayName(strings.Repeat("😀", 100)); problem != nil {
t.Fatalf("100 code points rejected: %v", problem)
}
if problem := validateDisplayName(strings.Repeat("😀", 101)); problem == nil {
t.Fatal("101 code points accepted")
}
if problem := validateDisplayName(" "); problem == nil {
t.Fatal("blank display_name accepted")
}
if problem := validateMessageText(strings.Repeat("я", 4000)); problem != nil {
t.Fatalf("4000 code points rejected: %v", problem)
}
if problem := validateMessageText(strings.Repeat("я", 4001)); problem == nil {
t.Fatal("4001 code points accepted")
}
if problem := validateMessageText(" \t\n"); problem == nil {
t.Fatal("blank message accepted")
}
if problem := validatePassword(strings.Repeat("p", 12)); problem != nil {
t.Fatalf("12-character password rejected: %v", problem)
}
if problem := validatePassword(strings.Repeat("p", 11)); problem == nil {
t.Fatal("11-character password accepted")
}
if problem := validatePassword(strings.Repeat("p", 128)); problem != nil {
t.Fatalf("128-character password rejected: %v", problem)
}
if problem := validatePassword(strings.Repeat("p", 129)); problem == nil {
t.Fatal("129-character password accepted")
}
if problem := validatePassword(strings.Repeat(" ", 12)); problem == nil {
t.Fatal("whitespace password accepted")
}
}
func TestPageParams(t *testing.T) {
valid := map[string][2]any{
"": {50, ""},
"?limit=1": {1, ""},
"?limit=100": {100, ""},
"?limit=7&cursor=x": {7, "x"},
}
for query, want := range valid {
request := httptest.NewRequest(http.MethodGet, "/api/v1/chats"+query, nil)
limit, cursor, problem := decodeTestApp().pageParams(request)
if problem != nil {
t.Fatalf("pageParams(%q) = %v", query, problem)
}
if limit != want[0].(int) || cursor != want[1].(string) {
t.Fatalf("pageParams(%q) = %d,%q", query, limit, cursor)
}
}
invalid := []string{"?limit=0", "?limit=101", "?limit=abc", "?limit=", "?limit=1&limit=2", "?cursor=", "?cursor=a&cursor=b", "?limit=1;cursor=x"}
for _, query := range invalid {
request := httptest.NewRequest(http.MethodGet, "/api/v1/chats"+query, nil)
if _, _, problem := decodeTestApp().pageParams(request); problem == nil {
t.Fatalf("pageParams accepted %q", query)
}
}
}
func TestBearerTokenParsing(t *testing.T) {
token := strings.Repeat("a", 43)
cases := map[string]string{
"Bearer " + token: token,
"bearer " + token: token,
"BEARER " + token: token,
}
for header, want := range cases {
got, ok := bearerToken(header)
if !ok || got != want {
t.Fatalf("bearerToken(%q) = %q,%v", header, got, ok)
}
}
for _, header := range []string{"", "Bearer", "Bearer ", "Basic abc", "Bearer a b", "Token " + token} {
if _, ok := bearerToken(header); ok {
t.Fatalf("bearerToken accepted %q", header)
}
}
}
func TestErrorEnvelopeShape(t *testing.T) {
envelope := errorEnvelope{Error: errorBody{Code: "invalid_request", Message: "x", RequestID: "id"}}
data, err := json.Marshal(envelope)
if err != nil {
t.Fatal(err)
}
if string(data) != `{"error":{"code":"invalid_request","message":"x","request_id":"id"}}` {
t.Fatalf("unexpected error JSON: %s", data)
}
}
+156
View File
@@ -0,0 +1,156 @@
package auth
import (
"encoding/base64"
"strings"
"testing"
)
func TestHashAndVerify(t *testing.T) {
password := "correct horse battery staple"
encoded, err := Hash(password)
if err != nil {
t.Fatalf("Hash: %v", err)
}
if !strings.HasPrefix(encoded, "$argon2id$v=19$m=19456,t=2,p=1$") {
t.Fatalf("unexpected PHC prefix: %q", encoded)
}
match, err := Verify(password, encoded)
if err != nil || !match {
t.Fatalf("Verify(correct) = %v, %v", match, err)
}
match, err = Verify(password+"x", encoded)
if err != nil || match {
t.Fatalf("Verify(wrong) = %v, %v", match, err)
}
}
func TestHashUnicodeAndMaximumLength(t *testing.T) {
for _, password := range []string{
"pässwörd:12✓",
strings.Repeat("界", 128),
" leading and trailing spaces ",
} {
encoded, err := Hash(password)
if err != nil {
t.Fatalf("Hash(%q): %v", password, err)
}
if match, err := Verify(password, encoded); err != nil || !match {
t.Fatalf("Verify(%q) = %v, %v", password, match, err)
}
}
}
func TestHashUsesRandomSalt(t *testing.T) {
first, err := Hash("same-password-twice")
if err != nil {
t.Fatal(err)
}
second, err := Hash("same-password-twice")
if err != nil {
t.Fatal(err)
}
if first == second {
t.Fatal("two hashes of the same password are identical")
}
}
func TestVerifyRejectsMalformedHashes(t *testing.T) {
for _, encoded := range []string{
"",
"plaintext",
"$2a$10$abcdefghijklmnopqrstuv",
"$argon2id$v=19$m=19456,t=2,p=1$not-base64$hash",
"$argon2id$v=19$m=1,t=3,p=2$c2FsdHNhbHQ$aGFzaGhhc2hoYXNoaGFzaA",
"$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaA",
} {
if _, err := Verify("password", encoded); err == nil {
t.Fatalf("Verify accepted malformed hash %q", encoded)
}
}
}
func TestParseBasic(t *testing.T) {
cases := []struct {
name string
raw string
username string
password string
ok bool
}{
{
name: "ordinary",
raw: "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:secret")),
username: "alice",
password: "secret",
ok: true,
},
{
name: "password contains colon and UTF-8",
raw: "bAsIc " + base64.StdEncoding.EncodeToString([]byte("alice:pässwörd:with:colons")),
username: "alice",
password: "pässwörd:with:colons",
ok: true,
},
{
name: "unpadded base64",
raw: "Basic " + base64.RawStdEncoding.EncodeToString([]byte("alice:secret")),
username: "alice",
password: "secret",
ok: true,
},
{name: "no scheme", raw: "alice:secret"},
{name: "wrong scheme", raw: "Bearer abc"},
{name: "no space", raw: "Basic" + base64.StdEncoding.EncodeToString([]byte("alice:secret"))},
{name: "bad base64", raw: "Basic !!!"},
{name: "no separator", raw: "Basic " + base64.StdEncoding.EncodeToString([]byte("alice"))},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
username, password, err := ParseBasic(tc.raw)
if !tc.ok {
if err == nil {
t.Fatalf("ParseBasic accepted %q", tc.raw)
}
return
}
if err != nil {
t.Fatalf("ParseBasic: %v", err)
}
if username != tc.username || password != tc.password {
t.Fatalf("got %q/%q, want %q/%q", username, password, tc.username, tc.password)
}
})
}
}
func TestTokenProperties(t *testing.T) {
first, err := NewToken()
if err != nil {
t.Fatal(err)
}
second, err := NewToken()
if err != nil {
t.Fatal(err)
}
if first == second {
t.Fatal("tokens are not unique")
}
if len(first) != 43 {
t.Fatalf("token length = %d, want 43 (256 bits)", len(first))
}
if !ValidTokenShape(first) {
t.Fatal("issued token fails its own shape check")
}
if TokenHash(first) == TokenHash(second) {
t.Fatal("token hashes collide")
}
if len(TokenHash(first)) != 64 {
t.Fatalf("token hash length = %d", len(TokenHash(first)))
}
for _, bad := range []string{"", "short", "has space in it", strings.Repeat("a", 129), "abc+/="} {
if ValidTokenShape(bad) {
t.Fatalf("ValidTokenShape accepted %q", bad)
}
}
}
+90
View File
@@ -0,0 +1,90 @@
// Package auth implements the lab3 credential primitives: a library password
// KDF (Argon2id), opaque session tokens and RFC 7617 Basic parsing. None of
// these helpers log or serialise the secret material they receive.
package auth
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
// Argon2id parameters. 19 MiB / 2 passes / 1 lane is the OWASP password
// storage minimum for Argon2id, chosen so eight concurrent registrations fit
// inside the 256 MiB API container limit. The parameters are stored in every
// PHC string, so a future change remains backward compatible.
const (
argonMemory uint32 = 19 * 1024 // KiB
argonIterations uint32 = 2
argonParallelism uint8 = 1
argonSaltLength = 16
argonKeyLength uint32 = 32
)
// ErrInvalidHash means a stored PHC string is malformed or uses unsupported
// parameters. It is an internal error, never shown to a client.
var ErrInvalidHash = errors.New("invalid password hash")
// Hash derives an Argon2id PHC string for password. Callers must validate the
// password policy before calling; the KDF itself accepts arbitrary UTF-8.
func Hash(password string) (string, error) {
salt := make([]byte, argonSaltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("generate password salt: %w", err)
}
key := argon2.IDKey([]byte(password), salt, argonIterations, argonMemory, argonParallelism, argonKeyLength)
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version, argonMemory, argonIterations, argonParallelism,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(key),
), nil
}
// Verify checks password against a PHC string in constant time and reports
// whether the encoded hash was structurally valid. A malformed hash is not a
// password mismatch and should be treated as an internal error by the caller.
func Verify(password, encoded string) (match bool, err error) {
params, salt, key, err := parse(encoded)
if err != nil {
return false, err
}
candidate := argon2.IDKey([]byte(password), salt, params.iterations, params.memory, params.parallelism, uint32(len(key)))
return subtle.ConstantTimeCompare(candidate, key) == 1, nil
}
type params struct {
memory uint32
iterations uint32
parallelism uint8
}
func parse(encoded string) (params, []byte, []byte, error) {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
return params{}, nil, nil, ErrInvalidHash
}
if parts[2] != fmt.Sprintf("v=%d", argon2.Version) {
return params{}, nil, nil, ErrInvalidHash
}
var p params
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.memory, &p.iterations, &p.parallelism); err != nil {
return params{}, nil, nil, ErrInvalidHash
}
if p.memory < 8*1024 || p.memory > 256*1024 || p.iterations < 1 || p.iterations > 10 || p.parallelism < 1 || p.parallelism > 16 {
return params{}, nil, nil, ErrInvalidHash
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil || len(salt) < 8 || len(salt) > 64 {
return params{}, nil, nil, ErrInvalidHash
}
key, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil || len(key) < 16 || len(key) > 64 {
return params{}, nil, nil, ErrInvalidHash
}
return p, salt, key, nil
}
+102
View File
@@ -0,0 +1,102 @@
package auth
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
)
// tokenBytes gives 256 bits of entropy, the contract minimum. The token is an
// opaque value: it is not a username, a UUID or a JWT.
const tokenBytes = 32
// NewToken returns a URL-safe opaque session token.
func NewToken() (string, error) {
raw := make([]byte, tokenBytes)
if _, err := rand.Read(raw); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(raw), nil
}
// TokenHash is the only representation of a token that is persisted. A cache
// dump therefore does not contain bearer credentials usable against the API.
func TokenHash(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
// ValidTokenShape rejects absurd header values before hashing. The check is a
// superset of the 43-character tokens this server issues, so token rotation
// remains possible without rejecting old values early.
func ValidTokenShape(token string) bool {
if len(token) < 16 || len(token) > 128 {
return false
}
for i := 0; i < len(token); i++ {
c := token[i]
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' {
continue
}
return false
}
return true
}
// ErrMalformedBasic is returned for anything that is not a well-formed
// RFC 7617 Basic credential. Callers must answer with the same 401 as a
// wrong password.
var ErrMalformedBasic = errors.New("malformed basic credentials")
// ParseBasic decodes an Authorization header of the form "Basic base64(user:pass)".
// The password may contain colons and arbitrary UTF-8; only the first colon
// separates the username.
func ParseBasic(header string) (username, password string, err error) {
const scheme = "basic"
trimmed := header
if len(trimmed) < len(scheme)+1 || !equalFoldASCII(trimmed[:len(scheme)], scheme) || trimmed[len(scheme)] != ' ' {
return "", "", ErrMalformedBasic
}
encoded := trimmed[len(scheme)+1:]
if encoded == "" || len(encoded) > 1024 {
return "", "", ErrMalformedBasic
}
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
// Some clients omit the RFC 4648 padding. Accept the unpadded form as
// well, but never fall back to a different alphabet.
decoded, err = base64.RawStdEncoding.DecodeString(encoded)
if err != nil {
return "", "", ErrMalformedBasic
}
}
separator := -1
for i := 0; i < len(decoded); i++ {
if decoded[i] == ':' {
separator = i
break
}
}
if separator < 0 {
return "", "", ErrMalformedBasic
}
return string(decoded[:separator]), string(decoded[separator+1:]), nil
}
func equalFoldASCII(value, lower string) bool {
if len(value) != len(lower) {
return false
}
for i := 0; i < len(value); i++ {
c := value[i]
if c >= 'A' && c <= 'Z' {
c += 'a' - 'A'
}
if c != lower[i] {
return false
}
}
return true
}
+375
View File
@@ -0,0 +1,375 @@
// Package config loads the explicit runtime configuration of the lab3
// messenger. The container image stays immutable: the same image is configured
// through environment variables (or files referenced by *_FILE variables for
// operators that do not want secrets in the environment).
package config
import (
"fmt"
"log/slog"
"os"
"strconv"
"strings"
"time"
)
const (
// DefaultSessionTTL is the contract default of contracts/README.md.
DefaultSessionTTL = time.Hour
// MaxShutdownTimeout leaves headroom below the 10 second termination
// window promised by the previous lab and expected by the container
// checks, even if an operator overrides the environment variable.
MaxShutdownTimeout = 9 * time.Second
// MaxStartupTimeout bounds the initial PostgreSQL connectivity wait.
MaxStartupTimeout = 120 * time.Second
)
// Config is validated at startup. The process refuses to start with an
// invalid value instead of silently falling back to a different security or
// durability posture.
type Config struct {
Host string
Port int
Env string
LogLevel slog.Level
ShutdownTimeout time.Duration
ShutdownDrain time.Duration
StartupTimeout time.Duration
MetricsAddr string
DatabaseURL string
CacheURL string
SessionTTL time.Duration
DBMaxConns int32
DBMinConns int32
DBConnectTimeout time.Duration
DBStatementTimeout time.Duration
QueryTimeout time.Duration
CachePoolSize int
CacheTimeout time.Duration
S3Endpoint string
S3Region string
S3Bucket string
S3AccessKey string
S3SecretKey string
S3Timeout time.Duration
MaxUploadBytes int64
MaxImagePixels int64
DecodeConcurrency int
PutConcurrency int
TempDir string
}
// Load reads and validates the full API configuration.
func Load() (Config, error) { return load(true, true) }
// LoadMigrate loads only what the one-shot migration command needs.
func LoadMigrate() (Config, error) { return load(false, false) }
// LoadTool loads the database and S3 configuration used by the offline
// reconciler and the bucket/test tools; Valkey is not required.
func LoadTool() (Config, error) { return load(false, true) }
// load is the shared parser. requireCache and requireS3 select which optional
// dependency blocks are mandatory for the calling command.
func load(requireCache, requireS3 bool) (Config, error) {
cfg := Config{
Host: envString("APP_HOST", "0.0.0.0"),
Env: envString("APP_ENV", "lab"),
ShutdownTimeout: 6 * time.Second,
ShutdownDrain: 3 * time.Second,
StartupTimeout: 30 * time.Second,
QueryTimeout: 3 * time.Second,
MetricsAddr: envString("METRICS_ADDR", "127.0.0.1:9090"),
}
port, err := envInt("APP_PORT", 8080)
if err != nil {
return Config{}, fmt.Errorf("APP_PORT: %w", err)
}
if port < 1 || port > 65535 {
return Config{}, fmt.Errorf("APP_PORT: must be between 1 and 65535")
}
cfg.Port = port
level, err := parseLogLevel(envString("LOG_LEVEL", "info"))
if err != nil {
return Config{}, fmt.Errorf("LOG_LEVEL: %w", err)
}
cfg.LogLevel = level
if strings.TrimSpace(cfg.Host) == "" {
return Config{}, fmt.Errorf("APP_HOST: must not be empty")
}
databaseURL, err := secret("DATABASE_URL")
if err != nil {
return Config{}, err
}
cfg.DatabaseURL = databaseURL
if requireCache {
cacheURL, err := secret("CACHE_URL")
if err != nil {
return Config{}, err
}
cfg.CacheURL = cacheURL
}
seconds, err := envInt("SESSION_TTL_SECONDS", int(DefaultSessionTTL/time.Second))
if err != nil {
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS: %w", err)
}
if seconds < 1 || seconds > 30*24*60*60 {
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS: must be between 1 and 2592000")
}
cfg.SessionTTL = time.Duration(seconds) * time.Second
maxConns, err := envInt("DB_MAX_CONNS", 8)
if err != nil {
return Config{}, fmt.Errorf("DB_MAX_CONNS: %w", err)
}
if maxConns < 1 || maxConns > 100 {
return Config{}, fmt.Errorf("DB_MAX_CONNS: must be between 1 and 100")
}
cfg.DBMaxConns = int32(maxConns)
minConns, err := envInt("DB_MIN_CONNS", 1)
if err != nil {
return Config{}, fmt.Errorf("DB_MIN_CONNS: %w", err)
}
if minConns < 0 || minConns > maxConns {
return Config{}, fmt.Errorf("DB_MIN_CONNS: must be between 0 and DB_MAX_CONNS")
}
cfg.DBMinConns = int32(minConns)
if cfg.DBConnectTimeout, err = envDurationSeconds("DB_CONNECT_TIMEOUT_SECONDS", 3, 1, 30); err != nil {
return Config{}, err
}
if cfg.DBStatementTimeout, err = envDurationSeconds("DB_STATEMENT_TIMEOUT_SECONDS", 3, 1, 60); err != nil {
return Config{}, err
}
if cfg.QueryTimeout, err = envDurationSeconds("DB_QUERY_TIMEOUT_SECONDS", 3, 1, 60); err != nil {
return Config{}, err
}
cachePool, err := envInt("CACHE_POOL_SIZE", 8)
if err != nil {
return Config{}, fmt.Errorf("CACHE_POOL_SIZE: %w", err)
}
if cachePool < 1 || cachePool > 100 {
return Config{}, fmt.Errorf("CACHE_POOL_SIZE: must be between 1 and 100")
}
cfg.CachePoolSize = cachePool
if cfg.CacheTimeout, err = envDurationSeconds("CACHE_TIMEOUT_SECONDS", 2, 1, 30); err != nil {
return Config{}, err
}
shutdown, err := envDurationSeconds("SHUTDOWN_TIMEOUT_SECONDS", 6, 1, 60)
if err != nil {
return Config{}, err
}
if shutdown > MaxShutdownTimeout {
shutdown = MaxShutdownTimeout
}
cfg.ShutdownTimeout = shutdown
drain, err := envDurationSeconds("SHUTDOWN_DRAIN_SECONDS", 3, 0, 8)
if err != nil {
return Config{}, err
}
// The drain must finish before the hard shutdown window; otherwise a
// SIGTERM could spend the whole grace period advertising readiness and
// never reach http.Server.Shutdown.
if drain >= shutdown {
return Config{}, fmt.Errorf("SHUTDOWN_DRAIN_SECONDS must be smaller than SHUTDOWN_TIMEOUT_SECONDS")
}
cfg.ShutdownDrain = drain
startup, err := envDurationSeconds("STARTUP_TIMEOUT_SECONDS", 30, 1, 120)
if err != nil {
return Config{}, err
}
cfg.StartupTimeout = startup
if requireS3 {
if err := loadS3(&cfg); err != nil {
return Config{}, err
}
}
return cfg, nil
}
// loadS3 parses the private object store configuration and the image limits
// that must be enforced before any unbounded read or decode.
func loadS3(cfg *Config) error {
endpoint, err := secret("S3_ENDPOINT")
if err != nil {
return err
}
cfg.S3Endpoint = endpoint
cfg.S3Region = envString("S3_REGION", "us-east-1")
cfg.S3Bucket = envString("S3_BUCKET", "messenger-attachments")
if !validBucketName(cfg.S3Bucket) {
return fmt.Errorf("S3_BUCKET: must match [a-z0-9][a-z0-9.-]{1,61}[a-z0-9]")
}
accessKey, err := secret("S3_ACCESS_KEY")
if err != nil {
return err
}
secretKey, err := secret("S3_SECRET_KEY")
if err != nil {
return err
}
cfg.S3AccessKey = accessKey
cfg.S3SecretKey = secretKey
timeout, err := envDurationSeconds("S3_TIMEOUT_SECONDS", 10, 5, 120)
if err != nil {
return err
}
cfg.S3Timeout = timeout
maxUpload, err := envInt64("MAX_UPLOAD_BYTES", 10*1024*1024)
if err != nil {
return fmt.Errorf("MAX_UPLOAD_BYTES: %w", err)
}
if maxUpload < 1 || maxUpload > 10*1024*1024 {
return fmt.Errorf("MAX_UPLOAD_BYTES: must be between 1 and 10485760")
}
cfg.MaxUploadBytes = maxUpload
maxPixels, err := envInt64("MAX_IMAGE_PIXELS", 40_000_000)
if err != nil {
return fmt.Errorf("MAX_IMAGE_PIXELS: %w", err)
}
if maxPixels < 1 || maxPixels > 40_000_000 {
return fmt.Errorf("MAX_IMAGE_PIXELS: must be between 1 and 40000000")
}
cfg.MaxImagePixels = maxPixels
concurrency, err := envInt("UPLOAD_DECODE_CONCURRENCY", 1)
if err != nil {
return fmt.Errorf("UPLOAD_DECODE_CONCURRENCY: %w", err)
}
if concurrency < 1 || concurrency > 4 {
return fmt.Errorf("UPLOAD_DECODE_CONCURRENCY: must be between 1 and 4")
}
cfg.DecodeConcurrency = concurrency
// The single-node SeaweedFS stand was verified stable at one concurrent
// PUT per API replica; two concurrent multi-megabyte writes could restart
// it. Uploads queue after their body was already streamed to a bounded
// temporary file, so queuing does not add unbounded RAM.
putConcurrency, err := envInt("S3_PUT_CONCURRENCY", 1)
if err != nil {
return fmt.Errorf("S3_PUT_CONCURRENCY: %w", err)
}
if putConcurrency != 1 {
return fmt.Errorf("S3_PUT_CONCURRENCY: must be 1 on this single-node stand")
}
cfg.PutConcurrency = putConcurrency
cfg.TempDir = envString("UPLOAD_TEMP_DIR", "")
return nil
}
func validBucketName(value string) bool {
if len(value) < 3 || len(value) > 63 {
return false
}
for i := 0; i < len(value); i++ {
c := value[i]
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '-' {
continue
}
return false
}
return value[0] != '.' && value[0] != '-' && value[len(value)-1] != '.' && value[len(value)-1] != '-'
}
// secret resolves NAME or NAME_FILE. A file is preferred when both are set so
// compose-style file secrets win over inherited environment values. Values are
// never echoed in error messages.
func secret(name string) (string, error) {
if path := strings.TrimSpace(os.Getenv(name + "_FILE")); path != "" {
data, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("%s_FILE: cannot read referenced file", name)
}
value := strings.TrimSpace(string(data))
if value == "" {
return "", fmt.Errorf("%s_FILE: referenced file is empty", name)
}
return value, nil
}
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
return value, nil
}
return "", fmt.Errorf("%s or %s_FILE is required", name, name)
}
func envString(key, fallback string) string {
// An environment variable set to an empty string is treated as unset; this
// keeps container defaults working when compose passes "" for an optional
// setting.
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
return value
}
return fallback
}
func envInt(key string, fallback int) (int, error) {
raw, ok := os.LookupEnv(key)
if !ok || strings.TrimSpace(raw) == "" {
return fallback, nil
}
value, err := strconv.Atoi(strings.TrimSpace(raw))
if err != nil {
return 0, fmt.Errorf("expected an integer, got %q", raw)
}
return value, nil
}
func envInt64(key string, fallback int64) (int64, error) {
raw, ok := os.LookupEnv(key)
if !ok || strings.TrimSpace(raw) == "" {
return fallback, nil
}
value, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64)
if err != nil {
return 0, fmt.Errorf("expected an integer, got %q", raw)
}
return value, nil
}
func envDurationSeconds(key string, fallback, minimum, maximum int) (time.Duration, error) {
value, err := envInt(key, fallback)
if err != nil {
return 0, fmt.Errorf("%s: %w", key, err)
}
if value < minimum || value > maximum {
return 0, fmt.Errorf("%s: must be between %d and %d", key, minimum, maximum)
}
return time.Duration(value) * time.Second, nil
}
func parseLogLevel(raw string) (slog.Level, error) {
switch strings.ToLower(strings.TrimSpace(raw)) {
case "debug":
return slog.LevelDebug, nil
case "info":
return slog.LevelInfo, nil
case "warn", "warning":
return slog.LevelWarn, nil
case "error":
return slog.LevelError, nil
default:
return 0, fmt.Errorf("expected debug, info, warn or error, got %q", raw)
}
}
+178
View File
@@ -0,0 +1,178 @@
package config
import (
"os"
"path/filepath"
"testing"
"time"
)
var allKeys = []string{
"APP_HOST", "APP_PORT", "APP_ENV", "LOG_LEVEL", "SESSION_TTL_SECONDS",
"DB_MAX_CONNS", "DB_MIN_CONNS", "DB_CONNECT_TIMEOUT_SECONDS",
"DB_STATEMENT_TIMEOUT_SECONDS", "DB_QUERY_TIMEOUT_SECONDS",
"CACHE_POOL_SIZE", "CACHE_TIMEOUT_SECONDS", "SHUTDOWN_TIMEOUT_SECONDS",
"STARTUP_TIMEOUT_SECONDS", "DATABASE_URL", "DATABASE_URL_FILE",
"CACHE_URL", "CACHE_URL_FILE",
"S3_ENDPOINT", "S3_ENDPOINT_FILE", "S3_REGION", "S3_BUCKET",
"S3_ACCESS_KEY", "S3_ACCESS_KEY_FILE", "S3_SECRET_KEY", "S3_SECRET_KEY_FILE",
"S3_TIMEOUT_SECONDS", "MAX_UPLOAD_BYTES", "MAX_IMAGE_PIXELS",
"UPLOAD_DECODE_CONCURRENCY", "S3_PUT_CONCURRENCY", "UPLOAD_TEMP_DIR",
}
func clearEnvironment(t *testing.T) {
t.Helper()
for _, key := range allKeys {
t.Setenv(key, "")
}
}
func baseEnvironment(t *testing.T) {
t.Helper()
clearEnvironment(t)
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres:5432/db?sslmode=disable")
t.Setenv("CACHE_URL", "redis://:pass@valkey:6379/0")
t.Setenv("S3_ENDPOINT", "http://s3:8333")
t.Setenv("S3_BUCKET", "messenger-attachments")
t.Setenv("S3_ACCESS_KEY", "local-test-access")
t.Setenv("S3_SECRET_KEY", "local-test-secret")
}
func TestLoadDefaults(t *testing.T) {
baseEnvironment(t)
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Port != 8080 || cfg.SessionTTL != time.Hour {
t.Fatalf("unexpected defaults: %+v", cfg)
}
if cfg.DBMaxConns != 8 || cfg.DBMinConns != 1 || cfg.QueryTimeout != 3*time.Second {
t.Fatalf("unexpected pool defaults: %+v", cfg)
}
if cfg.MaxUploadBytes != 10*1024*1024 || cfg.MaxImagePixels != 40_000_000 || cfg.DecodeConcurrency != 1 {
t.Fatalf("unexpected upload defaults: %+v", cfg)
}
if cfg.S3Bucket != "messenger-attachments" || cfg.S3Region != "us-east-1" {
t.Fatalf("unexpected S3 defaults: %+v", cfg)
}
}
func TestLoadReadsSecretsFromFiles(t *testing.T) {
clearEnvironment(t)
directory := t.TempDir()
databaseFile := filepath.Join(directory, "database_url")
cacheFile := filepath.Join(directory, "cache_url")
if err := os.WriteFile(databaseFile, []byte("postgres://file:secret@postgres/db\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(cacheFile, []byte("redis://:file-secret@valkey:6379/0\n"), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("DATABASE_URL_FILE", databaseFile)
t.Setenv("CACHE_URL_FILE", cacheFile)
t.Setenv("S3_ENDPOINT", "http://s3:8333")
t.Setenv("S3_ACCESS_KEY", "file-test-access")
t.Setenv("S3_SECRET_KEY", "file-test-secret")
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.DatabaseURL != "postgres://file:secret@postgres/db" {
t.Fatalf("database URL was not read from file: %q", cfg.DatabaseURL)
}
if cfg.CacheURL != "redis://:file-secret@valkey:6379/0" {
t.Fatalf("cache URL was not read from file: %q", cfg.CacheURL)
}
}
func TestLoadRejectsInvalidValues(t *testing.T) {
cases := []struct {
name string
key string
value string
}{
{"zero ttl", "SESSION_TTL_SECONDS", "0"},
{"huge ttl", "SESSION_TTL_SECONDS", "99999999"},
{"zero port", "APP_PORT", "0"},
{"bad log level", "LOG_LEVEL", "verbose"},
{"zero max conns", "DB_MAX_CONNS", "0"},
{"min above max", "DB_MIN_CONNS", "9"},
{"bad timeout", "DB_QUERY_TIMEOUT_SECONDS", "0"},
{"bad int", "APP_PORT", "eighty"},
{"upload above contract", "MAX_UPLOAD_BYTES", "10485761"},
{"pixels above contract", "MAX_IMAGE_PIXELS", "40000001"},
{"zero decode concurrency", "UPLOAD_DECODE_CONCURRENCY", "0"},
{"zero put concurrency", "S3_PUT_CONCURRENCY", "0"},
{"unsafe put concurrency", "S3_PUT_CONCURRENCY", "2"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
baseEnvironment(t)
t.Setenv(tc.key, tc.value)
if _, err := Load(); err == nil {
t.Fatalf("Load accepted %s=%q", tc.key, tc.value)
}
})
}
}
func TestLoadRequiresDatabaseAndCacheURLs(t *testing.T) {
clearEnvironment(t)
if _, err := Load(); err == nil {
t.Fatal("Load accepted missing DATABASE_URL/CACHE_URL")
}
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres/db")
if _, err := Load(); err == nil {
t.Fatal("Load accepted missing CACHE_URL")
}
}
func TestLoadRequiresS3Configuration(t *testing.T) {
baseEnvironment(t)
t.Setenv("S3_ACCESS_KEY", "")
if _, err := Load(); err == nil {
t.Fatal("Load accepted missing S3_ACCESS_KEY")
}
t.Setenv("S3_ACCESS_KEY", "local-test-access")
t.Setenv("S3_BUCKET", "Invalid_Bucket")
if _, err := Load(); err == nil {
t.Fatal("Load accepted an invalid S3 bucket name")
}
}
func TestMigrateConfigurationDoesNotRequireCacheOrS3(t *testing.T) {
clearEnvironment(t)
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres:5432/db?sslmode=disable")
cfg, err := LoadMigrate()
if err != nil {
t.Fatalf("LoadMigrate: %v", err)
}
if cfg.DatabaseURL == "" || cfg.CacheURL != "" || cfg.S3Endpoint != "" {
t.Fatalf("unexpected migrate configuration: %+v", cfg)
}
}
func TestShutdownTimeoutIsClamped(t *testing.T) {
baseEnvironment(t)
t.Setenv("SHUTDOWN_TIMEOUT_SECONDS", "60")
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.ShutdownTimeout != MaxShutdownTimeout {
t.Fatalf("shutdown timeout = %v, want clamp to %v", cfg.ShutdownTimeout, MaxShutdownTimeout)
}
}
func TestSecretFileErrorsDoNotLeakThePath(t *testing.T) {
clearEnvironment(t)
t.Setenv("DATABASE_URL_FILE", "/nonexistent/path/database_url")
_, err := Load()
if err == nil {
t.Fatal("Load accepted a missing secret file")
}
if got := err.Error(); got != "DATABASE_URL_FILE: cannot read referenced file" {
t.Fatalf("error leaks path: %q", got)
}
}
+119
View File
@@ -0,0 +1,119 @@
// Package cursor implements the opaque keyset cursor of the contract. A cursor
// carries the last item already returned; the next page asks PostgreSQL for
// rows strictly after (created_at, id). Cursors are bound to the endpoint and,
// for message history, to the chat that issued them.
package cursor
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"io"
"time"
"mtusi.ru/messenger-lab4/internal/model"
"mtusi.ru/messenger-lab4/internal/uuid"
)
const (
ScopeChats = "chats"
ScopeMessages = "messages"
version = 1
maxCursorSize = 512
)
// ErrInvalid is returned for malformed, tampered or out-of-scope cursors. The
// HTTP layer maps it to 400 invalid_request.
var ErrInvalid = errors.New("invalid cursor")
// Cursor is the decoded keyset position.
type Cursor struct {
At time.Time
ID string
ChatID string
}
// Encoding of the wire form. Time is an RFC 3339 timestamp with UTC Z and
// microsecond precision, matching PostgreSQL timestamptz. It is never used as
// an identifier on its own.
type wire struct {
Version int `json:"v"`
Scope string `json:"s"`
ChatID string `json:"c,omitempty"`
Time string `json:"t"`
ID string `json:"i"`
}
// ForChat encodes the position of the last returned chat.
func ForChat(chat model.Chat) string {
return encode(wire{Scope: ScopeChats, Time: chat.CreatedAt.UTC().Format(time.RFC3339Nano), ID: chat.ID})
}
// ForMessage encodes the position of the last returned message.
func ForMessage(message model.Message) string {
return encode(wire{
Scope: ScopeMessages,
ChatID: message.ChatID,
Time: message.CreatedAt.UTC().Format(time.RFC3339Nano),
ID: message.ID,
})
}
// Decode validates a cursor for the expected scope. chatID is required for the
// messages scope and must be empty for the chats scope.
func Decode(raw, scope, chatID string) (Cursor, error) {
if raw == "" || len(raw) > maxCursorSize {
return Cursor{}, ErrInvalid
}
data, err := base64.RawURLEncoding.DecodeString(raw)
if err != nil {
return Cursor{}, ErrInvalid
}
var value wire
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&value); err != nil {
return Cursor{}, ErrInvalid
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
return Cursor{}, ErrInvalid
}
if value.Version != version || value.Scope != scope {
return Cursor{}, ErrInvalid
}
at, err := time.Parse(time.RFC3339Nano, value.Time)
if err != nil || at.IsZero() || at.Location() != time.UTC {
return Cursor{}, ErrInvalid
}
normalizedID, ok := uuid.Normalize(value.ID)
if !ok || normalizedID != value.ID {
return Cursor{}, ErrInvalid
}
switch scope {
case ScopeChats:
if value.ChatID != "" {
return Cursor{}, ErrInvalid
}
return Cursor{At: at, ID: normalizedID}, nil
case ScopeMessages:
normalizedChat, ok := uuid.Normalize(value.ChatID)
if !ok || normalizedChat != value.ChatID || normalizedChat != chatID {
return Cursor{}, ErrInvalid
}
return Cursor{At: at, ID: normalizedID, ChatID: normalizedChat}, nil
default:
return Cursor{}, ErrInvalid
}
}
func encode(value wire) string {
value.Version = version
data, err := json.Marshal(value)
if err != nil {
panic("encode cursor: " + err.Error())
}
return base64.RawURLEncoding.EncodeToString(data)
}
+97
View File
@@ -0,0 +1,97 @@
package cursor
import (
"encoding/base64"
"encoding/json"
"strings"
"testing"
"time"
"mtusi.ru/messenger-lab4/internal/model"
)
func TestChatCursorRoundTrip(t *testing.T) {
at := time.Date(2026, 11, 30, 12, 34, 56, 123456000, time.UTC)
chat := model.Chat{
ID: "11111111-2222-4333-8444-555555555555",
Title: "chat",
MemberIDs: []string{"11111111-2222-4333-8444-555555555555"},
CreatedAt: model.Time{Time: at},
}
raw := ForChat(chat)
decoded, err := Decode(raw, ScopeChats, "")
if err != nil {
t.Fatalf("Decode: %v", err)
}
if !decoded.At.Equal(at) || decoded.ID != chat.ID || decoded.ChatID != "" {
t.Fatalf("decoded = %+v", decoded)
}
}
func TestMessageCursorIsBoundToChat(t *testing.T) {
at := time.Now().UTC().Truncate(time.Microsecond)
chatID := "11111111-2222-4333-8444-555555555555"
message := model.Message{
ID: "99999999-2222-4333-8444-555555555555",
ChatID: chatID,
SenderID: "11111111-2222-4333-8444-555555555555",
Text: "hello",
CreatedAt: model.Time{Time: at},
}
raw := ForMessage(message)
if _, err := Decode(raw, ScopeMessages, chatID); err != nil {
t.Fatalf("Decode(same chat): %v", err)
}
if _, err := Decode(raw, ScopeMessages, "22222222-2222-4333-8444-555555555555"); err == nil {
t.Fatal("cursor was accepted for another chat")
}
if _, err := Decode(raw, ScopeChats, ""); err == nil {
t.Fatal("message cursor was accepted by the chats scope")
}
}
func TestDecodeRejectsTamperedCursors(t *testing.T) {
at := time.Now().UTC().Truncate(time.Microsecond)
valid := wire{
Version: version,
Scope: ScopeMessages,
ChatID: "11111111-2222-4333-8444-555555555555",
Time: at.Format(time.RFC3339Nano),
ID: "99999999-2222-4333-8444-555555555555",
}
tampered := []wire{
{Version: 2, Scope: valid.Scope, ChatID: valid.ChatID, Time: valid.Time, ID: valid.ID},
{Version: version, Scope: ScopeChats, ChatID: valid.ChatID, Time: valid.Time, ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: "", Time: valid.Time, ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: "not-a-uuid", Time: valid.Time, ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: "2026-11-30T12:00:00+03:00", ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: "yesterday", ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: valid.Time, ID: "not-a-uuid"},
}
for i, value := range tampered {
data, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
raw := base64.RawURLEncoding.EncodeToString(data)
if _, err := Decode(raw, ScopeMessages, valid.ChatID); err == nil {
t.Fatalf("tampered cursor %d was accepted", i)
}
}
withExtra, _ := json.Marshal(map[string]any{
"v": version, "s": ScopeMessages, "c": valid.ChatID,
"t": valid.Time, "i": valid.ID, "x": 1,
})
if _, err := Decode(base64.RawURLEncoding.EncodeToString(withExtra), ScopeMessages, valid.ChatID); err == nil {
t.Fatal("cursor with an unknown field was accepted")
}
}
func TestDecodeRejectsGarbage(t *testing.T) {
for _, raw := range []string{"", "!!!", base64.RawURLEncoding.EncodeToString([]byte("not json")), strings.Repeat("a", 600)} {
if _, err := Decode(raw, ScopeChats, ""); err == nil {
t.Fatalf("Decode accepted %q", raw)
}
}
}
+99
View File
@@ -0,0 +1,99 @@
// Package model holds the public JSON shapes of the lab3 contract. They are
// deliberately separate from the database scan helpers so an accidental new
// column cannot silently become an API field.
package model
import "time"
// Time marshals an RFC 3339 UTC timestamp with exactly six fractional digits.
// Go's default time.Time JSON encoder trims trailing zeros, which produces
// 3-5 digit fractions that some Python 3.9 datetime parsers (used by the
// public test client) reject. A fixed microsecond precision matches
// PostgreSQL timestamptz and stays valid RFC 3339.
type Time struct{ time.Time }
const timestampLayout = "2006-01-02T15:04:05.000000Z"
// MarshalJSON implements json.Marshaler.
func (t Time) MarshalJSON() ([]byte, error) {
return []byte(`"` + t.UTC().Format(timestampLayout) + `"`), nil
}
// User is the public user shape. It never contains a password hash or session
// data.
type User struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt Time `json:"created_at"`
}
// Chat is the public chat shape. MemberIDs preserves the order supplied at
// creation; membership is immutable in the mandatory lab3 API.
type Chat struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt Time `json:"created_at"`
}
// Message is the public message shape. SenderID always comes from the server
// session, never from the request body. AttachmentIDs is always a JSON array,
// never null, and preserves the order supplied by the client.
type Message struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt Time `json:"created_at"`
AttachmentIDs []string `json:"attachment_ids"`
}
// Variant is the public derivative shape. Lab4 never creates variants, so
// every Attachment carries an empty array; the schema is kept for lab5.
type Variant struct {
Name string `json:"name"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
Width int `json:"width"`
Height int `json:"height"`
SHA256 string `json:"sha256"`
}
// Attachment is the public metadata shape. Object keys, bucket names and
// storage credentials are deliberately absent: they are server-side details.
type Attachment struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []Variant `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt Time `json:"created_at"`
UpdatedAt Time `json:"updated_at"`
}
// ChatPage is one keyset page of accessible chats.
type ChatPage struct {
Items []Chat `json:"items"`
NextCursor *string `json:"next_cursor"`
}
// MessagePage is one keyset page of a chat history.
type MessagePage struct {
Items []Message `json:"items"`
NextCursor *string `json:"next_cursor"`
}
// Session is the login response. Token is only ever written to the response
// body, never to logs or PostgreSQL.
type Session struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt Time `json:"expires_at"`
User User `json:"user"`
}
+50
View File
@@ -0,0 +1,50 @@
package model
import (
"encoding/json"
"strings"
"testing"
"time"
)
func TestTimeMarshalUsesFixedMicroseconds(t *testing.T) {
value := Time{Time: time.Date(2026, 11, 30, 12, 0, 0, 120000000, time.UTC)}
data, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
got := string(data)
// .120000 would be trimmed to .12 by the default encoder; the public
// Python 3.9 client requires 3 or 6 fractional digits.
if got != `"2026-11-30T12:00:00.120000Z"` {
t.Fatalf("marshal = %s", got)
}
if !strings.HasSuffix(got, "Z\"") {
t.Fatal("timestamp does not end in Z")
}
}
func TestUserJSONHasOnlyPublicFields(t *testing.T) {
user := User{
ID: "11111111-2222-4333-8444-555555555555",
Username: "alice",
DisplayName: "Алиса",
CreatedAt: Time{Time: time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)},
}
data, err := json.Marshal(user)
if err != nil {
t.Fatal(err)
}
var fields map[string]any
if err := json.Unmarshal(data, &fields); err != nil {
t.Fatal(err)
}
if len(fields) != 4 {
t.Fatalf("user JSON has unexpected fields: %v", fields)
}
for _, forbidden := range []string{"password", "password_hash", "token", "token_hash"} {
if _, present := fields[forbidden]; present {
t.Fatalf("user JSON leaks %q", forbidden)
}
}
}
+294
View File
@@ -0,0 +1,294 @@
// Package objectstore is the S3 adapter. PostgreSQL stores attachment
// metadata; this package stores and streams the original bytes. No handler
// talks to the S3 SDK directly, so error classification and timeouts are in one
// place.
package objectstore
import (
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
var (
// ErrNotFound means the object (or a prerequisite such as the bucket) does
// not exist. The HTTP layer maps it to 404 for an attachment read.
ErrNotFound = errors.New("object not found")
// ErrUnavailable means S3 could not answer. The HTTP layer maps it to 503
// and never to a fabricated success.
ErrUnavailable = errors.New("object store unavailable")
)
// Config is the validated S3 connection. Credentials are never logged.
type Config struct {
Endpoint string
Region string
Bucket string
AccessKey string
SecretKey string
Timeout time.Duration
}
// Store is a thin, timeout-aware wrapper around minio-go.
type Store struct {
client *minio.Client
bucket string
timeout time.Duration
}
// Open parses S3_ENDPOINT as a scheme://host:port URL and builds a client. The
// caller must have validated that every field is non-empty.
func Open(cfg Config) (*Store, error) {
parsed, err := url.Parse(strings.TrimSpace(cfg.Endpoint))
if err != nil || parsed.Host == "" {
return nil, errors.New("S3_ENDPOINT must be an http(s) URL with a host")
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return nil, errors.New("S3_ENDPOINT scheme must be http or https")
}
if parsed.Path != "" && parsed.Path != "/" {
return nil, errors.New("S3_ENDPOINT must not contain a path")
}
if cfg.Timeout <= 0 {
cfg.Timeout = 30 * time.Second
}
transport := &http.Transport{
Proxy: nil,
DialContext: (&net.Dialer{Timeout: 3 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
MaxIdleConns: 32,
MaxIdleConnsPerHost: 16,
IdleConnTimeout: 60 * time.Second,
TLSHandshakeTimeout: 5 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
ExpectContinueTimeout: time.Second,
}
client, err := minio.New(parsed.Host, &minio.Options{
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
Secure: parsed.Scheme == "https",
Region: cfg.Region,
BucketLookup: minio.BucketLookupPath,
Transport: transport,
// The HTTP request is synchronous user work. One bounded retry is
// enough; the default exponential retry series would hold an upload
// request open for many seconds when S3 is unreachable.
MaxRetries: 1,
})
if err != nil {
return nil, errors.New("could not create S3 client")
}
return &Store{client: client, bucket: cfg.Bucket, timeout: cfg.Timeout}, nil
}
func (s *Store) opCtx(ctx context.Context) (context.Context, context.CancelFunc) {
return context.WithTimeout(ctx, s.timeout)
}
// Put uploads exactly size bytes with the declared content type. The caller
// has already validated the image; this function does not buffer the body.
func (s *Store) Put(ctx context.Context, key string, body io.Reader, size int64, contentType string) error {
ctx, cancel := s.opCtx(ctx)
defer cancel()
_, err := s.client.PutObject(ctx, s.bucket, key, body, size, minio.PutObjectOptions{
ContentType: contentType,
PartSize: 16 << 20,
NumThreads: 1,
DisableMultipart: size <= 16<<20,
})
if err != nil {
return classify(err)
}
return nil
}
// Get opens the object stream. The caller closes it. A missing object is
// ErrNotFound; an unreachable store is ErrUnavailable.
//
// The operation context must stay alive while the body is read: cancelling it
// when Get returns would abort the HTTP response stream. Close releases both
// the SDK object and its timeout.
//
// Existence and size come from a separate StatObject. Calling Stat on the
// lazily opened Object would make minio-go attach an If-Match ETag to the
// subsequent GET; SeaweedFS 3.98 rejects that conditional read for large
// objects with 412 after the store has been restarted. A plain GET avoids the
// false precondition while the HEAD still lets the handler return 404 before
// it writes response headers.
func (s *Store) Get(ctx context.Context, key string) (io.ReadCloser, ObjectInfo, error) {
ctx, cancel := s.opCtx(ctx)
info, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
if err != nil {
cancel()
return nil, ObjectInfo{}, classify(err)
}
object, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
if err != nil {
cancel()
return nil, ObjectInfo{}, classify(err)
}
return &objectStream{ReadCloser: object, cancel: cancel}, ObjectInfo{
Key: key,
Size: info.Size,
ContentType: info.ContentType,
LastModified: info.LastModified,
}, nil
}
// objectStream ties the S3 read lifetime to Close. The standard S3 response
// is not reusable after Close, and the caller always defers Close.
type objectStream struct {
io.ReadCloser
cancel context.CancelFunc
}
func (s *objectStream) Close() error {
err := s.ReadCloser.Close()
s.cancel()
return err
}
// Stat checks existence without downloading the bytes. It is used by the
// metadata endpoint so a missing object is not reported as a ready attachment.
func (s *Store) Stat(ctx context.Context, key string) (ObjectInfo, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
info, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
if err != nil {
return ObjectInfo{}, classify(err)
}
return ObjectInfo{
Key: key,
Size: info.Size,
ContentType: info.ContentType,
LastModified: info.LastModified,
}, nil
}
// Remove deletes one object. S3 delete is idempotent: a missing key is not an
// error, which makes a repeated reconciler run safe.
func (s *Store) Remove(ctx context.Context, key string) error {
ctx, cancel := s.opCtx(ctx)
defer cancel()
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil {
return classify(err)
}
return nil
}
// ObjectInfo is the subset of S3 metadata the reconciler needs.
type ObjectInfo struct {
Key string
Size int64
ContentType string
LastModified time.Time
}
// List returns every object under prefix. The reconciler uses it once per run;
// the HTTP path never lists the bucket.
func (s *Store) List(ctx context.Context, prefix string) ([]ObjectInfo, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
result := make([]ObjectInfo, 0, 64)
for object := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) {
if object.Err != nil {
return nil, classify(object.Err)
}
result = append(result, ObjectInfo{
Key: object.Key,
Size: object.Size,
ContentType: object.ContentType,
LastModified: object.LastModified,
})
}
return result, nil
}
// EnsureBucket creates the bucket if it is absent. It is safe to run
// concurrently and repeatedly: an already existing bucket is not an error.
// The caller uses administrative credentials; API credentials are not allowed
// to create buckets.
func (s *Store) EnsureBucket(ctx context.Context) (bool, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
exists, err := s.client.BucketExists(ctx, s.bucket)
if err != nil {
return false, classify(err)
}
if exists {
return false, nil
}
if err := s.client.MakeBucket(ctx, s.bucket, minio.MakeBucketOptions{Region: s.region()}); err != nil {
response := minio.ToErrorResponse(err)
switch response.Code {
case "BucketAlreadyOwnedByYou", "BucketAlreadyExists":
return false, nil
}
return false, classify(err)
}
return true, nil
}
func (s *Store) region() string {
// minio-go keeps the region in an unexported field. Passing an empty
// region lets it discover us-east-1 for SeaweedFS; the explicit region is
// still set in the client options for signed requests.
return ""
}
// Probe writes, stats and removes a tiny object. It proves that the configured
// credentials can actually use the private bucket without leaving test data.
func (s *Store) Probe(ctx context.Context) error {
const key = "_bootstrap/probe"
ctx, cancel := s.opCtx(ctx)
defer cancel()
body := strings.NewReader("mtusi-lab4-bucket-probe")
if _, err := s.client.PutObject(ctx, s.bucket, key, body, int64(body.Len()), minio.PutObjectOptions{
ContentType: "text/plain",
PartSize: 5 << 20,
}); err != nil {
return classify(err)
}
if _, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{}); err != nil {
return classify(err)
}
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil {
return classify(err)
}
return nil
}
// classify converts an S3/SDK error into the two dependency classes the HTTP
// layer understands. An access-denied or malformed-bucket error stays a plain
// error and becomes a generic 500: it is a server configuration defect, not a
// user error and not a transient outage.
func classify(err error) error {
if err == nil {
return nil
}
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
var netErr net.Error
if errors.As(err, &netErr) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
response := minio.ToErrorResponse(err)
switch response.Code {
case "NoSuchKey", "NoSuchObject", "NotFound":
return ErrNotFound
case "NoSuchBucket", "SlowDown", "InternalError", "ServiceUnavailable", "XMinioServerNotInitialized":
return fmt.Errorf("%w: %s", ErrUnavailable, response.Code)
}
if response.StatusCode >= 500 {
return fmt.Errorf("%w: HTTP %d", ErrUnavailable, response.StatusCode)
}
return err
}
+151
View File
@@ -0,0 +1,151 @@
// Package session stores opaque server-side sessions in Valkey. The token is
// never persisted: only its SHA-256 hash is used as the cache key, so a cache
// dump does not contain credentials that can be replayed against the API.
//
// Valkey is the source of truth for sessions. It is configured with AOF
// persistence and a named volume, so valid sessions survive both the API
// process and the Valkey process restarting with volumes kept.
package session
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/redis/go-redis/v9"
"mtusi.ru/messenger-lab4/internal/auth"
)
const keyPrefix = "mtusi:lab3:session:"
var (
// ErrInvalid means the token is unknown, expired or malformed.
ErrInvalid = errors.New("invalid session")
// ErrUnavailable means Valkey is not answering; the API must return a
// bounded 503 instead of trusting the bearer token.
ErrUnavailable = errors.New("session store unavailable")
)
type record struct {
UserID string `json:"user_id"`
ExpiresAt time.Time `json:"expires_at"`
}
// Options bound every network operation and the connection pool.
type Options struct {
PoolSize int
DialTimeout time.Duration
IOTimeout time.Duration
TTL time.Duration
}
// Store is a thin, timeout-aware wrapper around go-redis.
type Store struct {
client *redis.Client
ttl time.Duration
}
// Open parses CACHE_URL (redis:// or rediss://) without echoing it in errors.
// It does not require Valkey to be reachable at startup: /health/ready and
// login report the outage as 503.
func Open(rawURL string, options Options) (*Store, error) {
parsed, err := redis.ParseURL(rawURL)
if err != nil {
return nil, errors.New("CACHE_URL is not a valid Redis/Valkey URL")
}
if options.PoolSize <= 0 {
options.PoolSize = 8
}
if options.DialTimeout <= 0 {
options.DialTimeout = 2 * time.Second
}
if options.IOTimeout <= 0 {
options.IOTimeout = 2 * time.Second
}
if options.TTL <= 0 {
options.TTL = time.Hour
}
parsed.PoolSize = options.PoolSize
parsed.DialTimeout = options.DialTimeout
parsed.ReadTimeout = options.IOTimeout
parsed.WriteTimeout = options.IOTimeout
// One retry keeps a transient blip invisible while bounding the worst-case
// time a handler spends waiting for the cache.
parsed.MaxRetries = 1
parsed.MinRetryBackoff = 20 * time.Millisecond
parsed.MaxRetryBackoff = 100 * time.Millisecond
return &Store{client: redis.NewClient(parsed), ttl: options.TTL}, nil
}
// TTL exposes the configured session lifetime (used by tests and startup logs).
func (s *Store) TTL() time.Duration { return s.ttl }
// Create issues a new opaque token and stores the session with a TTL. The
// returned expiry is the absolute instant the client must treat as the end of
// the session; restarting a process does not extend it.
func (s *Store) Create(ctx context.Context, userID string) (token string, expiresAt time.Time, err error) {
token, err = auth.NewToken()
if err != nil {
return "", time.Time{}, fmt.Errorf("generate session token: %w", err)
}
// A whole number of microseconds keeps the value parseable by the
// Python 3.9 public client (its fromisoformat accepts 3 or 6 fractional
// digits, not Go's trimmed nanosecond form) while staying RFC 3339.
expiresAt = time.Now().UTC().Add(s.ttl).Truncate(time.Microsecond)
payload, err := json.Marshal(record{UserID: userID, ExpiresAt: expiresAt})
if err != nil {
return "", time.Time{}, fmt.Errorf("encode session: %w", err)
}
if err := s.client.Set(ctx, key(auth.TokenHash(token)), payload, s.ttl).Err(); err != nil {
return "", time.Time{}, fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return token, expiresAt, nil
}
// Get resolves a token to a user id. Unknown, expired and corrupt records are
// all ErrInvalid; a transport failure is ErrUnavailable.
func (s *Store) Get(ctx context.Context, token string) (string, error) {
raw, err := s.client.Get(ctx, key(auth.TokenHash(token))).Bytes()
if errors.Is(err, redis.Nil) {
return "", ErrInvalid
}
if err != nil {
return "", fmt.Errorf("%w: %w", ErrUnavailable, err)
}
var value record
if err := json.Unmarshal(raw, &value); err != nil || value.UserID == "" {
return "", ErrInvalid
}
if !value.ExpiresAt.After(time.Now()) {
// TTL should already have removed the key; this also covers a clock
// adjustment or an externally imported record.
_ = s.client.Del(ctx, key(auth.TokenHash(token))).Err()
return "", ErrInvalid
}
return value.UserID, nil
}
// Delete revokes the session. Missing keys are not an error here: the caller
// has already authenticated the token, and a concurrent logout is harmless.
func (s *Store) Delete(ctx context.Context, token string) error {
if err := s.client.Del(ctx, key(auth.TokenHash(token))).Err(); err != nil {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return nil
}
// Ping is used by /health/ready and the startup log.
func (s *Store) Ping(ctx context.Context) error {
if err := s.client.Ping(ctx).Err(); err != nil {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return nil
}
// Close releases the connection pool.
func (s *Store) Close() error { return s.client.Close() }
func key(tokenHash string) string { return keyPrefix + tokenHash }
+184
View File
@@ -0,0 +1,184 @@
package store
import (
"context"
"errors"
"time"
"github.com/jackc/pgx/v5"
"mtusi.ru/messenger-lab4/internal/model"
)
// AttachmentRecord is the database view of an attachment. ObjectKey is an
// internal server detail and is never serialised into the public API.
type AttachmentRecord struct {
model.Attachment
ObjectKey string
}
// ReconcileAttachment is the minimal row the offline reconciler needs. It is
// intentionally not an API shape.
type ReconcileAttachment struct {
ID string
ObjectKey string
Status string
CreatedAt time.Time
UpdatedAt time.Time
}
// CreatePendingAttachment records the upload intent before the S3 PUT. If the
// process dies after this insert, the row is still accounted for and the
// reconciler can remove it after the grace period; it is never returned by the
// public API because only ready rows are visible.
func (s *Store) CreatePendingAttachment(ctx context.Context, record AttachmentRecord, createdAt time.Time) error {
ctx, cancel := s.opCtx(ctx)
defer cancel()
_, err := s.pool.Exec(ctx, `
INSERT INTO attachments
(id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
status, error_code, object_key, created_at, updated_at)
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5, $6, $7,
'pending', NULL, $8, $9, $9)`,
record.ID, record.ChatID, record.OwnerID, record.Filename,
record.ContentType, record.SizeBytes, record.SHA256, record.ObjectKey, createdAt,
)
return s.classify(err)
}
// MarkAttachmentReady promotes the pending row after the original bytes are in
// S3. If the update fails, the row stays pending and the object remains
// accounted; the reconciler owns the cleanup. Nothing is deleted here because
// an ambiguous commit must never destroy a successfully stored original.
func (s *Store) MarkAttachmentReady(ctx context.Context, id string, updatedAt time.Time) (time.Time, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var stored time.Time
err := s.pool.QueryRow(ctx, `
UPDATE attachments
SET status = 'ready', updated_at = $2
WHERE id = $1::uuid AND status = 'pending'
RETURNING updated_at`, id, updatedAt).Scan(&stored)
if errors.Is(err, pgx.ErrNoRows) {
return time.Time{}, ErrNotFound
}
if err != nil {
return time.Time{}, s.classify(err)
}
return stored.UTC(), nil
}
// ReadyAttachmentForUser applies the ACL in SQL: the row is returned only when
// the caller is a member of the attachment's chat and the attachment is ready.
// A foreign and a nonexistent attachment are indistinguishable.
func (s *Store) ReadyAttachmentForUser(ctx context.Context, attachmentID, userID string) (AttachmentRecord, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var record AttachmentRecord
var createdAt, updatedAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT a.id::text, a.chat_id::text, a.owner_id::text, a.filename,
a.content_type, a.size_bytes, a.sha256, a.status, a.error_code,
a.object_key, a.created_at, a.updated_at
FROM attachments a
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = $2::uuid
WHERE a.id = $1::uuid AND a.status = 'ready'`,
attachmentID, userID,
).Scan(&record.ID, &record.ChatID, &record.OwnerID, &record.Filename,
&record.ContentType, &record.SizeBytes, &record.SHA256, &record.Status, &record.ErrorCode,
&record.ObjectKey, &createdAt, &updatedAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return AttachmentRecord{}, ErrNotFound
}
return AttachmentRecord{}, s.classify(err)
}
record.CreatedAt = model.Time{Time: createdAt.UTC()}
record.UpdatedAt = model.Time{Time: updatedAt.UTC()}
record.Variants = []model.Variant{}
return record, nil
}
// DeleteAttachmentRow removes a pending upload intent. It is used only after a
// failed S3 PUT or by the reconciler; ready rows are never deleted here.
func (s *Store) DeleteAttachmentRow(ctx context.Context, id string) error {
ctx, cancel := s.opCtx(ctx)
defer cancel()
_, err := s.pool.Exec(ctx, `DELETE FROM attachments WHERE id = $1::uuid`, id)
return s.classify(err)
}
// ListAttachmentsForReconcile returns every row, including internal pending
// upload intents. Only the offline reconciler calls it.
func (s *Store) ListAttachmentsForReconcile(ctx context.Context) ([]ReconcileAttachment, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
rows, err := s.pool.Query(ctx, `
SELECT id::text, object_key, status, created_at, updated_at
FROM attachments
ORDER BY created_at, id`)
if err != nil {
return nil, s.classify(err)
}
defer rows.Close()
result := make([]ReconcileAttachment, 0, 128)
for rows.Next() {
var item ReconcileAttachment
if err := rows.Scan(&item.ID, &item.ObjectKey, &item.Status, &item.CreatedAt, &item.UpdatedAt); err != nil {
return nil, s.classify(err)
}
result = append(result, item)
}
if err := rows.Err(); err != nil {
return nil, s.classify(err)
}
return result, nil
}
// AttachmentByObjectKey reports whether a row still references the key. The
// reconciler re-checks this immediately before deleting an object, so a
// concurrent upload that committed between the snapshot and the delete is not
// destroyed.
func (s *Store) AttachmentByObjectKey(ctx context.Context, key string) (bool, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var exists bool
if err := s.pool.QueryRow(ctx,
`SELECT EXISTS (SELECT 1 FROM attachments WHERE object_key = $1)`, key).Scan(&exists); err != nil {
return false, s.classify(err)
}
return exists, nil
}
// AttachmentState re-reads the status and key before a mutation. A pending row
// that became ready while the reconciler was scanning must not be deleted.
func (s *Store) AttachmentState(ctx context.Context, id string) (string, string, time.Time, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var status, objectKey string
var updatedAt time.Time
err := s.pool.QueryRow(ctx,
`SELECT status, object_key, updated_at FROM attachments WHERE id = $1::uuid`, id,
).Scan(&status, &objectKey, &updatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return "", "", time.Time{}, ErrNotFound
}
if err != nil {
return "", "", time.Time{}, s.classify(err)
}
return status, objectKey, updatedAt.UTC(), nil
}
// DeleteAttachmentIfPending deletes the row only while it is still pending.
// The status predicate is the last line of defence against deleting a row that
// a concurrent request has already promoted to ready.
func (s *Store) DeleteAttachmentIfPending(ctx context.Context, id string) (bool, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
tag, err := s.pool.Exec(ctx,
`DELETE FROM attachments WHERE id = $1::uuid AND status = 'pending'`, id)
if err != nil {
return false, s.classify(err)
}
return tag.RowsAffected() == 1, nil
}
+139
View File
@@ -0,0 +1,139 @@
package store
import (
"context"
"crypto/sha256"
"embed"
"encoding/hex"
"errors"
"fmt"
"io/fs"
"sort"
"strconv"
"strings"
"github.com/jackc/pgx/v5"
)
//go:embed migrations/*.sql
var migrationFiles embed.FS
// advisoryLockKey is a fixed application-wide key. pg_advisory_lock serialises
// concurrent API replicas that start at the same time; it is released when the
// dedicated connection is returned or the session ends.
const advisoryLockKey int64 = 0x6d74756c616233 // "mtulab3"
type migration struct {
version int
name string
checksum string
sql string
}
// Migrate applies every embedded migration exactly once and records its
// checksum. Re-running it is a no-op, which is what the restart hook relies on.
// A changed migration file is a startup error rather than a silent divergence.
func (s *Store) Migrate(ctx context.Context) error {
conn, err := s.pool.Acquire(ctx)
if err != nil {
return s.classify(err)
}
defer conn.Release()
if _, err := conn.Exec(ctx, `SELECT pg_advisory_lock($1)`, advisoryLockKey); err != nil {
return s.classify(err)
}
defer func() {
// Use a background context: the request context may already be
// cancelled when a startup timeout fires, but the lock still has to be
// released explicitly before the connection is returned to the pool.
_, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock($1)`, advisoryLockKey)
}()
if _, err := conn.Exec(ctx, `
CREATE TABLE IF NOT EXISTS schema_migrations (
version integer PRIMARY KEY,
name text NOT NULL,
checksum text NOT NULL,
applied_at timestamptz NOT NULL DEFAULT now()
)`); err != nil {
return s.classify(err)
}
migrations, err := loadMigrations()
if err != nil {
return err
}
for _, item := range migrations {
var existing string
err := conn.QueryRow(ctx, `SELECT checksum FROM schema_migrations WHERE version = $1`, item.version).Scan(&existing)
switch {
case err == nil:
if existing != item.checksum {
return fmt.Errorf("migration %04d_%s was modified after it was applied", item.version, item.name)
}
continue
case !errors.Is(err, pgx.ErrNoRows):
return s.classify(err)
}
tx, err := conn.Begin(ctx)
if err != nil {
return s.classify(err)
}
if _, err := tx.Exec(ctx, item.sql); err != nil {
_ = tx.Rollback(context.Background())
return fmt.Errorf("apply migration %04d_%s: %w", item.version, item.name, err)
}
if _, err := tx.Exec(ctx,
`INSERT INTO schema_migrations (version, name, checksum) VALUES ($1, $2, $3)`,
item.version, item.name, item.checksum,
); err != nil {
_ = tx.Rollback(context.Background())
return s.classify(err)
}
if err := tx.Commit(ctx); err != nil {
return s.classify(err)
}
}
return nil
}
func loadMigrations() ([]migration, error) {
entries, err := fs.ReadDir(migrationFiles, "migrations")
if err != nil {
return nil, err
}
items := make([]migration, 0, len(entries))
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
continue
}
name := entry.Name()
if len(name) < 9 {
return nil, fmt.Errorf("migration %q has no NNNN_ prefix", name)
}
version, err := strconv.Atoi(name[:4])
if err != nil {
return nil, fmt.Errorf("migration %q has no numeric prefix", name)
}
data, err := migrationFiles.ReadFile("migrations/" + name)
if err != nil {
return nil, err
}
sum := sha256.Sum256(data)
items = append(items, migration{
version: version,
name: strings.TrimSuffix(name[5:], ".sql"),
checksum: hex.EncodeToString(sum[:]),
sql: string(data),
})
}
sort.Slice(items, func(i, j int) bool { return items[i].version < items[j].version })
for i := 1; i < len(items); i++ {
if items[i].version == items[i-1].version {
return nil, fmt.Errorf("duplicate migration version %d", items[i].version)
}
}
return items, nil
}
+71
View File
@@ -0,0 +1,71 @@
package store
import (
"strings"
"testing"
)
func TestLoadMigrations(t *testing.T) {
migrations, err := loadMigrations()
if err != nil {
t.Fatalf("loadMigrations: %v", err)
}
if len(migrations) != 5 {
t.Fatalf("loaded %d migrations, want 5", len(migrations))
}
for index, item := range migrations {
if item.version != index+1 {
t.Fatalf("migration order at %d = %d", index, item.version)
}
}
for _, item := range migrations {
if len(item.checksum) != 64 {
t.Fatalf("checksum for %d has length %d", item.version, len(item.checksum))
}
lower := strings.ToLower(item.sql)
if !strings.Contains(lower, "create ") && !strings.Contains(lower, "alter ") {
t.Fatalf("migration %d has no schema statements", item.version)
}
}
// The checksum must be stable across process runs: it is what detects an
// edited migration after it has been applied.
again, err := loadMigrations()
if err != nil {
t.Fatal(err)
}
for index := range migrations {
if migrations[index].checksum != again[index].checksum {
t.Fatal("migration checksums are not deterministic")
}
}
}
func TestMigrationsContainRequiredDomainObjects(t *testing.T) {
migrations, err := loadMigrations()
if err != nil {
t.Fatal(err)
}
all := ""
for _, item := range migrations {
all += item.sql
}
for _, required := range []string{
"CREATE TABLE users",
"CREATE TABLE chats",
"CREATE TABLE chat_members",
"CREATE TABLE messages",
"CREATE UNIQUE INDEX users_username_key",
"messages_sender_membership_fk",
"messages_chat_created_id_idx",
"CREATE TABLE message_idempotency",
"PRIMARY KEY (user_id, method, path, key)",
"CREATE TABLE attachments",
"CREATE TABLE message_attachments",
"attachments_object_key_unique",
"message_attachments_attachment_chat_fk",
} {
if !strings.Contains(all, required) {
t.Fatalf("migrations do not contain %q", required)
}
}
}
+54
View File
@@ -0,0 +1,54 @@
-- Lab2 schema. PostgreSQL is the source of truth for users, chats, chat
-- membership and messages. Sessions intentionally live in Valkey with a TTL.
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL,
display_name text NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT users_username_format
CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_length
CHECK (char_length(display_name) BETWEEN 1 AND 100),
CONSTRAINT users_password_hash_present
CHECK (length(password_hash) > 0)
);
-- Uniqueness is enforced by the database, not by a read-then-insert check, so
-- two concurrent registrations of the same username cannot both succeed.
CREATE UNIQUE INDEX users_username_key ON users (username);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT chats_title_length
CHECK (char_length(title) BETWEEN 1 AND 100)
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users (id),
position integer NOT NULL,
PRIMARY KEY (chat_id, user_id),
CONSTRAINT chat_members_position_nonnegative CHECK (position >= 0)
);
-- "Chats of the current user" walks chat_members by user_id.
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL,
sender_id uuid NOT NULL,
text text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT messages_text_length
CHECK (char_length(text) BETWEEN 1 AND 4000),
CONSTRAINT messages_chat_fk
FOREIGN KEY (chat_id) REFERENCES chats (id) ON DELETE CASCADE,
-- The sender must be a member of the chat at the database level too, not
-- only in the HTTP handler.
CONSTRAINT messages_sender_membership_fk
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members (chat_id, user_id)
);
@@ -0,0 +1,15 @@
-- Indexes justified by the two keyset queries of the contract.
--
-- Message history:
-- WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
-- ORDER BY created_at, id LIMIT $4
-- The three-column index lets PostgreSQL start at the cursor position inside
-- one chat instead of scanning the whole history for every page.
CREATE INDEX messages_chat_created_id_idx
ON messages (chat_id, created_at, id);
-- Chat list:
-- ORDER BY created_at, id LIMIT $1
-- after joining chat_members for the current user.
CREATE INDEX chats_created_id_idx
ON chats (created_at, id);
@@ -0,0 +1,28 @@
-- Lab3: shared idempotency records for POST /api/v1/chats/{chat_id}/messages.
--
-- The primary key is exactly the contract scope: acting user + HTTP method +
-- chat message path + Idempotency-Key. Different users or chats may reuse the
-- same key independently. request_hash lets a replay distinguish the same
-- semantic body (201 + original message) from a different body (409).
--
-- A row is written in the same transaction as the message it references, so a
-- committed row always has a committed message and an aborted request leaves
-- neither. created_at supports the 24-hour retention prune; contract requires
-- at least 24 h, this stand prunes only records older than that bound.
CREATE TABLE message_idempotency (
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
method text NOT NULL,
path text NOT NULL,
key text NOT NULL,
request_hash bytea NOT NULL,
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, method, path, key),
CONSTRAINT message_idempotency_method_post CHECK (method = 'POST'),
CONSTRAINT message_idempotency_key_length CHECK (char_length(key) BETWEEN 1 AND 128),
CONSTRAINT message_idempotency_path_length CHECK (char_length(path) BETWEEN 1 AND 256)
);
-- Retention housekeeping walks old rows; new inserts stay cheap.
CREATE INDEX message_idempotency_created_at_idx
ON message_idempotency (created_at);
@@ -0,0 +1,75 @@
-- Lab4: attachment metadata lives in PostgreSQL; the original bytes live in
-- the private S3 bucket. The only public state in the mandatory lab4 contract
-- is ready. pending exists solely as an internal, server-side upload intent:
-- it is written before the S3 PUT and promoted in the same request after the
-- PUT. A crash or a database failure between the two steps therefore leaves an
-- accounted row, never an anonymous object. The reconciler removes stale
-- pending rows and their objects after a documented grace period.
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
owner_id uuid NOT NULL REFERENCES users (id),
filename text NOT NULL,
content_type text NOT NULL,
size_bytes bigint NOT NULL,
sha256 text NOT NULL,
status text NOT NULL,
error_code text,
object_key text NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT attachments_filename_length
CHECK (char_length(filename) BETWEEN 1 AND 255),
CONSTRAINT attachments_content_type
CHECK (content_type IN ('image/png', 'image/jpeg')),
CONSTRAINT attachments_size
CHECK (size_bytes BETWEEN 1 AND 10485760),
CONSTRAINT attachments_sha256
CHECK (sha256 ~ '^[a-f0-9]{64}$'),
CONSTRAINT attachments_status
CHECK (status IN ('pending', 'ready')),
CONSTRAINT attachments_ready_error
CHECK ((status = 'ready' AND error_code IS NULL) OR status = 'pending'),
CONSTRAINT attachments_object_key
CHECK (object_key LIKE 'attachments/%'),
CONSTRAINT attachments_object_key_unique UNIQUE (object_key),
-- Referenced by the composite foreign key of message_attachments so the
-- database itself rejects a link to an attachment of another chat.
CONSTRAINT attachments_id_chat_unique UNIQUE (id, chat_id)
);
-- The only attachment query on the hot path is "attachment of this chat".
CREATE INDEX attachments_chat_created_idx
ON attachments (chat_id, created_at, id);
-- The reconciler scans all rows by state and age. It never runs on the HTTP
-- hot path.
CREATE INDEX attachments_status_updated_idx
ON attachments (status, updated_at);
-- messages.id is already the primary key; this unique constraint is the
-- target required by the composite foreign keys below, not a second identity.
-- It must exist before the foreign key that references (id, chat_id).
ALTER TABLE messages
ADD CONSTRAINT messages_id_chat_unique UNIQUE (id, chat_id);
-- A message and its attachment links share one transaction. The composite
-- foreign keys make "file of another chat" impossible at the database level
-- even if a future handler forgets the application check.
CREATE TABLE message_attachments (
message_id uuid NOT NULL,
attachment_id uuid NOT NULL,
chat_id uuid NOT NULL,
position integer NOT NULL,
PRIMARY KEY (message_id, attachment_id),
CONSTRAINT message_attachments_position_unique UNIQUE (message_id, position),
CONSTRAINT message_attachments_position_nonnegative CHECK (position >= 0),
CONSTRAINT message_attachments_message_chat_fk
FOREIGN KEY (message_id, chat_id) REFERENCES messages (id, chat_id) ON DELETE CASCADE,
CONSTRAINT message_attachments_attachment_chat_fk
FOREIGN KEY (attachment_id, chat_id) REFERENCES attachments (id, chat_id)
);
-- Reconciler lookup: "is this object key still referenced by any row?".
CREATE INDEX message_attachments_attachment_idx
ON message_attachments (attachment_id);
@@ -0,0 +1,10 @@
-- Lab4 contract: a message may carry text = "" when it references at least one
-- attachment of the chat (contracts/README.md, "Вложения"). The HTTP handler
-- still rejects empty or blank text without attachments; the database
-- constraint only widens to permit the documented attachment-only message.
ALTER TABLE messages
DROP CONSTRAINT messages_text_length;
ALTER TABLE messages
ADD CONSTRAINT messages_text_length
CHECK (char_length(text) BETWEEN 0 AND 4000);
+702
View File
@@ -0,0 +1,702 @@
// Package store is the PostgreSQL repository. Every statement uses positional
// parameters; identifiers are never interpolated into SQL. The pool is
// bounded and every operation carries a context timeout.
package store
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"strconv"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/puddle/v2"
"mtusi.ru/messenger-lab4/internal/cursor"
"mtusi.ru/messenger-lab4/internal/model"
"mtusi.ru/messenger-lab4/internal/uuid"
)
// Domain errors. The HTTP layer maps them to the contract's status codes.
var (
ErrNotFound = errors.New("object not found")
ErrUsernameTaken = errors.New("username already taken")
ErrUnknownMember = errors.New("unknown chat member")
ErrUnavailable = errors.New("database unavailable")
ErrIdempotencyConflict = errors.New("idempotency key reused with a different request body")
ErrAttachmentNotReady = errors.New("attachment is not ready")
)
// Options bounds the pool and every query. Zero values fall back to safe
// defaults so the store is still testable from small programs.
type Options struct {
MaxConns int32
MinConns int32
ConnectTimeout time.Duration
StatementTimeout time.Duration
QueryTimeout time.Duration
}
// Store owns a bounded pgx pool.
type Store struct {
pool *pgxpool.Pool
queryTimeout time.Duration
}
// Open parses the DSN and creates the pool. Parse errors deliberately do not
// echo the DSN: it contains the database password.
func Open(ctx context.Context, dsn string, options Options) (*Store, error) {
config, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, errors.New("DATABASE_URL is not a valid PostgreSQL URL")
}
applyDefaults(&options)
config.MaxConns = options.MaxConns
config.MinConns = options.MinConns
config.MaxConnLifetime = 30 * time.Minute
config.MaxConnIdleTime = 5 * time.Minute
config.HealthCheckPeriod = 30 * time.Second
config.ConnConfig.ConnectTimeout = options.ConnectTimeout
config.ConnConfig.RuntimeParams["application_name"] = "messenger-lab4"
// A statement timeout in the server session is the last line of defence
// against a runaway query; the caller's context is the first.
config.ConnConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(options.StatementTimeout.Milliseconds(), 10)
pool, err := pgxpool.NewWithConfig(ctx, config)
if err != nil {
return nil, fmt.Errorf("create PostgreSQL pool: %w", err)
}
return &Store{pool: pool, queryTimeout: options.QueryTimeout}, nil
}
func applyDefaults(options *Options) {
if options.MaxConns <= 0 {
options.MaxConns = 8
}
if options.MinConns < 0 {
options.MinConns = 0
}
if options.MinConns > options.MaxConns {
options.MinConns = options.MaxConns
}
if options.ConnectTimeout <= 0 {
options.ConnectTimeout = 3 * time.Second
}
if options.StatementTimeout <= 0 {
options.StatementTimeout = 3 * time.Second
}
if options.QueryTimeout <= 0 {
options.QueryTimeout = 3 * time.Second
}
}
// Ping is used by /health/ready and by the startup readiness loop.
func (s *Store) Ping(ctx context.Context) error {
return s.pool.Ping(ctx)
}
// Close waits for in-flight queries and closes the pool.
func (s *Store) Close() { s.pool.Close() }
func (s *Store) opCtx(ctx context.Context) (context.Context, context.CancelFunc) {
if s.queryTimeout <= 0 {
return ctx, func() {}
}
return context.WithTimeout(ctx, s.queryTimeout)
}
// classify separates a dependency outage (contract 503 unavailable) from a
// genuine application bug (500 internal_error). Only the error class is mapped;
// the original error is logged server-side and never sent to a client.
func (s *Store) classify(err error) error {
if err == nil {
return nil
}
if errors.Is(err, pgx.ErrNoRows) {
return ErrNotFound
}
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
switch {
case strings.HasPrefix(pgErr.Code, "08"), // connection exception
pgErr.Code == "57P01", // admin shutdown
pgErr.Code == "57P02", // crash shutdown
pgErr.Code == "57P03", // cannot connect now
pgErr.Code == "57014", // query cancelled (statement_timeout)
strings.HasPrefix(pgErr.Code, "53"): // insufficient resources
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return err
}
if errors.Is(err, puddle.ErrClosedPool) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
var netErr net.Error
if errors.As(err, &netErr) {
return fmt.Errorf("%w: %w", ErrUnavailable, err)
}
return err
}
func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "users_username_key"
}
func isForeignKeyViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23503"
}
func isIdempotencyViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505" &&
pgErr.ConstraintName == "message_idempotency_pkey"
}
// CreateUser inserts a user and relies on the unique index for both ordinary
// duplicates and concurrent registrations of the same username.
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
id := uuid.New()
createdAt := time.Now().UTC()
var stored time.Time
err := s.pool.QueryRow(ctx, `
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ($1::uuid, $2, $3, $4, $5)
RETURNING created_at`,
id, username, displayName, passwordHash, createdAt,
).Scan(&stored)
if err != nil {
if isUniqueViolation(err) {
return model.User{}, ErrUsernameTaken
}
return model.User{}, s.classify(err)
}
return model.User{
ID: id,
Username: username,
DisplayName: displayName,
CreatedAt: model.Time{Time: stored.UTC()},
}, nil
}
// UserByUsername returns the public user and the Argon2id hash. The hash is
// used only by the login handler and is never serialised.
func (s *Store) UserByUsername(ctx context.Context, username string) (model.User, string, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var user model.User
var passwordHash string
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT id::text, username, display_name, password_hash, created_at
FROM users WHERE username = $1`, username,
).Scan(&user.ID, &user.Username, &user.DisplayName, &passwordHash, &createdAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.User{}, "", ErrNotFound
}
return model.User{}, "", s.classify(err)
}
user.CreatedAt = model.Time{Time: createdAt.UTC()}
return user, passwordHash, nil
}
// UserByID resolves the identity stored in a server-side session.
func (s *Store) UserByID(ctx context.Context, id string) (model.User, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var user model.User
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT id::text, username, display_name, created_at
FROM users WHERE id = $1::uuid`, id,
).Scan(&user.ID, &user.Username, &user.DisplayName, &createdAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.User{}, ErrNotFound
}
return model.User{}, s.classify(err)
}
user.CreatedAt = model.Time{Time: createdAt.UTC()}
return user, nil
}
// CreateChat inserts the chat and its membership in one transaction. A caller
// cannot observe a chat without members: either both are committed or neither.
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []string, callerID string) (model.Chat, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Chat{}, s.classify(err)
}
defer func() { _ = tx.Rollback(context.Background()) }()
var existing int
if err := tx.QueryRow(ctx, `
SELECT count(*) FROM users
WHERE id IN (SELECT value::uuid FROM unnest($1::text[]) AS value)`, memberIDs,
).Scan(&existing); err != nil {
return model.Chat{}, s.classify(err)
}
if existing != len(memberIDs) {
return model.Chat{}, ErrUnknownMember
}
id := uuid.New()
createdAt := time.Now().UTC()
var stored time.Time
if err := tx.QueryRow(ctx, `
INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)
RETURNING created_at`, id, title, createdAt,
).Scan(&stored); err != nil {
return model.Chat{}, s.classify(err)
}
batch := &pgx.Batch{}
for position, memberID := range memberIDs {
batch.Queue(`INSERT INTO chat_members (chat_id, user_id, position) VALUES ($1::uuid, $2::uuid, $3)`,
id, memberID, position)
}
results := tx.SendBatch(ctx, batch)
for range memberIDs {
if _, err := results.Exec(); err != nil {
_ = results.Close()
if isForeignKeyViolation(err) {
return model.Chat{}, ErrUnknownMember
}
return model.Chat{}, s.classify(err)
}
}
if err := results.Close(); err != nil {
return model.Chat{}, s.classify(err)
}
if err := tx.Commit(ctx); err != nil {
return model.Chat{}, s.classify(err)
}
return model.Chat{
ID: id,
Title: title,
MemberIDs: append([]string(nil), memberIDs...),
CreatedAt: model.Time{Time: stored.UTC()},
}, nil
}
// IsChatMember is used before parsing query parameters so a foreign chat is
// always 404, independent of the submitted cursor or limit.
func (s *Store) IsChatMember(ctx context.Context, chatID, userID string) (bool, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var member bool
err := s.pool.QueryRow(ctx, `
SELECT EXISTS (
SELECT 1 FROM chat_members WHERE chat_id = $1::uuid AND user_id = $2::uuid
)`, chatID, userID).Scan(&member)
if err != nil {
return false, s.classify(err)
}
return member, nil
}
// ChatForUser returns a chat only when the user is a member. A missing chat and
// a foreign chat are indistinguishable to the caller.
func (s *Store) ChatForUser(ctx context.Context, chatID, userID string) (model.Chat, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
var chat model.Chat
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT c.id::text, c.title, c.created_at,
array_agg(cm.user_id::text ORDER BY cm.position)
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2::uuid
JOIN chat_members cm ON cm.chat_id = c.id
WHERE c.id = $1::uuid
GROUP BY c.id`, chatID, userID,
).Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.Chat{}, ErrNotFound
}
return model.Chat{}, s.classify(err)
}
chat.CreatedAt = model.Time{Time: createdAt.UTC()}
return chat, nil
}
const chatsPageSelect = `
SELECT c.id::text, c.title, c.created_at,
array_agg(cm.user_id::text ORDER BY cm.position)
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1::uuid
JOIN chat_members cm ON cm.chat_id = c.id`
// Chats returns one keyset page of chats visible to the user.
func (s *Store) Chats(ctx context.Context, userID string, position *cursor.Cursor, limit int) (model.ChatPage, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
query := chatsPageSelect + `
GROUP BY c.id
ORDER BY c.created_at, c.id
LIMIT $2`
args := []any{userID, limit + 1}
if position != nil {
query = chatsPageSelect + `
WHERE (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
GROUP BY c.id
ORDER BY c.created_at, c.id
LIMIT $4`
args = []any{userID, position.At, position.ID, limit + 1}
}
rows, err := s.pool.Query(ctx, query, args...)
if err != nil {
return model.ChatPage{}, s.classify(err)
}
defer rows.Close()
items := make([]model.Chat, 0, limit)
for rows.Next() {
var chat model.Chat
var createdAt time.Time
if err := rows.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil {
return model.ChatPage{}, s.classify(err)
}
chat.CreatedAt = model.Time{Time: createdAt.UTC()}
items = append(items, chat)
}
if err := rows.Err(); err != nil {
return model.ChatPage{}, s.classify(err)
}
page := model.ChatPage{Items: items}
if len(items) > limit {
page.Items = items[:limit]
next := cursor.ForChat(page.Items[len(page.Items)-1])
page.NextCursor = &next
}
return page, nil
}
// PoolStats is a point-in-time snapshot of the bounded pgx pool. It is used
// only by the operator-only metrics listener, never by the public API.
type PoolStats struct {
MaxConns int32 `json:"max_conns"`
TotalConns int32 `json:"total_conns"`
AcquiredConns int32 `json:"acquired_conns"`
IdleConns int32 `json:"idle_conns"`
EmptyAcquireCount int64 `json:"empty_acquire_count"`
CanceledAcquireCount int64 `json:"canceled_acquire_count"`
AcquireCount int64 `json:"acquire_count"`
AcquireDurationMillis int64 `json:"acquire_duration_ms_total"`
NewConnsCount int64 `json:"new_conns_count"`
MaxLifetimeDestroyCount int64 `json:"max_lifetime_destroy_count"`
MaxIdleDestroyCount int64 `json:"max_idle_destroy_count"`
}
// PoolStats reports saturation signals for the connection pool. EmptyAcquire
// Count is the number of calls that had to wait for a free connection; a fast
// rising value while the API CPU is below its limit points at the database or
// the pool size, not at the HTTP layer.
func (s *Store) PoolStats() PoolStats {
stat := s.pool.Stat()
return PoolStats{
MaxConns: stat.MaxConns(),
TotalConns: stat.TotalConns(),
AcquiredConns: stat.AcquiredConns(),
IdleConns: stat.IdleConns(),
EmptyAcquireCount: stat.EmptyAcquireCount(),
CanceledAcquireCount: stat.CanceledAcquireCount(),
AcquireCount: stat.AcquireCount(),
AcquireDurationMillis: stat.AcquireDuration().Milliseconds(),
NewConnsCount: stat.NewConnsCount(),
MaxLifetimeDestroyCount: stat.MaxLifetimeDestroyCount(),
MaxIdleDestroyCount: stat.MaxIdleDestroyCount(),
}
}
// CreateMessageIdempotent appends a message, its attachment links and the
// idempotency result in one PostgreSQL transaction. A committed transaction
// therefore always contains the message, every link and the key record; a
// failed one contains none of them. The idempotency unique index serialises
// concurrent replays: the loser blocks, then rolls back and reads the committed
// winner, so a concurrent repeat can never create a second message.
//
// Behavior derived from contracts/README.md:
// - a new (user, method, path, key) creates a message and its record, 201;
// - the same semantic body replays the stored message and links, 201;
// - a different body with the same key is a conflict, 409;
// - a transient failure touches neither table, so the client may safely
// retry the same key and never observe a duplicate side effect.
func (s *Store) CreateMessageIdempotent(ctx context.Context, chatID, senderID, method, path, key string, requestHash []byte, text string, attachmentIDs []string) (model.Message, bool, error) {
if attachmentIDs == nil {
attachmentIDs = []string{}
}
message := model.Message{
ID: uuid.New(),
ChatID: chatID,
SenderID: senderID,
Text: text,
// A non-nil empty slice is required: the public Message schema has
// attachment_ids: [] as an array, never null.
AttachmentIDs: append([]string{}, attachmentIDs...),
}
ctx, cancel := s.opCtx(ctx)
defer cancel()
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Message{}, false, s.classify(err)
}
defer func() { _ = tx.Rollback(context.Background()) }()
// Validate every attachment against the message chat before writing any
// row. The composite foreign key is the second line of defence; this query
// lets the handler distinguish "foreign/unknown" (404) from "not ready"
// (409) without leaking whether a foreign attachment id exists.
if len(attachmentIDs) > 0 {
rows, queryErr := tx.Query(ctx, `
SELECT id::text, status
FROM attachments
WHERE chat_id = $1::uuid
AND id IN (SELECT value::uuid FROM unnest($2::text[]) AS value)`,
chatID, attachmentIDs)
if queryErr != nil {
return model.Message{}, false, s.classify(queryErr)
}
statuses := make(map[string]string, len(attachmentIDs))
for rows.Next() {
var id, status string
if scanErr := rows.Scan(&id, &status); scanErr != nil {
rows.Close()
return model.Message{}, false, s.classify(scanErr)
}
statuses[id] = status
}
if rows.Err() != nil {
rows.Close()
return model.Message{}, false, s.classify(rows.Err())
}
rows.Close()
if len(statuses) != len(attachmentIDs) {
return model.Message{}, false, ErrNotFound
}
for _, status := range statuses {
if status != "ready" {
return model.Message{}, false, ErrAttachmentNotReady
}
}
}
created := time.Now().UTC()
var stored time.Time
err = tx.QueryRow(ctx, `
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
RETURNING created_at`,
message.ID, chatID, senderID, text, created,
).Scan(&stored)
if err != nil {
if isForeignKeyViolation(err) {
return model.Message{}, false, ErrNotFound
}
return model.Message{}, false, s.classify(err)
}
if len(attachmentIDs) > 0 {
batch := &pgx.Batch{}
for position, attachmentID := range attachmentIDs {
batch.Queue(`
INSERT INTO message_attachments (message_id, attachment_id, chat_id, position)
VALUES ($1::uuid, $2::uuid, $3::uuid, $4)`,
message.ID, attachmentID, chatID, position)
}
results := tx.SendBatch(ctx, batch)
for range attachmentIDs {
if _, execErr := results.Exec(); execErr != nil {
_ = results.Close()
if isForeignKeyViolation(execErr) {
return model.Message{}, false, ErrNotFound
}
return model.Message{}, false, s.classify(execErr)
}
}
if closeErr := results.Close(); closeErr != nil {
if isForeignKeyViolation(closeErr) {
return model.Message{}, false, ErrNotFound
}
return model.Message{}, false, s.classify(closeErr)
}
}
_, err = tx.Exec(ctx, `
INSERT INTO message_idempotency
(user_id, method, path, key, request_hash, message_id, created_at)
VALUES ($1::uuid, $2, $3, $4, $5, $6::uuid, $7)`,
senderID, method, path, key, requestHash, message.ID, created)
if err != nil {
if isIdempotencyViolation(err) {
// This transaction never committed. Roll it back explicitly before
// reading the winner; PostgreSQL has already released the row lock
// when it reported the unique violation.
_ = tx.Rollback(ctx)
storedHash, storedMessage, found, replayErr := s.replayIdempotent(ctx, senderID, method, path, key)
if replayErr != nil {
return model.Message{}, false, replayErr
}
if !found {
return model.Message{}, false, fmt.Errorf("%w: idempotency record vanished", ErrUnavailable)
}
if !bytes.Equal(storedHash, requestHash) {
return model.Message{}, false, ErrIdempotencyConflict
}
return storedMessage, true, nil
}
return model.Message{}, false, s.classify(err)
}
if err := tx.Commit(ctx); err != nil {
return model.Message{}, false, s.classify(err)
}
message.CreatedAt = model.Time{Time: stored.UTC()}
return message, false, nil
}
func (s *Store) replayIdempotent(ctx context.Context, userID, method, path, key string) ([]byte, model.Message, bool, error) {
var storedHash []byte
var message model.Message
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT i.request_hash,
m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at,
COALESCE((
SELECT array_agg(ma.attachment_id::text ORDER BY ma.position)
FROM message_attachments ma
WHERE ma.message_id = m.id
), '{}')
FROM message_idempotency i
JOIN messages m ON m.id = i.message_id
WHERE i.user_id = $1::uuid AND i.method = $2 AND i.path = $3 AND i.key = $4`,
userID, method, path, key,
).Scan(&storedHash, &message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt, &message.AttachmentIDs)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, model.Message{}, false, nil
}
return nil, model.Message{}, false, s.classify(err)
}
if message.AttachmentIDs == nil {
message.AttachmentIDs = []string{}
}
message.CreatedAt = model.Time{Time: createdAt.UTC()}
return storedHash, message, true, nil
}
// PruneIdempotency removes records older than the contract's minimum
// retention. It runs opportunistically from every replica; the statement is
// safe to execute concurrently and is bounded to keep one delete short.
func (s *Store) PruneIdempotency(ctx context.Context, olderThan time.Duration) (int64, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
tag, err := s.pool.Exec(ctx, `
DELETE FROM message_idempotency
WHERE ctid IN (
SELECT ctid FROM message_idempotency
WHERE created_at < now() - $1::interval
LIMIT 500
)`, fmt.Sprintf("%d seconds", int(olderThan.Seconds())))
if err != nil {
return 0, s.classify(err)
}
return tag.RowsAffected(), nil
}
const messagesPageSelect = `
SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at,
COALESCE((
SELECT array_agg(ma.attachment_id::text ORDER BY ma.position)
FROM message_attachments ma
WHERE ma.message_id = m.id
), '{}')
FROM (`
// Messages returns one keyset page of a chat history. The caller has already
// verified membership; the query itself never loads the whole history.
func (s *Store) Messages(ctx context.Context, chatID string, position *cursor.Cursor, limit int) (model.MessagePage, error) {
ctx, cancel := s.opCtx(ctx)
defer cancel()
where := `WHERE chat_id = $1::uuid`
args := []any{chatID, limit + 1}
order := `ORDER BY created_at, id
LIMIT $2`
if position != nil {
where = `WHERE chat_id = $1::uuid
AND (created_at, id) > ($2::timestamptz, $3::uuid)`
args = []any{chatID, position.At, position.ID, limit + 1}
order = `ORDER BY created_at, id
LIMIT $4`
}
query := messagesPageSelect + `
SELECT id, chat_id, sender_id, text, created_at
FROM messages
` + where + `
` + order + `
) m
LEFT JOIN message_attachments ma ON ma.message_id = m.id
GROUP BY m.id, m.chat_id, m.sender_id, m.text, m.created_at
ORDER BY m.created_at, m.id`
rows, err := s.pool.Query(ctx, query, args...)
if err != nil {
return model.MessagePage{}, s.classify(err)
}
defer rows.Close()
items := make([]model.Message, 0, limit)
for rows.Next() {
var message model.Message
var createdAt time.Time
if err := rows.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt, &message.AttachmentIDs); err != nil {
return model.MessagePage{}, s.classify(err)
}
if message.AttachmentIDs == nil {
message.AttachmentIDs = []string{}
}
message.CreatedAt = model.Time{Time: createdAt.UTC()}
items = append(items, message)
}
if err := rows.Err(); err != nil {
return model.MessagePage{}, s.classify(err)
}
page := model.MessagePage{Items: items}
if len(items) > limit {
page.Items = items[:limit]
next := cursor.ForMessage(page.Items[len(page.Items)-1])
page.NextCursor = &next
}
return page, nil
}
+75
View File
@@ -0,0 +1,75 @@
// Package uuid generates and normalizes canonical lowercase UUIDs. The
// application, not PostgreSQL, assigns identifiers so every API replica and
// the database agree on the exact on-the-wire form.
package uuid
import (
"crypto/rand"
"encoding/hex"
"strings"
)
// New returns a canonical lowercase UUIDv4. A failure of crypto/rand means the
// process cannot safely create identifiers, so panicking is intentional; the
// HTTP layer turns it into a generic 500 response.
func New() string {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
panic("crypto/rand failed: " + err.Error())
}
b[6] = (b[6] & 0x0f) | 0x40 // version 4
b[8] = (b[8] & 0x3f) | 0x80 // RFC 4122 variant
return format(b)
}
// NewRandom returns a lowercase hex string with n random bytes. It is used for
// request ids and stable per-process instance ids, not for resource ids.
func NewRandom(n int) string {
raw := make([]byte, n)
if _, err := rand.Read(raw); err != nil {
panic("crypto/rand failed: " + err.Error())
}
return hex.EncodeToString(raw)
}
func format(b [16]byte) string {
var out [36]byte
hex.Encode(out[0:8], b[0:4])
out[8] = '-'
hex.Encode(out[9:13], b[4:6])
out[13] = '-'
hex.Encode(out[14:18], b[6:8])
out[18] = '-'
hex.Encode(out[19:23], b[8:10])
out[23] = '-'
hex.Encode(out[24:36], b[10:16])
return string(out[:])
}
// Normalize accepts only the canonical 8-4-4-4-12 hyphenated form (ASCII hex,
// case-insensitive) and returns its lowercase representation. Braces, urn:
// prefixes, SQL uuid spellings and other aliases are rejected so resource
// identifiers have exactly one wire form.
func Normalize(value string) (string, bool) {
if len(value) != 36 {
return "", false
}
for i := 0; i < len(value); i++ {
c := value[i]
switch i {
case 8, 13, 18, 23:
if c != '-' {
return "", false
}
default:
if !isHex(c) {
return "", false
}
}
}
return strings.ToLower(value), true
}
func isHex(c byte) bool {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
}
+44
View File
@@ -0,0 +1,44 @@
package uuid
import "testing"
func TestNewIsCanonicalV4(t *testing.T) {
id := New()
normalized, ok := Normalize(id)
if !ok || normalized != id {
t.Fatalf("New() returned non-canonical UUID %q", id)
}
if id[14] != '4' {
t.Fatalf("version nibble = %c, want 4", id[14])
}
if id[19] != '8' && id[19] != '9' && id[19] != 'a' && id[19] != 'b' {
t.Fatalf("variant nibble = %c, want 8/9/a/b", id[19])
}
if New() == New() {
t.Fatal("two generated UUIDs are equal")
}
}
func TestNormalize(t *testing.T) {
valid := "11111111-2222-4333-8444-555555555555"
if got, ok := Normalize(valid); !ok || got != valid {
t.Fatalf("Normalize(%q) = %q, %v", valid, got, ok)
}
upper := "AAAAAAAA-BBBB-4CCC-8DDD-EEEEEEEEEEEE"
if got, ok := Normalize(upper); !ok || got != "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee" {
t.Fatalf("uppercase normalization failed: %q, %v", got, ok)
}
for _, invalid := range []string{
"",
"{11111111-2222-4333-8444-555555555555}",
"urn:uuid:11111111-2222-4333-8444-555555555555",
"11111111222243338444555555555555",
"11111111-2222-4333-8444-55555555555z",
"11111111-2222-4333-8444-5555555555555",
" 1111111-2222-4333-8444-555555555555",
} {
if _, ok := Normalize(invalid); ok {
t.Fatalf("Normalize accepted %q", invalid)
}
}
}
Regular → Executable
View File
+117
View File
@@ -0,0 +1,117 @@
#!/bin/sh
# Build and test the committed revision from a separate clone with empty named
# volumes, then remove only that clone's containers, network, volumes and image.
#
# The main lab4 stand (if running) is stopped with data preserved for the
# duration so both stands fit the 2 vCPU / ~2 GiB Colima VM, and restarted at
# the end. The temporary clone lives under .local/highload-tasks/lab4-artifacts
# because Colima only shares the user's home into the VM.
set -eu
cd "$(dirname "$0")/.."
root=$(pwd)
revision=$(git rev-parse HEAD)
if [ -n "$(git status --porcelain)" ]; then
echo "clean-clone-check: working tree is dirty; commit first" >&2
exit 2
fi
artifact_root=${LAB4_ARTIFACTS:-$(cd "$root/../.." && pwd)/.local/highload-tasks/lab4-artifacts}
mkdir -p "$artifact_root"
tmp=$(mktemp -d "$artifact_root/clean-clone.XXXXXX")
project=mtusi-lab4-melnikov-clean
port=8085
image=$project:local
main_was_running=0
if docker ps --format '{{.Names}}' | grep -q '^mtusi-lab4-melnikov-'; then
main_was_running=1
fi
cleanup() {
status=$?
if [ -d "$tmp" ]; then
(cd "$tmp" && COMPOSE_PROJECT_NAME=$project LB_PORT=$port \
./scripts/compose.sh --env-file .env down -v --remove-orphans >/dev/null 2>&1 || true)
ids=$(docker ps -aq --filter label=com.docker.compose.project=$project || true)
if [ -n "$ids" ]; then docker rm -f $ids >/dev/null 2>&1 || true; fi
volumes=$(docker volume ls -q --filter label=com.docker.compose.project=$project || true)
if [ -n "$volumes" ]; then docker volume rm $volumes >/dev/null 2>&1 || true; fi
networks=$(docker network ls -q --filter label=com.docker.compose.project=$project || true)
if [ -n "$networks" ]; then docker network rm $networks >/dev/null 2>&1 || true; fi
docker image rm -f "$image" >/dev/null 2>&1 || true
case "$tmp" in
"$artifact_root"/clean-clone.*) rm -rf "$tmp" ;;
*) echo "clean-clone-check: refusing to remove unexpected path $tmp" >&2 ;;
esac
fi
if [ "$main_was_running" = "1" ]; then
echo "main lab4 stand was stopped for the check; data volumes are preserved."
echo "run 'make up' in $root to restart it."
fi
exit "$status"
}
trap cleanup EXIT INT TERM
echo "== clean clone =="
echo "source revision: $revision"
echo "clone: $tmp"
echo "project: $project; LB port: $port; image: $image"
if [ "$main_was_running" = "1" ]; then
echo "stopping the main lab4 stand with data preserved for the check"
(cd "$root" && make stop >/dev/null)
fi
git clone --quiet "$root" "$tmp"
cd "$tmp"
test "$(git rev-parse HEAD)" = "$revision"
echo "== local configuration with fresh synthetic credentials =="
./scripts/init-env.sh
python3 - "$tmp/.env" "$port" "$project" <<'PY'
import sys
path, port, project = sys.argv[1], sys.argv[2], sys.argv[3]
lines = []
for line in open(path):
if line.startswith('LB_PORT='):
line = 'LB_PORT=%s\n' % port
elif line.startswith('COMPOSE_PROJECT_NAME='):
line = 'COMPOSE_PROJECT_NAME=%s\n' % project
lines.append(line)
open(path, 'w').writelines(lines)
PY
export COMPOSE_PROJECT_NAME=$project
export LB_PORT=$port
export IMAGE=$image
export BASE_URL=http://127.0.0.1:$port
echo "== offline contract and syntax checks =="
make check
echo "== build, migrate and bootstrap the bucket from empty volumes =="
GIT_REVISION=$revision API_IMAGE=$image make up
postgres=$(./scripts/compose.sh --env-file .env ps -q postgres)
set -a
. ./.env
set +a
docker exec -i "$postgres" psql -X -A -t -U "$POSTGRES_USER" -d "$POSTGRES_DB" \
-c "SELECT 'users=' || count(*) FROM users;" \
-c "SELECT 'attachments=' || count(*) FROM attachments;" \
-c "SELECT 'migrations=' || string_agg(version::text, ',' ORDER BY version) FROM schema_migrations;"
./scripts/compose.sh --env-file .env logs s3-init 2>&1 | grep -E '"created":(true|false)' || true
./scripts/compose.sh --env-file .env ps --format 'table {{.Name}}\t{{.Status}}'
echo "== public and own API tests on the clean stand =="
make test
make test-student
make test-persistence ACTION_SCRIPT=scripts/restart.sh
echo "== intentional cleanup of this temporary clone's resources =="
make purge
docker image rm -f "$image" >/dev/null 2>&1 || true
if docker ps -aq --filter label=com.docker.compose.project=$project | grep -q .; then
echo "clean-clone-check: containers remain" >&2
exit 1
fi
if docker volume ls -q | grep -q "^${project}-"; then
echo "clean-clone-check: volumes remain" >&2
exit 1
fi
echo "PASS: clean clone built, migrated, bootstrapped and tested; temporary resources removed"
+93
View File
@@ -0,0 +1,93 @@
#!/bin/bash
# Reproduce the lab4 mandatory and own checks on the running stand and keep
# their real stdout under evidence/commands/. No secrets are printed by these
# commands; the context block contains versions and image ids only.
set -euo pipefail
cd "$(dirname "$0")/.."
export BASE_URL=${BASE_URL:-http://127.0.0.1:8084}
PY39=/usr/bin/python3
out=evidence/commands
mkdir -p "$out"
stamp=$(date -u +%Y-%m-%dT%H:%M:%SZ)
{
echo "started_at: $stamp"
echo "base_url: $BASE_URL"
echo "git_revision: $(git rev-parse HEAD)"
echo "git_status_lines: $(git status --porcelain | wc -l | tr -d ' ')"
echo "python3: $(python3 --version 2>&1)"
echo "python39: $($PY39 --version 2>&1)"
echo "go: $(go version)"
echo "docker_server: $(docker version --format '{{.Server.Version}}')"
echo "docker_cpus_mem: $(docker info --format 'CPUs={{.NCPU}} MemTotal={{.MemTotal}}')"
echo "api_images:"
for id in $(./scripts/compose.sh --env-file .env ps -q api); do
docker inspect -f ' {{.Name}} image={{.Image}} started={{.State.StartedAt}}' "$id"
done
echo "s3_image:"
for id in $(./scripts/compose.sh --env-file .env ps -q s3); do
docker inspect -f ' {{.Name}} image={{.Image}}' "$id"
done
} | tee "$out/context.txt"
run() {
name=$1
shift
{
echo
echo "### $name"
echo "### command: $*"
echo "### started_at: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
} | tee "$out/$name.txt"
set +e
"$@" 2>&1 | tee -a "$out/$name.txt"
code=${PIPESTATUS[0]}
set -e
echo "### exit_code: $code" | tee -a "$out/$name.txt"
if [ "$code" -ne 0 ]; then
echo "evidence collection stopped: $name failed" >&2
exit "$code"
fi
}
restore_replicas() {
./scripts/compose.sh --env-file .env up -d --no-deps api >/dev/null
./scripts/wait-ready.sh
# The LB needs a moment to see the restarted backend. Do not continue until
# the public health endpoint reports two distinct X-Instance-Id values.
attempt=0
while [ "$attempt" -lt 60 ]; do
visible=$(for _ in $(seq 1 20); do
curl -fsS -D - -o /dev/null "$BASE_URL/health/ready" 2>/dev/null \
| tr -d '\r' | awk 'tolower($1)=="x-instance-id:"{print $2}'
done | sort -u | wc -l | tr -d ' ')
if [ "$visible" -ge 2 ]; then
return 0
fi
attempt=$((attempt + 1))
sleep 0.5
done
echo "restore_replicas: LB still sees fewer than two API instances" >&2
return 1
}
run make_check make PYTHON=$PY39 check
run make_validate make PYTHON=.venv/bin/python validate
run go_tests make PYTHON=$PY39 test-student
run go_race make PYTHON=$PY39 test-student-race
run smoke make PYTHON=$PY39 test
run smoke_python39 ./scripts/py39-tests.sh
run attachment_checks make PYTHON=$PY39 test-attachment
run container_checks make PYTHON=$PY39 test-container
run persistence_public make PYTHON=$PY39 test-persistence ACTION_SCRIPT=scripts/restart.sh
run persistence_evidence $PY39 scripts/persistence-evidence.py --base-url "$BASE_URL"
run failover_public make PYTHON=$PY39 test-failover ACTION_SCRIPT=scripts/stop-one.sh
restore_replicas
run failover_upload $PY39 scripts/failover-upload.py --base-url "$BASE_URL"
run track2 make PYTHON=$PY39 test-consistency
run experiment make PYTHON=$PY39 experiment
run smoke_after_experiment make PYTHON=$PY39 test
echo "finished_at: $(date -u +%Y-%m-%dT%H:%M:%SZ)" | tee "$out/summary.txt"
grep -h '^### exit_code:' "$out"/*.txt | sort | uniq -c | tee -a "$out/summary.txt"
echo "PASS: evidence collection finished; raw command logs are in $out"
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Accept both the Compose v2 plugin ("docker compose") and the standalone
# binary ("docker-compose"), so the same Makefile works on machines where only
# one of them is installed. This wrapper does not change any global setting.
set -eu
if docker compose version >/dev/null 2>&1; then
exec docker compose "$@"
fi
if command -v docker-compose >/dev/null 2>&1; then
exec docker-compose "$@"
fi
echo "Docker Compose is required (docker compose or docker-compose)" >&2
exit 2
+232
View File
@@ -0,0 +1,232 @@
#!/usr/bin/env python3
"""Lab4 infrastructure evidence from actual Docker state, not compose.yaml.
Checks:
* at least two API processes with distinct container ids and hostnames;
* only HAProxy is published, on 127.0.0.1, and API/S3/admin ports are not;
* API is non-root, read-only, cap-drop ALL, no state volume; S3 has its data volume;
* every stand service has CPU and memory limits; named volumes use the lab prefix;
* the API S3 identity is bucket-scoped and differs from the admin identity,
and the admin identity is never present in an API container;
* the bucket bootstrap is idempotent (second run reports created=false);
* an anonymous S3 GET/list outside the API is denied;
* one session is served by both API replicas through the LB.
Python 3.9+, standard library only. Requires the running stand and Docker.
Writes evidence/container-checks.json and .txt.
"""
import json
import re
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, arguments, check # noqa: E402
import lab4_metrics as M # noqa: E402
def docker_exec(container, *args):
return subprocess.run(['docker', 'exec', container] + list(args),
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
def wait_exited(container, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
state = M.inspect(container).get('State', {})
if state.get('Status') == 'exited':
return state.get('ExitCode')
time.sleep(0.5)
raise RuntimeError('container did not exit: ' + container)
def main():
args = arguments('Lab4 container, S3 privacy and credential checks')
checks = {}
failures = []
compose_text = (ROOT / 'compose.yaml').read_text()
checks['no_container_name_in_compose'] = not re.search(r'^\s*container_name\s*:', compose_text, re.MULTILINE)
images = re.findall(r'^\s*image:\s*(\S+)', compose_text, re.MULTILINE)
third_party = [image for image in images if not image.startswith('${API_IMAGE')]
checks['third_party_images_pinned_by_digest'] = all('@sha256:' in image for image in third_party)
checks['third_party_images'] = third_party
api = M.containers('api')
lb = M.containers('lb')
postgres = M.containers('postgres')
valkey = M.containers('valkey')
s3 = M.containers('s3')
check(len(api) >= 2, 'expected at least two API containers')
check(len(lb) == 1 and len(postgres) == 1 and len(valkey) == 1 and len(s3) == 1,
'expected one LB, PostgreSQL, Valkey and S3 container')
checks['api_replica_count'] = len(api)
checks['api_container_ids_distinct'] = len({item['container_id'] for item in api}) == len(api)
checks['api_hostnames_distinct'] = len({item['hostname'] for item in api}) == len(api)
checks['api_image_ids'] = sorted({item['image_id'] for item in api})
checks['s3_image_id'] = s3[0]['image_id']
checks['git_revision'] = M.run(['git', 'rev-parse', 'HEAD']).stdout.strip()
api_ports = {item['name']: M.run(['docker', 'port', item['container_id']]).stdout.strip() for item in api}
s3_ports = M.run(['docker', 'port', s3[0]['container_id']]).stdout.strip()
lb_ports = M.run(['docker', 'port', lb[0]['container_id']]).stdout.strip()
checks['api_ports'] = api_ports
checks['s3_published_ports'] = s3_ports
checks['lb_ports'] = lb_ports
checks['api_has_no_published_ports'] = all(value == '' for value in api_ports.values())
checks['s3_has_no_published_ports'] = s3_ports == ''
checks['lb_published_loopback_only'] = ('127.0.0.1:' in lb_ports and '8080' in lb_ports)
limits = {}
for service, items in (('api', api), ('postgres', postgres), ('valkey', valkey), ('s3', s3), ('lb', lb)):
rows = []
for item in items:
data = M.inspect(item['container_id'])
host = data.get('HostConfig', {})
rows.append({
'name': item['name'],
'nano_cpus': host.get('NanoCpus'),
'memory_bytes': host.get('Memory'),
'readonly_rootfs': host.get('ReadonlyRootfs'),
'cap_drop': host.get('CapDrop'),
'security_opt': host.get('SecurityOpt'),
'user': data.get('Config', {}).get('User'),
'mounts': [mount.get('Name') or mount.get('Source') for mount in data.get('Mounts', [])],
'volume_mounts': [mount.get('Name') for mount in data.get('Mounts', [])
if mount.get('Type') == 'volume'],
})
limits[service] = rows
checks['limits'] = limits
checks['all_services_have_cpu_and_memory_limits'] = all(
row['nano_cpus'] and row['memory_bytes']
for rows in limits.values() for row in rows)
checks['api_non_root'] = all((row['user'] or '').startswith('10001') for row in limits['api'])
checks['api_read_only_rootfs'] = all(row['readonly_rootfs'] for row in limits['api'])
checks['api_cap_drop_all'] = all(row['cap_drop'] == ['ALL'] for row in limits['api'])
checks['api_no_new_privileges'] = all(
any('no-new-privileges' in value for value in (row['security_opt'] or []))
for row in limits['api'])
checks['api_has_no_state_volume'] = all(not row['mounts'] for row in limits['api'])
checks['s3_has_data_volume'] = any(
row['volume_mounts'] and all(name.startswith(M.PROJECT + '-') for name in row['volume_mounts'])
for row in limits['s3'])
volume_names = set()
for item in postgres + valkey + s3:
for mount in M.inspect(item['container_id']).get('Mounts', []):
if mount.get('Type') == 'volume':
volume_names.add(mount.get('Name'))
checks['named_volumes'] = sorted(volume_names)
checks['volumes_have_prefix'] = all(name.startswith(M.PROJECT + '-') for name in volume_names)
# S3 credentials: the API must not receive the administrative identity and
# must fail on a bucket outside its grant.
api_env = api[0]['env']
s3_init = M.compose('ps', '-a', '-q', 's3-init').stdout.strip()
check(s3_init != '', 's3-init container is missing')
init_env = M.inspect(s3_init).get('Config', {}).get('Env', [])
admin_access = ''
for item in init_env:
if item.startswith('S3_ADMIN_ACCESS_KEY='):
admin_access = item.split('=', 1)[1]
checks['api_s3_access_key_present'] = bool(api_env.get('S3_ACCESS_KEY'))
checks['api_s3_secret_present'] = bool(api_env.get('S3_SECRET_KEY'))
checks['api_credentials_differ_from_admin'] = (
bool(admin_access) and api_env.get('S3_ACCESS_KEY') != admin_access)
checks['api_has_no_admin_credentials'] = not any(
key.startswith('S3_ADMIN_') for key in api_env)
buckets = M.s3ctl('-op', 'list', '-prefix', '').stdout
checks['api_credentials_can_list_own_bucket'] = '"objects"' in buckets
other = M.s3ctl('-op', 'list', '-prefix', '', '-bucket', 'definitely-not-granted', check=False)
checks['api_credentials_denied_other_bucket'] = other.returncode != 0
# Bucket bootstrap is idempotent: run the same one-shot container again.
first = M.run(['docker', 'start', '-a', s3_init.strip()], check=False)
code = wait_exited(s3_init.strip())
logs = M.run(['docker', 'logs', '--tail', '5', s3_init.strip()]).stdout + M.run(
['docker', 'logs', '--tail', '5', s3_init.strip()]).stderr
checks['bucket_bootstrap_second_run_exit'] = code
checks['bucket_bootstrap_second_run_created_false'] = '"created":false' in logs
checks['bucket_bootstrap_second_run_verified'] = '"verified":true' in logs
# Anonymous access outside the API must not return an object or a listing.
alice, bob, eve, chat = Client(args.base_url, args.ca_file).bootstrap()
attachment, content = Client(args.base_url, args.ca_file).attachment(alice, chat)
object_key = M.psql(
"SELECT object_key FROM attachments WHERE id = '%s'" % attachment['id'])
bucket = api_env.get('S3_BUCKET', '')
check(bucket and object_key, 'cannot resolve bucket/object key for the privacy probe')
anonymous_object = docker_exec(api[0]['container_id'], 'wget', '-q', '-S', '-O', '/dev/null',
'http://s3:8333/' + bucket + '/' + object_key)
anonymous_list = docker_exec(api[0]['container_id'], 'wget', '-q', '-S', '-O', '/dev/null',
'http://s3:8333/' + bucket + '?list-type=2')
checks['anonymous_object_get_status'] = anonymous_object.stderr + anonymous_object.stdout
checks['anonymous_object_get_denied'] = (
anonymous_object.returncode != 0 and '403' in checks['anonymous_object_get_status'])
checks['anonymous_list_status'] = anonymous_list.stderr + anonymous_list.stdout
checks['anonymous_list_denied'] = (
anonymous_list.returncode != 0 and '403' in checks['anonymous_list_status'])
checks['attachment_download_still_authorized'] = (
Client(args.base_url, args.ca_file).call(
'GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob)['bytes'] == content)
# One session crosses the real replicas through the LB.
client = Client(args.base_url, args.ca_file)
observed = set()
for _ in range(40):
response = client.call('GET', '/api/v1/users/me', actor=alice, schema='User')
observed.add(response['headers']['X-Instance-Id'])
checks['observed_instances'] = sorted(observed)
checks['session_crosses_replicas'] = len(observed) >= 2
checks['session_instances_are_api_hostnames'] = observed.issubset({item['hostname'] for item in api})
checks['health_ready_via_lb'] = client.call('GET', '/health/ready', schema='Health')['status'] == 200
for key, value in checks.items():
if isinstance(value, bool) and not value:
failures.append(key)
checks['result'] = 'PASS' if not failures else 'FAIL'
checks['failed'] = failures
checks['checked_at'] = M.now_iso()
checks['base_url'] = args.base_url
output = ROOT / 'evidence' / 'container-checks.json'
output.parent.mkdir(parents=True, exist_ok=True)
M.write_json(output, checks)
lines = [
'lab4 container checks at ' + checks['checked_at'],
'result: ' + checks['result'],
'git revision: ' + checks['git_revision'],
'API replicas: %d (%s)' % (len(api), ', '.join(item['hostname'] for item in api)),
'API image ids: ' + ', '.join(checks['api_image_ids']),
'S3 image id: ' + checks['s3_image_id'],
'API ports published: %r' % api_ports,
'S3 ports published: %r' % s3_ports,
'LB ports: ' + lb_ports,
'volumes: ' + ', '.join(checks['named_volumes']),
'limits: ' + json.dumps(limits, separators=(',', ':')),
'observed session instances: ' + ', '.join(sorted(observed)),
'anonymous object GET denied: %r' % checks['anonymous_object_get_denied'],
'anonymous bucket list denied: %r' % checks['anonymous_list_denied'],
'bootstrap second run: exit=%r created_false=%r' % (
checks['bucket_bootstrap_second_run_exit'],
checks['bucket_bootstrap_second_run_created_false']),
]
(ROOT / 'evidence' / 'container-checks.txt').write_text('\n'.join(lines) + '\n', encoding='utf-8')
print('\n'.join(lines))
if failures:
raise SystemExit('FAILED checks: ' + ', '.join(failures))
print('PASS: container, S3 privacy and credential checks')
if __name__ == '__main__':
try:
main()
except Exception as exc: # noqa: BLE001
import traceback
traceback.print_exc()
print('FAIL:', exc)
raise SystemExit(1)
+155
View File
@@ -0,0 +1,155 @@
#!/usr/bin/env python3
"""Lab4 failover evidence: upload, stop the serving API replica, read elsewhere.
The public `make test-failover` checks writes and idempotency. This script adds
the lab4-specific proof: the attachment is uploaded by a known replica, that
replica is stopped with scripts/stop-one.sh, and the same original is
downloaded through a different replica with an identical SHA-256.
Python 3.9+, standard library only. Requires the running stand and Docker.
"""
import hashlib
import json
import os
import subprocess
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check # noqa: E402
import lab4_metrics as M # noqa: E402
EVIDENCE = ROOT / 'evidence' / 'resilience'
def upload_with_instance(c, actor, chat, data):
response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=failover.png',
201, actor=actor, raw=data, headers={'Content-Type': 'image/png'},
schema='Attachment')
return response['json'], response['headers']['X-Instance-Id']
def main():
args = arguments('Lab4 upload/failover evidence; stops one API replica and restores it')
EVIDENCE.mkdir(parents=True, exist_ok=True)
c = Client(args.base_url, args.ca_file, timeout=20)
alice, bob, eve, chat = c.bootstrap()
data = M.png_random(1400, 1000, seed=42)
attachment, uploader = upload_with_instance(c, alice, chat, data)
observed = set()
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
observed.add(c.call('GET', '/api/v1/users/me', actor=alice,
schema='User')['headers']['X-Instance-Id'])
if len(observed) >= 2:
break
time.sleep(0.3)
check(len(observed) >= 2, 'expected at least two API replicas before failover')
check(uploader in observed, 'upload was served by an unknown instance: ' + uploader)
command = [str(ROOT / 'scripts/stop-one.sh')]
environment = dict(os.environ)
environment['TARGET_INSTANCE_ID'] = uploader
started = M.now_iso()
process = subprocess.run(command, cwd=str(ROOT), env=environment,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stopped = M.now_iso()
check(process.returncode == 0, 'stop-one.sh failed: ' + process.stderr.strip()[-500:])
# The stopped replica must be the actual Docker container and stay stopped.
target_ids = []
for container in M.compose('ps', '-a', '-q', 'api').stdout.split():
hostname = M.run(['docker', 'inspect', '-f', '{{.Config.Hostname}}', container]).stdout.strip()
if hostname == uploader:
target_ids.append(container)
check(len(target_ids) == 1, 'could not map the upload instance to exactly one API container')
state = M.inspect(target_ids[0])['State']
check(state['Status'] == 'exited', 'target container is not stopped: ' + state['Status'])
M.wait_ready(60)
replica_set = set()
download = None
restored_at = None
restored_instances = set()
try:
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
download = c.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob)
replica_set.add(download['headers']['X-Instance-Id'])
if download['headers']['X-Instance-Id'] != uploader and download['bytes'] == data:
break
time.sleep(0.3)
check(download is not None and download['bytes'] == data,
'download after failover differs from the original')
check(download['headers']['X-Instance-Id'] != uploader,
'download was served by the stopped replica')
check(uploader not in replica_set, 'download hit the stopped replica')
metadata = c.call('GET', '/api/v1/attachments/' + attachment['id'], actor=bob,
schema='Attachment')['json']
check(metadata['sha256'] == hashlib.sha256(data).hexdigest(),
'metadata checksum changed after failover')
check(metadata['size_bytes'] == len(data), 'metadata size changed after failover')
finally:
# Restore the replica explicitly; the failover hook itself must leave it
# down, and this cleanup runs even when an assertion above fails.
M.compose('up', '-d', '--no-deps', 'api')
M.wait_ready(120)
restored_at = M.now_iso()
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
restored_instances.add(
c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id'])
if len(restored_instances) >= 2:
break
time.sleep(0.3)
check(len(restored_instances) >= 2, 'restored stand does not serve two API replicas')
result = {
'checked_at': M.now_iso(),
'base_url': args.base_url,
'git_revision': M.run(['git', 'rev-parse', 'HEAD']).stdout.strip(),
'attachment_id': attachment['id'],
'content_bytes': len(data),
'sha256': hashlib.sha256(data).hexdigest(),
'instances_before': sorted(observed),
'upload_instance': uploader,
'stopped_container_id': target_ids[0],
'stopped_container_state': state['Status'],
'stop_started_at': started,
'stop_finished_at': stopped,
'download_instance': download['headers']['X-Instance-Id'] if download else None,
'download_instances_seen': sorted(replica_set),
'download_sha256': hashlib.sha256(download['bytes']).hexdigest() if download else None,
'restored_at': restored_at,
'restored_instances': sorted(restored_instances),
'result': 'PASS',
'notes': [
'The upload response X-Instance-Id was mapped to the exact Docker hostname.',
'scripts/stop-one.sh left that container exited; the hook is not a restart helper.',
'The download was served by the remaining replica and matched the original bytes.',
'The stopped replica was restored explicitly with docker compose up -d api; Compose may recreate it with a new hostname.',
],
}
M.write_json(EVIDENCE / 'failover-upload.json', result)
print(json.dumps({
'upload_instance': uploader,
'download_instance': result['download_instance'],
'instances_seen': result['download_instances_seen'],
'sha256_matches': result['download_sha256'] == result['sha256'],
'stopped_container_state': result['stopped_container_state'],
'restored_at': result['restored_at'],
}, ensure_ascii=False))
print('PASS: upload survived replica stop and downloaded with the same SHA-256 via another replica')
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
+93
View File
@@ -0,0 +1,93 @@
#!/bin/sh
# Create a local .env with fresh synthetic passwords and generate the ignored
# SeaweedFS S3 identity file from those values. Nothing is printed: the files
# are readable only by the current user. This stand never talks to a remote
# secret store.
set -eu
cd "$(dirname "$0")/.."
if [ ! -f .env ]; then
random_secret() {
LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 32
}
postgres_password=$(random_secret)
valkey_password=$(random_secret)
s3_admin_access=$(random_secret)
s3_admin_secret=$(random_secret)
s3_api_access=$(random_secret)
s3_api_secret=$(random_secret)
for value in "$postgres_password" "$valkey_password" "$s3_admin_access" "$s3_admin_secret" "$s3_api_access" "$s3_api_secret"; do
if [ "${#value}" -ne 32 ]; then
echo "could not generate local secrets" >&2
exit 1
fi
done
revision=$(git rev-parse HEAD 2>/dev/null || echo unknown)
umask 077
sed \
-e "s|^POSTGRES_PASSWORD=.*|POSTGRES_PASSWORD=${postgres_password}|" \
-e "s|^VALKEY_PASSWORD=.*|VALKEY_PASSWORD=${valkey_password}|" \
-e "s|^S3_ADMIN_ACCESS_KEY=.*|S3_ADMIN_ACCESS_KEY=${s3_admin_access}|" \
-e "s|^S3_ADMIN_SECRET_KEY=.*|S3_ADMIN_SECRET_KEY=${s3_admin_secret}|" \
-e "s|^S3_API_ACCESS_KEY=.*|S3_API_ACCESS_KEY=${s3_api_access}|" \
-e "s|^S3_API_SECRET_KEY=.*|S3_API_SECRET_KEY=${s3_api_secret}|" \
-e "s|^GIT_REVISION=.*|GIT_REVISION=${revision}|" \
.env.example > .env
chmod 600 .env
echo "wrote .env with generated local synthetic credentials (mode 600); values not printed"
else
echo ".env already exists; keeping it"
fi
# Read the values back from the ignored file. The generated secrets use only
# [A-Za-z0-9], so a simple sed extraction is sufficient and never echoes them.
value() {
sed -n "s/^$1=//p" .env | head -n 1
}
postgres_password=$(value POSTGRES_PASSWORD)
valkey_password=$(value VALKEY_PASSWORD)
s3_admin_access=$(value S3_ADMIN_ACCESS_KEY)
s3_admin_secret=$(value S3_ADMIN_SECRET_KEY)
s3_api_access=$(value S3_API_ACCESS_KEY)
s3_api_secret=$(value S3_API_SECRET_KEY)
s3_bucket=$(value S3_BUCKET)
s3_bucket=${s3_bucket:-messenger-attachments}
for value_name in postgres_password valkey_password s3_admin_access s3_admin_secret s3_api_access s3_api_secret; do
eval "check=\${$value_name}"
if [ -z "$check" ]; then
echo "init-env: $value_name is empty in .env" >&2
exit 1
fi
done
umask 077
mkdir -p infra
cat > infra/seaweedfs-s3.json <<EOF
{
"identities": [
{
"name": "lab4-admin-bootstrap",
"credentials": [
{"accessKey": "${s3_admin_access}", "secretKey": "${s3_admin_secret}"}
],
"actions": ["Admin"]
},
{
"name": "lab4-api-bucket-scoped",
"credentials": [
{"accessKey": "${s3_api_access}", "secretKey": "${s3_api_secret}"}
],
"actions": [
"Read:${s3_bucket}",
"Write:${s3_bucket}",
"List:${s3_bucket}"
]
}
]
}
EOF
chmod 600 infra/seaweedfs-s3.json
echo "wrote infra/seaweedfs-s3.json (mode 600); values not printed"
+199
View File
@@ -0,0 +1,199 @@
#!/usr/bin/env python3
"""Shared operator helpers for the lab4 evidence scripts.
Python 3.9+, standard library only. The module wraps Docker/Compose and
PostgreSQL access used by student tests and experiments. It never prints
credentials: values are read from the running containers or the ignored .env
and are returned only to the caller.
"""
import datetime as dt
import json
import os
import random
import struct
import subprocess
import time
import zlib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
BASE_URL = os.environ.get('BASE_URL', 'http://127.0.0.1:8084')
PROJECT = 'mtusi-lab4-melnikov'
def run(args, cwd=ROOT, check=True, input_bytes=None):
process = subprocess.run(
args, cwd=str(cwd), input=input_bytes, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=input_bytes is None,
)
if check and process.returncode != 0:
stderr = process.stderr if isinstance(process.stderr, str) else process.stderr.decode('utf-8', 'replace')
raise RuntimeError('command failed: %s\n%s' % (' '.join(args), stderr.strip()[:2000]))
return process
def compose(*args):
return run([str(ROOT / 'scripts/compose.sh'), '--env-file', '.env'] + list(args))
def compose_ids(service):
output = compose('ps', '-q', service).stdout
return [line.strip() for line in output.splitlines() if line.strip()]
def inspect(container):
output = run(['docker', 'inspect', container]).stdout
return json.loads(output)[0]
def containers(service):
result = []
for container_id in compose_ids(service):
data = inspect(container_id)
result.append({
'container_id': data['Id'],
'name': (data.get('Name') or '').lstrip('/'),
'hostname': data.get('Config', {}).get('Hostname', ''),
'image_id': data.get('Image', ''),
'image_ref': (data.get('Config', {}).get('Image') or ''),
'status': (data.get('State') or {}).get('Status', ''),
'env': dict(item.split('=', 1) for item in (data.get('Config', {}).get('Env') or []) if '=' in item),
})
return result
def env_value(container, name):
for item in inspect(container).get('Config', {}).get('Env', []) or []:
if item.startswith(name + '='):
return item.split('=', 1)[1]
return ''
def postgres_identity():
postgres = compose_ids('postgres')
if not postgres:
raise RuntimeError('postgres container is not running')
user = env_value(postgres[0], 'POSTGRES_USER')
database = env_value(postgres[0], 'POSTGRES_DB')
return postgres[0], user, database
def psql(sql):
container, user, database = postgres_identity()
process = subprocess.run(
['docker', 'exec', '-i', container, 'psql', '-X', '-A', '-t', '-v', 'ON_ERROR_STOP=1',
'-U', user, '-d', database, '-c', sql],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
)
if process.returncode != 0:
raise RuntimeError('psql failed: ' + process.stderr.strip()[:2000])
return process.stdout.strip()
def s3ctl(*args, check=True):
api = compose_ids('api')
if not api:
raise RuntimeError('no API container is running')
return run(['docker', 'exec', api[0], '/app/s3ctl'] + list(args), check=check)
def s3_list(prefix='attachments/'):
output = s3ctl('-op', 'list', '-prefix', prefix).stdout
return json.loads(output)['objects']
def s3_count(prefix='attachments/'):
return len(s3_list(prefix))
def wait_ready(timeout=90, base_url=None):
import urllib.error
import urllib.request
url = (base_url or BASE_URL).rstrip('/') + '/health/ready'
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(url, timeout=2) as response:
if response.status == 200:
return True
except (urllib.error.URLError, OSError):
pass
time.sleep(0.5)
raise RuntimeError('stack did not become ready: ' + url)
def wait_healthy(service, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
ids = compose_ids(service)
if ids:
state = inspect(ids[0]).get('State', {})
health = state.get('Health', {}).get('Status')
if health in (None, 'healthy'):
return True
time.sleep(0.5)
raise RuntimeError('service did not become healthy: ' + service)
def now_iso():
return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
def monotonic_ms():
return int(time.monotonic() * 1000)
def png_chunk(kind, payload):
body = kind + payload
return struct.pack('>I', len(payload)) + body + struct.pack('>I', zlib.crc32(body) & 0xffffffff)
def _png_header(width, height, color_type=2, bit_depth=8):
return (b'\x89PNG\r\n\x1a\n'
+ png_chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, bit_depth, color_type, 0, 0, 0)))
def png_solid(width, height, rgb=(90, 130, 200)):
"""Small, valid PNG that compresses extremely well (used for pixel limits)."""
row = b'\x00' + bytes(rgb) * width
compressor = zlib.compressobj(6)
payload = bytearray()
for _ in range(height):
payload += compressor.compress(row)
payload += compressor.flush()
return (_png_header(width, height)
+ png_chunk(b'IDAT', bytes(payload))
+ png_chunk(b'IEND', b''))
def png_random(width, height, seed=7):
"""Valid PNG with incompressible RGB rows for byte-size and load profiles."""
generator = random.Random(seed)
compressor = zlib.compressobj(1)
payload = bytearray()
row_size = width * 3 + 1
for _ in range(height):
payload += compressor.compress(b'\x00' + generator.randbytes(row_size - 1))
payload += compressor.flush()
return (_png_header(width, height)
+ png_chunk(b'IDAT', bytes(payload))
+ png_chunk(b'IEND', b''))
def png_corrupt(width=320, height=200):
data = bytearray(png_solid(width, height))
# Flip a byte inside IDAT; the signature and IHDR still look like PNG, so
# the failure must come from the real decoder, not from MIME sniffing.
data[len(data) // 2] ^= 0xff
return bytes(data)
def fixture_bytes(name='sample.png'):
return (ROOT / 'tests' / 'fixtures' / name).read_bytes()
def write_json(path, value):
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(json.dumps(value, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
return target
+127
View File
@@ -0,0 +1,127 @@
#!/usr/bin/env python3
"""Operator evidence for lab4 persistence: real containers restarted, volumes kept.
The public `make test-persistence` proves the contract result. This script adds
the missing infrastructure evidence: every API/PostgreSQL/Valkey/S3 container
has the same id but a new StartedAt, the named volumes are unchanged, and the
same token, message and original attachment still work afterwards.
Python 3.9+, standard library only. Requires the running stand and Docker.
"""
import json
import subprocess
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check # noqa: E402
import lab4_metrics as M # noqa: E402
EVIDENCE = ROOT / 'evidence' / 'resilience'
def snapshot():
state = {'services': {}, 'volumes': [], 'captured_at': M.now_iso()}
for service in ('api', 'postgres', 'valkey', 's3'):
state['services'][service] = []
for item in M.containers(service):
data = M.inspect(item['container_id'])
state['services'][service].append({
'container_id': item['container_id'],
'name': item['name'],
'started_at': data['State'].get('StartedAt'),
'restart_count': data['RestartCount'],
'image_id': item['image_id'],
'volumes': [mount.get('Name') for mount in data.get('Mounts', [])
if mount.get('Type') == 'volume'],
})
volumes = M.run(['docker', 'volume', 'ls', '--format', '{{.Name}}']).stdout.splitlines()
state['volumes'] = sorted(name for name in volumes if name.startswith(M.PROJECT + '-'))
return state
def main():
args = arguments('Lab4 persistence infrastructure evidence; restarts the stand')
EVIDENCE.mkdir(parents=True, exist_ok=True)
c = Client(args.base_url, args.ca_file)
alice, bob, chat = None, None, None
alice, bob, eve, chat = c.bootstrap()
message = c.message(alice, chat, 'persistence evidence ' + uuid.uuid4().hex)['json']
attachment, content = c.attachment(alice, chat)
before = snapshot()
check(len(before['services']['api']) >= 2, 'need at least two API replicas')
check(len(before['volumes']) >= 3, 'expected pgdata, valkeydata and s3data volumes')
started = M.now_iso()
print('running scripts/restart.sh (all API replicas and used stores, volumes kept)')
process = subprocess.run([str(ROOT / 'scripts/restart.sh')], cwd=str(ROOT),
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
check(process.returncode == 0, 'restart.sh failed: ' + process.stderr.strip()[-500:])
finished = M.now_iso()
M.wait_ready(120)
after = snapshot()
checks = {}
checks['same_container_ids'] = all(
before['services'][service][index]['container_id'] == after['services'][service][index]['container_id']
for service in before['services'] for index in range(len(before['services'][service])))
checks['started_at_changed'] = all(
before['services'][service][index]['started_at'] != after['services'][service][index]['started_at']
for service in before['services'] for index in range(len(before['services'][service])))
checks['all_services_restarted'] = all(
len(before['services'][service]) == len(after['services'][service])
for service in before['services'])
checks['volumes_unchanged'] = before['volumes'] == after['volumes']
# Same token, no re-login. The session lives in the restarted Valkey with
# an absolute deadline; the original attachment lives in the restarted S3
# with its metadata in PostgreSQL.
me = c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['json']
checks['same_token_still_valid'] = me['id'] == alice['id']
page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100',
actor=bob, schema='MessagePage')['json']
checks['message_survived'] = any(item == message for item in page['items'])
metadata = c.call('GET', '/api/v1/attachments/' + attachment['id'], actor=bob, schema='Attachment')['json']
checks['attachment_metadata_survived'] = metadata['sha256'] == attachment['sha256']
download = c.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob)
checks['attachment_bytes_survived'] = download['bytes'] == content
failed = [key for key, value in checks.items() if not value]
result = {
'checked_at': M.now_iso(),
'base_url': args.base_url,
'git_revision': M.run(['git', 'rev-parse', 'HEAD']).stdout.strip(),
'restart_started_at': started,
'restart_finished_at': finished,
'hook_exit_code': process.returncode,
'hook_stdout': process.stdout,
'hook_stderr': process.stderr,
'before': before,
'after': after,
'checks': checks,
'result': 'PASS' if not failed else 'FAIL',
'failed': failed,
'notes': [
'Container ids are unchanged: compose restarted real containers, it did not recreate them.',
'StartedAt changed for every API/PostgreSQL/Valkey/S3 container.',
'Named volumes were preserved; no volume was removed or re-created.',
'The public make test-persistence additionally checks the contract with the old token.',
],
}
M.write_json(EVIDENCE / 'persistence.json', result)
print(json.dumps({'result': result['result'], 'checks': checks}, ensure_ascii=False))
if failed:
raise SystemExit('FAILED checks: ' + ', '.join(failed))
print('PASS: real containers restarted, volumes and data preserved')
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Run the public and own black-box suites with the oldest promised Python
# (system Python 3.9 on this machine) against the running stand.
set -eu
cd "$(dirname "$0")/.."
base_url=${BASE_URL:-http://127.0.0.1:8084}
/usr/bin/python3 --version
/usr/bin/python3 -m py_compile scripts/*.py student-tests/*.py tests/*.py
/usr/bin/python3 scripts/check_contract.py
/usr/bin/python3 tests/smoke.py --base-url "$base_url"
/usr/bin/python3 student-tests/blackbox.py --base-url "$base_url"
echo "PASS: Python 3.9 compilation, public smoke and student black-box suite"
+56
View File
@@ -0,0 +1,56 @@
#!/bin/sh
# Restart the API and every state store this lab uses, keeping the named
# volumes and all data. This is the hook for:
# make test-persistence ACTION_SCRIPT=scripts/restart.sh
#
# It never removes volumes, never re-seeds and never prints credentials.
set -eu
cd "$(dirname "$0")/.."
if [ ! -f .env ]; then
echo "restart.sh: .env is missing; run make env first" >&2
exit 2
fi
compose="./scripts/compose.sh --env-file .env"
wait_healthy() {
container=$1
attempts=0
while [ "$attempts" -lt 60 ]; do
status=$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$container" 2>/dev/null || echo missing)
if [ "$status" = "healthy" ] || [ "$status" = "running" ]; then
return 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "restart.sh: $container did not become healthy" >&2
return 1
}
echo "restart.sh: restarting shared postgres, valkey and the private S3 store (volumes kept)"
postgres=$($compose ps -q postgres)
valkey=$($compose ps -q valkey)
s3=$($compose ps -q s3)
$compose restart postgres valkey s3
wait_healthy "$postgres"
wait_healthy "$valkey"
wait_healthy "$s3"
echo "restart.sh: restarting every api replica"
$compose restart api
for container in $($compose ps -q api); do
wait_healthy "$container"
done
attempts=0
while [ "$attempts" -lt 90 ]; do
if curl -fsS -o /dev/null "http://127.0.0.1:${LB_PORT:-8084}/health/ready" 2>/dev/null; then
echo "restart.sh: all lab4 services restarted; volumes preserved"
exit 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "restart.sh: LB readiness did not recover" >&2
exit 1
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
# Stop exactly the API replica that served TARGET_INSTANCE_ID and leave it
# stopped. This is the hook for:
# make test-failover ACTION_SCRIPT=scripts/stop-one.sh
#
# X-Instance-Id is the container hostname in lab4, so the mapping is an exact
# identity match, not a guess from a header prefix. The script touches only
# that one API container: no DB, no sessions, no volumes, no LB.
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
if [ ! -f .env ]; then
echo "stop-one.sh: .env is missing; run make env first" >&2
exit 2
fi
target=""
for container in $(./scripts/compose.sh --env-file .env ps -q api); do
hostname=$(docker inspect -f '{{.Config.Hostname}}' "$container" 2>/dev/null || true)
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
target=$container
break
fi
done
if [ -z "$target" ]; then
echo "stop-one.sh: no running API container has hostname $TARGET_INSTANCE_ID" >&2
exit 1
fi
echo "stop-one.sh: stopping API container $target (instance $TARGET_INSTANCE_ID)"
# SIGTERM starts the drain window; compose stop_grace_period is 15 s and the
# application's hard shutdown budget is 6 s, so this returns well within the
# test's 10 s hook budget. The container stays stopped afterwards.
docker stop --time 15 "$target" >/dev/null
state=$(docker inspect -f '{{.State.Status}}' "$target")
if [ "$state" != "exited" ] && [ "$state" != "dead" ]; then
echo "stop-one.sh: container state is $state, expected exited" >&2
exit 1
fi
echo "stop-one.sh: container $target is $state; other replicas keep serving"
+448
View File
@@ -0,0 +1,448 @@
#!/usr/bin/env python3
"""Track 2: repeatable reconciler experiment for the two lab4 stores.
Hypothesis: a single-pass reconciler that compares PostgreSQL attachment rows
with the private bucket, protects everything younger than a configurable grace
period, and re-reads each row immediately before a mutation can remove only
provably unreferenced stale objects and stale upload intents. It must never
delete a ready attachment that a message uses, a fresh upload in flight, or a
file whose metadata and bytes still agree, and it must not invent missing
bytes or report a missing object as ready.
Protocol:
1. create a reproducible base set of attachments (half linked to messages);
2. measure clean dry-run scans (cost of the traversal);
3. inject real faults on both sides:
- stale orphan object (S3 has no metadata row),
- stale pending intent with object (crash between PUT and COMMIT),
- stale pending intent without object,
- ready metadata whose object is gone (missing, used and unused),
- fresh orphan object and fresh pending intent (must be protected);
4. dry-run (no mutations), verify findings and unchanged counts;
5. apply, verify only the provable stale items changed;
6. rerun apply immediately (no new deletions while fresh items are young);
7. wait past the grace period and apply again: the fresh orphan is then old
enough to remove, while a completed real attachment stays intact;
8. verify the API still serves used attachments and new uploads.
Python 3.9+, standard library only. Requires the running stand and Docker.
Raw reports and a compact summary are written under evidence/track2/.
"""
import concurrent.futures
import hashlib
import json
import statistics
import subprocess
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check # noqa: E402
import lab4_metrics as M # noqa: E402
EVIDENCE = ROOT / 'evidence' / 'track2'
BASE_SIZE = 300
USED_SIZE = 150
GRACE = 20
RESULTS = []
def ok(condition, message):
RESULTS.append({'check': message, 'passed': bool(condition)})
check(condition, message)
def reconcile(apply, grace, output_path):
command = [
str(ROOT / 'scripts/compose.sh'), '--env-file', '.env', 'run', '--rm', '--no-deps', '-T',
'--entrypoint', '/app/reconciler', 'api', '-prefix', 'attachments/', '-grace', '%ds' % grace,
]
if apply:
command.append('-apply')
started = M.now_iso()
process = M.run(command)
finished = M.now_iso()
report = json.loads(process.stdout.strip())
report['_invocation'] = {'command': ' '.join(command), 'started_at': started, 'finished_at': finished}
M.write_json(output_path, report)
return report
def object_keys(report, section):
return {item['object_key'] for item in (report['findings'].get(section) or [])}
def item_ids(report, section):
return {item['id'] for item in (report['findings'].get(section) or []) if item.get('id')}
def attachment_count(status=None):
where = '' if status is None else " WHERE status = '%s'" % status
return int(M.psql('SELECT count(*) FROM attachments' + where))
def link_count():
return int(M.psql('SELECT count(*) FROM message_attachments'))
def object_exists(key):
return M.s3ctl('-op', 'stat', '-key', key, check=False).returncode == 0
def put_object(key, data, container=None):
container = container or M.compose_ids('api')[0]
name = '/tmp/lab4-track2-object.bin'
process = subprocess.run(
['docker', 'exec', '-i', container, 'sh', '-c', 'cat > ' + name],
input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
if process.returncode != 0:
raise RuntimeError('could not stage object in API container')
M.s3ctl('-op', 'put', '-key', key, '-file', name, '-content-type', 'image/png')
M.run(['docker', 'exec', container, 'rm', '-f', name])
def delete_object(key):
M.s3ctl('-op', 'delete', '-key', key)
def insert_pending(attachment_id, chat_id, owner_id, object_key, data, age_seconds):
M.psql(
"INSERT INTO attachments "
"(id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, error_code, "
" object_key, created_at, updated_at) VALUES "
"('%s'::uuid, '%s'::uuid, '%s'::uuid, 'crash.png', 'image/png', %d, '%s', 'pending', NULL, "
" '%s', now() - interval '%d seconds', now() - interval '%d seconds')" % (
attachment_id, chat_id, owner_id, len(data), hashlib.sha256(data).hexdigest(),
object_key, age_seconds, age_seconds))
def promote_ready(attachment_id):
M.psql("UPDATE attachments SET status = 'ready', updated_at = now() "
"WHERE id = '%s'::uuid AND status = 'pending'" % attachment_id)
def all_messages(c, actor, chat):
from urllib.parse import quote
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100'
items, seen = [], set()
for _ in range(1000):
page = c.call('GET', path, actor=actor, schema='MessagePage')['json']
items.extend(page['items'])
cursor = page['next_cursor']
if cursor is None:
return items
if cursor in seen:
raise Failure('message cursor cycle')
seen.add(cursor)
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100&cursor=' + quote(cursor, safe='')
raise Failure('message history exceeded safety bound')
def sleep_until_age(started_monotonic, grace, margin=1.5):
while time.monotonic() - started_monotonic < grace + margin:
time.sleep(0.25)
def main():
args = arguments('Track 2 reconciler experiment; injects faults into SQL and S3')
EVIDENCE.mkdir(parents=True, exist_ok=True)
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
sample = M.fixture_bytes('sample.png')
sha = hashlib.sha256(sample).hexdigest()
revision = M.run(['git', 'rev-parse', 'HEAD']).stdout.strip()
api_image = M.containers('api')[0]['image_id']
print('== reproducible base set ==')
rows_pre = attachment_count()
objects_pre = M.s3_count()
attachments = []
for index in range(BASE_SIZE):
response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=track2-%03d.png' % index,
201, actor=alice, raw=sample, headers={'Content-Type': 'image/png'},
schema='Attachment')
attachments.append({'id': response['json']['id'], 'used': False,
'size_bytes': response['json']['size_bytes']})
used_messages = []
for index in range(USED_SIZE // 10):
chosen = attachments[index * 10:(index + 1) * 10]
message = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': 'track2 link %02d' % index,
'attachment_ids': [item['id'] for item in chosen]},
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')['json']
used_messages.append(message)
for item in chosen:
item['used'] = True
used = [item for item in attachments if item['used']]
unused = [item for item in attachments if not item['used']]
ok(len(attachments) == BASE_SIZE and len(used) == USED_SIZE and len(unused) == BASE_SIZE - USED_SIZE,
'base attachment set is incomplete')
ok(all(message['attachment_ids'] == [item['id'] for item in attachments[index * 10:(index + 1) * 10]]
for index, message in enumerate(used_messages)), 'message attachments were reordered')
baseline_rows = attachment_count() - rows_pre
baseline_objects = M.s3_count() - objects_pre
baseline_links = link_count()
ok(baseline_rows == BASE_SIZE and baseline_objects == BASE_SIZE,
'base rows/objects were not exactly the %d uploads' % BASE_SIZE)
# A previous interrupted run may have left stale pending rows/orphans.
# One preliminary apply makes the cost baseline honest on a reused stand;
# on a clean stand it deletes nothing.
cleanup = reconcile(True, GRACE, EVIDENCE / 'raw-cleanup.json')
cleanup_deleted = list(cleanup['actions'].get('deleted_objects') or []) + list(
cleanup['actions'].get('deleted_pending_rows') or [])
if cleanup_deleted:
print('pre-run cleanup removed %d leftovers from an earlier interrupted run' % len(cleanup_deleted))
print('== cost of a clean traversal ==')
cost_runs = []
for index in range(3):
report = reconcile(False, 3600, EVIDENCE / ('raw-cost-%d.json' % index))
cost_runs.append({
'run': index + 1,
'generated_at': report['generated_at'],
'db_scan_ms': report['timing']['db_scan_ms'],
's3_list_ms': report['timing']['s3_list_ms'],
'total_ms': report['timing']['total_ms'],
'db_rows': report['timing']['db_rows'],
's3_objects': report['timing']['s3_objects'],
})
ok(all(run['db_rows'] >= BASE_SIZE and run['s3_objects'] >= BASE_SIZE for run in cost_runs),
'cost run did not scan the full base set')
print('== inject faults on both sides ==')
stale_started = time.monotonic()
stale_orphan = 'attachments/orphan-stale-' + uuid.uuid4().hex
put_object(stale_orphan, sample)
crash_one = str(uuid.uuid4())
crash_one_key = 'attachments/' + crash_one
insert_pending(crash_one, chat['id'], alice['id'], crash_one_key, sample, 60)
put_object(crash_one_key, sample)
crash_two = str(uuid.uuid4())
crash_two_key = 'attachments/' + crash_two
insert_pending(crash_two, chat['id'], alice['id'], crash_two_key, sample, 60)
missing_used = used[0]
missing_unused = unused[0]
missing_used_key = M.psql("SELECT object_key FROM attachments WHERE id = '%s'::uuid" % missing_used['id'])
missing_unused_key = M.psql("SELECT object_key FROM attachments WHERE id = '%s'::uuid" % missing_unused['id'])
delete_object(missing_used_key)
delete_object(missing_unused_key)
ok(not object_exists(missing_used_key) and not object_exists(missing_unused_key),
'missing objects were not removed from S3')
# The stale orphan must be older than the grace period. The injected rows
# are already older by construction; the S3 object uses its real mtime.
sleep_until_age(stale_started, GRACE)
active_id = str(uuid.uuid4())
active_key = 'attachments/' + active_id
insert_pending(active_id, chat['id'], alice['id'], active_key, sample, 0)
put_object(active_key, sample)
fresh_orphan = 'attachments/orphan-fresh-' + uuid.uuid4().hex
put_object(fresh_orphan, sample)
fresh_started = time.monotonic()
rows_before = attachment_count()
objects_before = M.s3_count()
links_before = link_count()
print('== dry run: detection without mutation ==')
dry = reconcile(False, GRACE, EVIDENCE / 'raw-dry-run.json')
ok(stale_orphan in object_keys(dry, 'orphan_objects'), 'stale orphan object not detected')
ok(fresh_orphan in object_keys(dry, 'protected_recent_objects'), 'fresh orphan object not protected')
ok({crash_one, crash_two} <= item_ids(dry, 'stale_pending'), 'stale upload intents not detected')
ok(active_id in item_ids(dry, 'protected_pending'), 'fresh upload intent not protected')
ok({missing_used['id'], missing_unused['id']} <= item_ids(dry, 'missing_objects'),
'missing objects not detected')
ok(not (dry['actions'].get('deleted_objects') or []), 'dry run deleted objects')
ok(not (dry['actions'].get('deleted_pending_rows') or []), 'dry run deleted rows')
ok(attachment_count() == rows_before and M.s3_count() == objects_before and link_count() == links_before,
'dry run mutated either store')
ok(object_exists(stale_orphan) and object_exists(fresh_orphan), 'dry run removed an object')
ok(object_exists(active_key), 'dry run removed an active upload object')
print('== apply: only provable stale items ==')
def upload_worker(index):
local = Client(c.base)
response = local.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=concurrent-%d.png' % index,
201, actor=alice, raw=sample, headers={'Content-Type': 'image/png'}, schema='Attachment')
return response['json']
upload_pool = concurrent.futures.ThreadPoolExecutor(max_workers=6)
upload_futures = [upload_pool.submit(upload_worker, index) for index in range(6)]
# Run the reconciler while those uploads are in flight. Their rows/objects
# are younger than the grace period and must not be touched.
apply = reconcile(True, GRACE, EVIDENCE / 'raw-apply.json')
uploaded_concurrently = [future.result() for future in upload_futures]
upload_pool.shutdown()
ok(all(item['status'] == 'ready' for item in uploaded_concurrently),
'concurrent upload during reconcile did not finish ready')
deleted_objects = set(apply['actions'].get('deleted_objects') or [])
deleted_rows = set(apply['actions'].get('deleted_pending_rows') or [])
ok(stale_orphan in deleted_objects, 'stale orphan object was not removed')
ok(crash_one in deleted_rows and crash_two in deleted_rows, 'stale pending rows were not removed')
ok(crash_one_key in deleted_objects, 'stale pending object was not removed')
ok(not object_exists(stale_orphan) and not object_exists(crash_one_key) and not object_exists(crash_two_key),
'stale S3 objects survived apply')
ok(M.psql("SELECT count(*) FROM attachments WHERE id IN ('%s'::uuid, '%s'::uuid)" % (crash_one, crash_two)).strip() == '0',
'stale pending rows survived apply')
ok(object_exists(fresh_orphan), 'fresh orphan object was deleted inside grace')
rows_after_apply = rows_before + len(uploaded_concurrently) - 2
ok(object_exists(active_key) and attachment_count() == rows_after_apply,
'active upload, concurrent upload or active row was deleted')
ok({missing_used['id'], missing_unused['id']} <= set(apply['actions'].get('unresolved_missing') or []),
'missing objects were not left for manual recovery')
ok(link_count() == links_before, 'apply changed message attachment links')
ok(M.psql("SELECT status FROM attachments WHERE id = '%s'::uuid" % active_id).strip() == 'pending',
'active upload intent changed state unexpectedly')
# The simulated in-flight upload completes: the same row is promoted ready
# and becomes usable, proving the reconciler protected a real file.
promote_ready(active_id)
active_message = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': '', 'attachment_ids': [active_id]},
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')['json']
ok(active_message['attachment_ids'] == [active_id], 'protected upload cannot be attached after completion')
active_download = c.call('GET', '/api/v1/attachments/' + active_id + '/content', actor=bob)
ok(active_download['bytes'] == sample, 'protected upload bytes changed')
print('== rerun before grace expiry: no new deletions ==')
rerun = reconcile(True, GRACE, EVIDENCE / 'raw-rerun.json')
ok(not (rerun['actions'].get('deleted_objects') or []), 'rerun deleted objects')
ok(not (rerun['actions'].get('deleted_pending_rows') or []), 'rerun deleted rows')
ok(fresh_orphan in object_keys(rerun, 'protected_recent_objects'), 'fresh orphan lost protection on rerun')
ok(object_exists(fresh_orphan), 'fresh orphan removed on rerun')
print('== grace expiry: the fresh orphan is now old enough ==')
sleep_until_age(fresh_started, GRACE)
expired = reconcile(True, GRACE, EVIDENCE / 'raw-after-grace.json')
ok(fresh_orphan in set(expired['actions'].get('deleted_objects') or []),
'aged orphan was not removed after grace')
ok(not object_exists(fresh_orphan), 'aged orphan object still exists')
ok(attachment_count() == rows_after_apply, 'grace expiry deleted a metadata row')
ok(c.call('GET', '/api/v1/attachments/' + active_id + '/content', actor=bob)['bytes'] == sample,
'completed protected attachment lost after grace expiry')
print('== API and used attachments after reconciliation ==')
history = all_messages(c, bob, chat)
indexed = {item['id']: item for item in history}
for message in used_messages:
ok(message['id'] in indexed, 'used message disappeared from history')
ok(indexed[message['id']]['attachment_ids'] == message['attachment_ids'],
'used message lost or reordered its attachment links')
sample_used = used[10]
download = c.call('GET', '/api/v1/attachments/' + sample_used['id'] + '/content', actor=bob)
ok(download['bytes'] == sample, 'used attachment bytes changed or disappeared')
c.call('GET', '/api/v1/attachments/' + sample_used['id'], 404, actor=eve)
c.call('GET', '/api/v1/attachments/' + missing_used['id'], 404, actor=bob)
c.call('GET', '/api/v1/attachments/' + missing_unused['id'] + '/content', 404, actor=bob)
new_attachment = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=after.png', 201,
actor=alice, raw=sample, headers={'Content-Type': 'image/png'},
schema='Attachment')['json']
ok(new_attachment['sha256'] == sha, 'new upload after reconciliation failed')
failures = [item for item in RESULTS if not item['passed']]
summary = {
'track': 'Track 2: consistency of two stores',
'hypothesis': ('A grace-protected, re-checked reconciler removes only stale orphan objects and '
'stale upload intents, and never deletes ready/used/fresh attachments or invents '
'missing bytes.'),
'generated_at': M.now_iso(),
'git_revision': revision,
'api_image_id': api_image,
'database_rows_base': baseline_rows,
'object_store_objects_base': baseline_objects,
'message_attachment_links_base': baseline_links,
'base_profile': {
'attachments': BASE_SIZE,
'linked_attachments': USED_SIZE,
'unlinked_ready_attachments': BASE_SIZE - USED_SIZE,
'bytes_per_attachment': len(sample),
'total_attachment_bytes': BASE_SIZE * len(sample),
'image_profile': 'tests/fixtures/sample.png 320x200, identical synthetic bytes',
},
'grace_seconds': GRACE,
'cost_runs': cost_runs,
'cost_summary': {
'runs': len(cost_runs),
'db_scan_ms_median': statistics.median(run['db_scan_ms'] for run in cost_runs),
's3_list_ms_median': statistics.median(run['s3_list_ms'] for run in cost_runs),
'total_ms_median': statistics.median(run['total_ms'] for run in cost_runs),
'note': 'traversal cost is O(rows + objects); timings are wall-clock milliseconds '
'reported by the reconciler process on this local stand',
},
'injected': {
'stale_orphan_object': stale_orphan,
'stale_pending_with_object': {'id': crash_one, 'object_key': crash_one_key},
'stale_pending_without_object': {'id': crash_two, 'object_key': crash_two_key},
'missing_used_attachment': {'id': missing_used['id'], 'object_key': missing_used_key},
'missing_unused_attachment': {'id': missing_unused['id'], 'object_key': missing_unused_key},
'fresh_orphan_object': fresh_orphan,
'active_upload_intent': {'id': active_id, 'object_key': active_key},
},
'dry_run': {
'orphan_objects': sorted(object_keys(dry, 'orphan_objects')),
'protected_recent_objects': sorted(object_keys(dry, 'protected_recent_objects')),
'stale_pending': sorted(item_ids(dry, 'stale_pending')),
'protected_pending': sorted(item_ids(dry, 'protected_pending')),
'missing_objects': sorted(item_ids(dry, 'missing_objects')),
'deleted_objects': dry['actions'].get('deleted_objects') or [],
'deleted_pending_rows': dry['actions'].get('deleted_pending_rows') or [],
},
'apply': {
'deleted_objects': sorted(deleted_objects),
'deleted_pending_rows': sorted(deleted_rows),
'unresolved_missing': apply['actions'].get('unresolved_missing') or [],
},
'rerun': {
'deleted_objects': rerun['actions'].get('deleted_objects') or [],
'deleted_pending_rows': rerun['actions'].get('deleted_pending_rows') or [],
},
'after_grace': {
'deleted_objects': expired['actions'].get('deleted_objects') or [],
'deleted_pending_rows': expired['actions'].get('deleted_pending_rows') or [],
},
'assertions': RESULTS,
'assertions_failed': len(failures),
'result': 'PASS' if not failures else 'FAIL',
'limitations': [
'The reconciler never deletes or fabricates a missing original: bytes cannot be restored '
'automatically, so those rows are reported as unresolved for operator recovery.',
'A simulated in-flight upload row is used as the deterministic active state; real concurrent '
'uploads are additionally exercised and must finish ready.',
'Cost is measured on this 2 vCPU / ~2 GiB Colima stand and does not extrapolate to production.',
'The S3 ListObjects scan is not a snapshot: concurrent uploads are protected by the grace '
'period and by the immediate database re-check before each delete.',
],
}
M.write_json(EVIDENCE / 'dataset.json', {
'generated_at': summary['generated_at'],
'base_profile': summary['base_profile'],
'attachments': attachments,
'used_messages': [{'id': item['id'], 'attachment_ids': item['attachment_ids']} for item in used_messages],
'concurrent_uploads': [item['id'] for item in uploaded_concurrently],
})
M.write_json(EVIDENCE / 'summary.json', summary)
print(json.dumps({'result': summary['result'], 'assertions': len(RESULTS),
'failed': len(failures), 'cost_ms_median': summary['cost_summary']['total_ms_median']},
ensure_ascii=False))
if failures:
raise SystemExit('FAILED checks: ' + ', '.join(item['check'] for item in failures))
print('PASS: track 2 reconciler experiment')
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
+335
View File
@@ -0,0 +1,335 @@
#!/usr/bin/env python3
"""Mandatory lab4 upload experiment: >=10 simultaneous uploads + API memory.
Metrics and units (do not confuse them):
* process RSS: VmRSS from /proc/1/status inside each API container, bytes.
This is the resident set of the API process (PID 1), sampled by `docker exec`.
* process peak RSS (HWM): VmHWM from the same file, bytes. The kernel high-water
mark since that process started; the API is restarted before the run so the
baseline is fresh.
* cgroup memory.current / memory.peak: the whole container cgroup, bytes,
including page cache and any other process. It is reported separately and
is NOT presented as process RSS.
The run uploads a reproducible profile of generated PNGs (no giant fixtures in
Git), records real UTC timestamps, per-upload intervals, observed concurrency,
HTTP results and the Sampled RSS of both API replicas. Raw samples and the
compact summary are stored under evidence/experiment/.
Python 3.9+, standard library only. Requires the running stand and Docker.
"""
import concurrent.futures
import datetime as dt
import hashlib
import json
import sys
import threading
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check # noqa: E402
import lab4_metrics as M # noqa: E402
EVIDENCE = ROOT / 'evidence' / 'experiment'
CONCURRENCY = 12
SAMPLE_INTERVAL_SECONDS = 0.2
def iso_now():
return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
def process_memory(container):
process = M.run(['docker', 'exec', container, 'cat', '/proc/1/status'], check=False)
if process.returncode != 0:
return None
values = {}
for line in process.stdout.splitlines():
if line.startswith('VmRSS:'):
values['rss_bytes'] = int(line.split()[1]) * 1024
elif line.startswith('VmHWM:'):
values['hwm_bytes'] = int(line.split()[1]) * 1024
return values
def cgroup_memory(container):
result = {}
current = M.run(['docker', 'exec', container, 'cat', '/sys/fs/cgroup/memory.current'], check=False)
peak = M.run(['docker', 'exec', container, 'cat', '/sys/fs/cgroup/memory.peak'], check=False)
if current.returncode == 0:
result['current_bytes'] = int(current.stdout.strip())
if peak.returncode == 0:
result['peak_bytes'] = int(peak.stdout.strip())
return result or None
class Sampler(threading.Thread):
def __init__(self, containers):
super().__init__(daemon=True)
self.containers = containers
self.samples = []
self.error = None
self._stop_event = threading.Event() # never name this Thread._stop
def run(self):
try:
while not self._stop_event.is_set():
started = iso_now()
monotonic = time.monotonic()
row = {'sampled_at': started, 'monotonic_seconds': round(monotonic, 6), 'api': {}}
for container in self.containers:
row['api'][container['hostname']] = {
'process': process_memory(container['container_id']),
'cgroup': cgroup_memory(container['container_id']),
}
self.samples.append(row)
self._stop_event.wait(SAMPLE_INTERVAL_SECONDS)
except Exception as exc: # noqa: BLE001 - reported in the summary
self.error = type(exc).__name__ + ': ' + str(exc)
def stop(self):
self._stop_event.set()
def main():
args = arguments('Lab4 >=10 concurrent uploads with API process RSS sampling')
EVIDENCE.mkdir(parents=True, exist_ok=True)
api = M.containers('api')
check(len(api) >= 2, 'the experiment needs at least two API replicas')
api_limit = M.inspect(api[0]['container_id'])['HostConfig'].get('Memory')
gomemlimit = api[0]['env'].get('GOMEMLIMIT', '')
decode_concurrency = api[0]['env'].get('UPLOAD_DECODE_CONCURRENCY', '')
put_concurrency = api[0]['env'].get('S3_PUT_CONCURRENCY', '')
max_upload = api[0]['env'].get('MAX_UPLOAD_BYTES', '')
max_pixels = api[0]['env'].get('MAX_IMAGE_PIXELS', '')
revision = M.run(['git', 'rev-parse', 'HEAD']).stdout.strip()
image_id = api[0]['image_id']
print('== restart API replicas to reset the process high-water mark ==')
M.compose('restart', 'api')
M.wait_ready(120)
api = M.containers('api')
check(len(api) >= 2, 'API replicas did not come back')
restarts_before = {item['hostname']: M.inspect(item['container_id'])['RestartCount'] for item in api}
baseline = {}
for item in api:
baseline[item['hostname']] = {
'process': process_memory(item['container_id']),
'cgroup': cgroup_memory(item['container_id']),
}
print('== generate the reproducible upload profile ==')
profiles = []
for index in range(CONCURRENCY):
if index < 6:
width, height = 1000, 700
profile = 'small'
elif index < 10:
width, height = 1500, 1100
profile = 'medium'
else:
width, height = 1600, 2167
profile = 'near-max-bytes'
data = M.png_random(width, height, seed=1000 + index)
profiles.append({
'index': index,
'profile': profile,
'filename': 'load-%02d.png' % index,
'width': width,
'height': height,
'pixels': width * height,
'bytes': len(data),
'sha256': hashlib.sha256(data).hexdigest(),
'content': data,
})
check(all(item['pixels'] <= 40_000_000 and item['bytes'] <= 10 * 1024 * 1024 for item in profiles),
'generated profile violates contract limits')
check(max(item['bytes'] for item in profiles) > 10 * 1024 * 1024 - 100000,
'profile does not include a near-limit file')
client = Client(args.base_url, args.ca_file, timeout=60)
alice, bob, eve, chat = client.bootstrap()
barrier = threading.Barrier(CONCURRENCY)
def upload(item):
local = Client(args.base_url, args.ca_file, timeout=60)
barrier.wait()
started_monotonic = time.monotonic()
started_utc = iso_now()
response = local.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + item['filename'],
201, actor=alice, raw=item['content'],
headers={'Content-Type': 'image/png'}, schema='Attachment')
finished_monotonic = time.monotonic()
return {
'index': item['index'],
'profile': item['profile'],
'filename': item['filename'],
'width': item['width'],
'height': item['height'],
'pixels': item['pixels'],
'bytes': item['bytes'],
'sha256': item['sha256'],
'started_at': started_utc,
'finished_at': iso_now(),
'started_monotonic': started_monotonic,
'finished_monotonic': finished_monotonic,
'duration_ms': round((finished_monotonic - started_monotonic) * 1000, 3),
'status': response['status'],
'instance_id': response['headers'].get('X-Instance-Id', ''),
'attachment_id': response['json']['id'],
'server_sha256': response['json']['sha256'],
'server_size_bytes': response['json']['size_bytes'],
'server_status': response['json']['status'],
}
sampler = Sampler(api)
sampler.start()
started_utc = iso_now()
started_monotonic = time.monotonic()
with concurrent.futures.ThreadPoolExecutor(max_workers=CONCURRENCY) as pool:
results = list(pool.map(upload, profiles))
finished_monotonic = time.monotonic()
finished_utc = iso_now()
time.sleep(0.5)
sampler.stop()
sampler.join(timeout=5)
check(sampler.error is None, 'memory sampler failed: ' + str(sampler.error))
# Observed concurrency from the real client intervals.
events = []
for item in results:
events.append((item['started_monotonic'], 1))
events.append((item['finished_monotonic'], -1))
active = peak = 0
for _, delta in sorted(events, key=lambda pair: (pair[0], -pair[1])):
active += delta
peak = max(peak, active)
per_instance = {}
for item in results:
bucket = per_instance.setdefault(item['instance_id'], {'uploads': 0, 'bytes': 0})
bucket['uploads'] += 1
bucket['bytes'] += item['bytes']
memory = {}
for hostname in baseline:
rss = [row['api'][hostname]['process']['rss_bytes']
for row in sampler.samples
if row['api'].get(hostname) and row['api'][hostname]['process']]
hwm = [row['api'][hostname]['process']['hwm_bytes']
for row in sampler.samples
if row['api'].get(hostname) and row['api'][hostname]['process']]
cgroup = [row['api'][hostname]['cgroup']['current_bytes']
for row in sampler.samples
if row['api'].get(hostname) and row['api'][hostname]['cgroup']]
cgroup_peak = [row['api'][hostname]['cgroup']['peak_bytes']
for row in sampler.samples
if row['api'].get(hostname) and row['api'][hostname]['cgroup']]
memory[hostname] = {
'samples': len(rss),
'baseline_rss_bytes': baseline[hostname]['process']['rss_bytes'] if baseline[hostname]['process'] else None,
'baseline_hwm_bytes': baseline[hostname]['process']['hwm_bytes'] if baseline[hostname]['process'] else None,
'peak_sampled_rss_bytes': max(rss) if rss else None,
'peak_sampled_rss_delta_bytes': (max(rss) - baseline[hostname]['process']['rss_bytes'])
if rss and baseline[hostname]['process'] else None,
'final_hwm_bytes': hwm[-1] if hwm else None,
'peak_cgroup_current_bytes': max(cgroup) if cgroup else None,
'peak_cgroup_memory_peak_bytes': max(cgroup_peak) if cgroup_peak else None,
'api_memory_limit_bytes': api_limit,
}
successes = [item for item in results if item['status'] == 201 and item['server_status'] == 'ready'
and item['server_sha256'] == item['sha256'] and item['server_size_bytes'] == item['bytes']]
failures = [item for item in results if item not in successes]
restarts_after = {item['hostname']: M.inspect(item['container_id'])['RestartCount'] for item in api}
check(len(results) == CONCURRENCY, 'not all uploads returned')
check(len(successes) == CONCURRENCY, 'some uploads failed')
check(peak >= 10, 'observed concurrency below 10: %d' % peak)
check(not failures, 'failed uploads: %r' % [(item['index'], item['status']) for item in failures])
check(restarts_after == restarts_before, 'an API container restarted during the experiment')
for hostname, item in memory.items():
check(item['peak_sampled_rss_bytes'] and item['peak_sampled_rss_bytes'] < api_limit,
'process RSS exceeded the container limit on ' + hostname)
summary = {
'experiment': 'lab4 concurrent upload: peak API process RSS',
'generated_at': iso_now(),
'git_revision': revision,
'api_image_id': image_id,
'base_url': args.base_url,
'started_at': started_utc,
'finished_at': finished_utc,
'wall_seconds': round(finished_monotonic - started_monotonic, 3),
'configured_concurrency': CONCURRENCY,
'observed_peak_concurrency': peak,
'successful_uploads': len(successes),
'failed_uploads': len(failures),
'api_instances': sorted(per_instance),
'uploads_per_instance': per_instance,
'profile': {
'files': len(profiles),
'total_bytes': sum(item['bytes'] for item in profiles),
'min_bytes': min(item['bytes'] for item in profiles),
'max_bytes': max(item['bytes'] for item in profiles),
'max_pixels': max(item['pixels'] for item in profiles),
'small': {'count': 6, 'width': 1000, 'height': 700},
'medium': {'count': 4, 'width': 1500, 'height': 1100},
'near_max_bytes': {'count': 2, 'width': 1600, 'height': 2167},
},
'limits': {
'api_memory_limit_bytes': api_limit,
'GOMEMLIMIT': gomemlimit,
'UPLOAD_DECODE_CONCURRENCY': decode_concurrency,
'S3_PUT_CONCURRENCY': put_concurrency,
'MAX_UPLOAD_BYTES': max_upload,
'MAX_IMAGE_PIXELS': max_pixels,
},
'memory_metrics': {
'process_rss_source': '/proc/1/status VmRSS inside each API container, sampled by docker exec',
'process_hwm_source': '/proc/1/status VmHWM inside each API container',
'cgroup_source': '/sys/fs/cgroup/memory.current and memory.peak (whole container cgroup)',
'sample_interval_seconds': SAMPLE_INTERVAL_SECONDS,
'samples_taken': len(sampler.samples),
'first_sample_at': sampler.samples[0]['sampled_at'] if sampler.samples else None,
'last_sample_at': sampler.samples[-1]['sampled_at'] if sampler.samples else None,
'max_sample_gap_seconds': round(max(
sampler.samples[index]['monotonic_seconds'] - sampler.samples[index - 1]['monotonic_seconds']
for index in range(1, len(sampler.samples))), 3) if len(sampler.samples) > 1 else None,
'per_instance': memory,
},
'uploads': [{key: value for key, value in item.items() if key != 'content'} for item in results],
'result': 'PASS',
'limitations': [
'One local stand: RSS includes Go runtime and handler state, not a production profile.',
'The sampler uses docker exec every 200 ms; a shorter allocation spike between samples is '
'bounded by VmHWM, which is also reported.',
'cgroup memory.current includes page cache and is not process RSS.',
],
}
M.write_json(EVIDENCE / 'uploads.json', summary['uploads'])
M.write_json(EVIDENCE / 'rss-samples.json', {'samples': sampler.samples, 'baseline': baseline})
M.write_json(EVIDENCE / 'summary.json', summary)
print(json.dumps({
'result': 'PASS',
'observed_peak_concurrency': peak,
'successful_uploads': len(successes),
'wall_seconds': summary['wall_seconds'],
'process_peak_sampled_rss_bytes': {key: value['peak_sampled_rss_bytes'] for key, value in memory.items()},
'process_final_hwm_bytes': {key: value['final_hwm_bytes'] for key, value in memory.items()},
'api_memory_limit_bytes': api_limit,
}, ensure_ascii=False))
print('PASS: >=10 concurrent uploads with bounded API process RSS')
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
Regular → Executable
View File
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
# Wait until /health/ready answers 200 through the load balancer.
# Usage: scripts/wait-ready.sh [url]
set -eu
url=${1:-http://127.0.0.1:${LB_PORT:-8084}/health/ready}
attempts=0
while [ "$attempts" -lt 120 ]; do
if curl -fsS -o /dev/null "$url" 2>/dev/null; then
echo "ready: $url"
exit 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "not ready after 120 seconds: $url" >&2
exit 1

Some files were not shown because too many files have changed in this diff Show More