feat: add image attachments to messages

- upload, metadata and download endpoints for PNG/JPEG attachments:
  limits before reading and decompression, type by content,
  structural integrity check without decoding pixels, safe filename
- write order: pending row with object key -> PUT to S3 -> ready;
  per-step DB sessions so no pool connection is held during transfers
- attachment_ids in messages (validation, idempotency hash, history);
  whitespace-only text allowed with an attachment (teacher, 2026-10-20)
- migration: attachments and message_attachments tables, text length
  CHECK relaxed with NOT VALID
- student tests, fault checks and driver commands for attachments;
  rollout profile starts from e1161f7 and checks the commit first
- sync attachments deltas into main specs; rules, AGENTS.md, PLAN.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 01:08:56 +03:00
co-authored by Claude Opus 5.5
parent 73779f7acd
commit 116d8d3bf0
72 changed files with 5546 additions and 247 deletions
+36 -8
View File
@@ -20,7 +20,11 @@ HAProxy на `APP_OUT_PORT` перед репликами API) работают
реплика, `hang-key` — повтор ключа после зависшей реплики,
`cache-check` и `auth-storage` — доказательства исключений сверки
покрытия (кэш, хранение паролей и токенов), `s3-check` (`make
s3_check`) — приватность bucket вне API. `stop-at-start` — остановка
s3_check`) — приватность bucket вне API, `attachment-failover` и
`attachment-storage` — доказательства исключений `attachments`
(остановка реплики, принявшей файл; где лежат байты). `upload` и
`download` — загрузка и скачивание вложения с SHA-256 на любом
сервере. `stop-at-start` — остановка
контейнеров образа во время старта, без стенда. Только
стандартная библиотека Python 3.9+: `make instances` запускает драйвер
системным `python3` (на macOS — 3.9), поэтому без `datetime.UTC`,
@@ -55,8 +59,9 @@ make env_setup # .env (случайные POSTGRES_PASSWORD, VALKEY_PASS
Нужен запущенный Docker: Postgres, Valkey и S3 живут в compose. Без
Postgres сервер стартует, но `/health/ready` отвечает 503; без Valkey
всё работает, но мимо кэша (`warning` «Cache is unavailable» в логе);
без S3 `/health/ready` — 200, а пути вложений (с change `attachments`)
— 503. `driver.py start` сам делает `make upgrade start_cache
без S3 `/health/ready` — 200, а загрузка и скачивание байтов
вложений — 503 (метаданные, сообщения и история работают). S3 нужен
только путям вложений. `driver.py start` сам делает `make upgrade start_cache
start_s3`. В `.env`, созданном до `membership-cache` или `s3-storage`,
нет строк Valkey или S3: их переносят из `.env.example` руками, иначе
compose падает с `… is empty, copy … lines from .env.example`.
@@ -77,12 +82,18 @@ python3 $D status # listeners: [pid reloader, pid worker], ready: True
python3 $D flow # ~60 проверок: регистрация с паролем, вход, 409, неверный пароль,
# 401 с WWW-Authenticate, X-User-Id игнорируется, чат, 5 сообщений,
# пагинация limit=2 по курсору, чужой → 404, 400-е, повтор с ключом,
# 409 на другое тело, без ключа → 400, logout; X-Instance-Id везде
# 409 на другое тело, без ключа → 400, вложение: загрузка fixture,
# сообщение со ссылкой, оригинал Бобу (SHA-256), 404 Еве; logout;
# X-Instance-Id везде
python3 $D req POST /api/v1/users --data '{"username":"zoe_demo","display_name":"Зоя","password":"Zoe-password-1"}'
python3 $D req POST /api/v1/auth/sessions --basic zoe_demo:Zoe-password-1
python3 $D req GET /api/v1/users/me --token <token из ответа выше>
python3 $D req POST /api/v1/chats/<chat>/messages --token <token> --data '{"text":"hi"}'
# печатает idempotency-key; повтор той же отправки — тот же запрос с --key <ключ>
python3 $D upload --token <token> --chat <chat> --file tests/fixtures/sample.png
# 201, x-instance-id, Attachment, SHA-256 файла и «sha256 matches: True»
python3 $D download --token <token> --attachment <id> [--out /tmp/x.png]
# 200, Content-Type, размер, SHA-256 полученного (99ea7533… у fixture)
python3 $D smoke # публичный tests/smoke.py против этого порта
python3 $D student # make student_test BASE_URL=http://localhost:<port> — ~20 с
python3 $D --port 8080 instances # стенд через LB: X-Instance-Id 12 запросов одной сессии
@@ -104,6 +115,10 @@ python3 $D stop
| `cache-check [--require-test-keys]` | только стенд с LB (`--port 8080`): сценарии `chat-cache` «Чтение из кэша», «Срок записи», «Временная база». Два синтетических пользователя и чат; ключ `messenger:v1:<база>:chat:<id>` сразу после 201 (`EXISTS`, TTL ≤ `[cache] chat_ttl_seconds` из реплики, поля значения), `DEL`, через 11 с снимок `seq_scan + idx_scan` таблицы `chats` и `keyspace_hits` / `keyspace_misses`, 50 чтений через LB, через 11 с второй снимок; TTL до и после ещё 10 чтений; число ключей рабочей и тестовой (`test_<db>`) базы. Код 0 — чтений `chats` ≤ 1, hits ≥ +49, промахов ≤ 1, ответы равны ответу на создание, TTL не продлевается, ≥ 2 `X-Instance-Id`. Для «Временной базы» перед ней — `make test_isolated`: без ключей тестовой базы строка `PASS` заканчивается «temporary database: not checked», с `--require-test-keys` — код 1 (доказательство сценария снимается с флагом). На стенде в это время ничего другого не должно идти. Вывод — `evidence/cache/hits.md` |
| `auth-storage` | только стенд с LB: сценарии `users` «Хэш в БД» и `sessions` «Токена нет в хранилище». Пароль P (с `:` и кириллицей) и токен T — только в памяти; через psql — префикс `$argon2id$…` до соли и длина у двух пользователей с одним P, неравенство хэшей, строка `sessions` с `token_hash` = SHA-256(T) (32 байта); `pg_dump --data-only` в память — нет ли T (текстом и в hex) и P. Код 0 — всё так. Вывод — `evidence/auth/passwords-and-tokens.md` |
| `s3-check` | стенд compose (`make s3_check`), без приложения: спек `object-storage` «Проверка приватности вне API». `docker compose run --rm --no-deps s3-bootstrap check` — права ключа API (PUT/GET/HEAD объекта, 404 отсутствующего; 403 на список, создание и удаление bucket, политику и ACL bucket, публичный ACL объекта), временный чужой bucket (403 на всё), аноним изнутри сервера (403); анонимные запросы с хоста (`127.0.0.1:S3_OUT_PORT`) и из сети стенда (одноразовый контейнер образа S3), порты контейнера S3: слушающие сокеты из `netstat -tuln` в контейнере — вне loopback ровно API S3 и gRPC шлюза, а остальные слушающие порты из сети закрыты (`nc -z`); затем `s3-bootstrap cleanup` и `weed shell` — проверочных объектов и bucket не осталось. Таблица «где → проверка → ожидаемо → получено» без секретов, код 1 при расхождении (печатает нарушенные). Вывод — `evidence/s3/privacy.md` |
| `upload --token T --chat C --file F [--type …] [--filename …]` | загрузка файла сырыми байтами (`urllib`): статус, `x-instance-id`, тело `Attachment`, размер и SHA-256 файла, совпал ли `sha256` ответа. `--type` по умолчанию — по сигнатуре (PNG, JPEG, иначе `application/octet-stream`), `--filename` — имя файла. Код 2 при статусе ≥ 400 |
| `download --token T --attachment A [--out F] [--variant …]` | скачивание оригинала: статус, `x-instance-id`, `Content-Type`, `Content-Length`, размер и SHA-256 полученного; `--out` сохраняет байты. Код 2 при статусе ≠ 200 (тело ошибки печатается) |
| `attachment-failover [--mode stop\|kill]` | только стенд с LB: спек `attachments` «Принявшая реплика остановлена». Синтетические Алиса, Боб, Ева и чат; загрузка `tests/fixtures/sample.png` через LB (реплика A — `X-Instance-Id` ответа), сообщение со ссылкой, `scripts/stop-one.sh` с `TARGET_INSTANCE_ID=A` и `STOP_MODE`, Боб скачивает через LB (до 30 попыток), пока не ответит другая реплика: SHA-256 совпадает, метаданные равны ответу загрузки; Ева — 404 на метаданные и байты. В `finally` — `make replicas`, затем ожидание, пока LB снова видит все реплики `UP`. Печатает `docker compose ps` до и после и таблицу «шаг → ожидаемо → получено → реплика» без токенов. Код 1 при расхождении, без LB (порт консольного процесса драйвера) — код 2. Вывод — `evidence/attachments/failover.md` |
| `attachment-storage` | только стенд с LB: спек `attachments` «Байты не в БД и не на диске API». Две загрузки fixture через LB; psql — колонки `attachments` и `message_attachments` (из `bytea` только 32-байтный `sha256`), `object_key` = `<база>/attachments/<id>/original` без `filename`; `weed shell fs.ls -l` — объект в bucket и его размер; анонимный GET ключа с `127.0.0.1:S3_OUT_PORT` — 403; скачивание участником — тот же SHA-256; `docker diff` каждой реплики — ни одного файла оригинала. Код 1 с названной проверкой, без LB — код 2. Вывод — `evidence/attachments/storage.md` |
| `stop-at-start [--image ТЕГ] [--delays 0.2,0.3,0.4,1.5,5] [--server-start 3]` | спек `graceful-shutdown` «Остановка во время старта»: контейнеры образа (по умолчанию `mtusi-messenger:lab4`) с лимитами реплики (1 CPU / 512 МиБ без swap), без сети и `config.toml`; `docker stop --timeout 10` через паузу после `docker run` и сразу по строке «Started server process». По потоку `docker events` и журналу: «сигнал через», время `docker stop`, «выход после сигнала», код выхода, этап (`import` / `server-start` / `running`), кто остановил (`early` / `uvicorn`). Код 0 — каждая попытка с кодом 0 и `docker stop` ≤ 1 с, есть `import`, остановленный ранним обработчиком, и `running`. Проекты compose не трогает, свои контейнеры удаляет по метке `mtusi.stop-at-start`. Вывод — `evidence/failover/stop-at-start.md` |
| `stop` | SIGTERM всей группе; ждёт, пока порт освободится. Чужой сервер и контейнер не трогает |
| `all` | всё подряд (`student` — если есть `student-tests/`), `stop` в `finally` |
@@ -150,6 +165,8 @@ python3 $D --port 8080 idle-conns # простаивающие сое
python3 $D --port 8080 hang-key # зависшая реплика держит ключ: повтор получает 201 после прерывания транзакции
make test_isolated && python3 $D --port 8080 cache-check --require-test-keys # кэш карточки: одно чтение chats на 50, TTL, ключи двух баз
python3 $D --port 8080 auth-storage # Argon2id в users, SHA-256 токена в sessions, ни токена, ни пароля в pg_dump
python3 $D --port 8080 attachment-failover --mode kill # реплика, принявшая файл, убита: скачивание через другую, тот же SHA-256
python3 $D --port 8080 attachment-storage # байты только в приватном bucket: схема, ключ, объект, аноним 403, docker diff
python3 $D stop-at-start # docker stop стартующей реплики: ~0,06 с и код 0 (раньше 10 с и 137)
make bench_failover_quick # отказ каждой реплики под нагрузкой на своём стенде mtusi-bench, ~2 мин
make rolling_update # новый код на реплики без простоя: сборка, миграции один раз, по одной: новая UP → старая drain → stop → rm
@@ -249,10 +266,10 @@ make lint # ruff; затрагивает и dr
Ожидаемо: `PASS: offline skeleton structure...`, `FAILED: none` у
`flow`, smoke — `PASS: lab4 public API scenario...`, student — все
прошли (тесты `fault` — `deselected`), `All checks passed!`; `all`,
`test_isolated` и `failure_checks` — код 0. **До change `attachments`**
smoke (загрузка вложения) и тесты со схемой `Message` (контракт лабы 4
требует `attachment_ids`) красные — список в `tasks.md` change
`s3-storage`.
`test_isolated` и `failure_checks` — код 0. Пока файлы `evidence/`, на
которые ссылаются исключения сверки покрытия, не сняты на стенде лабы
(AGENTS.md, «Переход в следующую лабу»), красный только
`test_exclusion_evidence_exists` — он называет сценарий и путь.
Проверки отказов (`student-tests/test_failures.py`, маркер `fault`)
останавливают и замораживают Postgres, Valkey и S3, поэтому идут только на
@@ -323,6 +340,17 @@ smoke (загрузка вложения) и тесты со схемой `Messa
без `Idempotency-Key` получит 400, а не 404. Порядок 401 → 400 → 404 →
409 — штатный для FastAPI (`api-contract.md`). Ключ в журнал сервера не
пишется: повтор виден по `"replayed": true` и `message_id`.
- **Ранний 413 на большой загрузке `urllib` напрямую к процессу
теряет.** API отвечает 413 (и 404, 415), не дочитывая тело; uvicorn
закрывает соединение, а `urllib` всё ещё пишет тело и получает
`BrokenPipe` / `ConnectionReset` вместо ответа. Через LB ответ
доходит (HAProxy дочитывает тело сам), httpx и `curl` получают его и
напрямую. Поэтому `driver.py upload` большие тела проверять через
`--port 8080`, а в консоли — `curl -H 'Content-Type: image/png'
--data-binary @big.png`.
- **Скачивание через LB может прийти не от той реплики, что загрузку**
— это и есть проверка «байты не на диске API»: оригинал отдаёт любая
реплика из S3. `X-Instance-Id` ответа загрузки — у `upload`.
- **`X-Instance-Id` в консоли — hostname машины**, в контейнере —
короткий ID контейнера (начало `docker compose ps -q api`, по нему
`scripts/stop-one.sh` находит реплику). Другое значение —
@@ -68,6 +68,24 @@
сигнала и выхода, код выхода, этап старта, кто остановил
(ранний обработчик или uvicorn); код 1, если стартующий
контейнер останавливается дольше 1 с или не с кодом 0
upload --token T --chat C --file F [--type …] [--filename …]
загрузка вложения: статус, X-Instance-Id, тело, SHA-256 файла
download --token T --attachment A [--out F] [--variant …]
скачивание оригинала: статус, X-Instance-Id, Content-Type,
размер и SHA-256 полученного
attachment-failover [--mode stop|kill] только стенд с LB: спек
attachments «Принявшая реплика остановлена» — загрузка
tests/fixtures/sample.png через LB, сообщение со ссылкой,
scripts/stop-one.sh реплики, принявшей файл, скачивание Бобом
через другую реплику (SHA-256 совпадает), 404 Еве; в finally
— make replicas; docker compose ps до и после, таблица без
токенов; код 1 при расхождении, без LB — код 2
attachment-storage только стенд с LB: спек attachments «Байты не в
БД и не на диске API» — колонки таблиц вложений (байты — только
32-байтный SHA-256), object_key вида <база>/attachments/<id>/
original без filename, объект в bucket (weed shell), анонимный
GET ключа с хоста — 403, docker diff реплик без файлов
оригиналов; код 1 при расхождении, без LB — код 2
stop остановить свой экземпляр на порту
all start → flow → smoke → student (если есть student-tests/) → stop
@@ -103,6 +121,7 @@ import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from collections import Counter
@@ -571,6 +590,65 @@ def cmd_flow(port: int) -> int:
listed = [item["id"] for item in chats["items"]]
flow.check("bob sees the chat", chat["id"] in listed)
# вложения (лаба 4): загрузка fixture, сообщение со ссылкой, оригинал
# Бобу побайтно, 404 Еве
data = FIXTURE_PNG.read_bytes()
status, hdrs, attachment = upload_bytes(
port,
alice,
chat["id"],
data,
content_type="image/png",
filename=FIXTURE_PNG.name,
)
uploaded = status == 201 and isinstance(attachment, dict)
flow.check(
f"POST {CHATS}/…/attachments -> 201 (upload fixture)",
uploaded and attachment.get("sha256") == sha256_hex(data),
f"{status} {hdrs.get('x-instance-id')}",
)
if uploaded:
attachment_path = f"{ATTACHMENTS}/{attachment['id']}"
with_file = flow.expect(
"message with attachment",
"POST",
msgs,
201,
token=alice,
body={"text": "", "attachment_ids": [attachment["id"]]},
extra=key_header(),
)
flow.check(
"attachment_ids in message",
isinstance(with_file, dict)
and with_file.get("attachment_ids") == [attachment["id"]],
)
status, hdrs, payload = call_bytes(
port,
"GET",
f"{attachment_path}/content",
token=bob,
)
flow.check(
f"GET {ATTACHMENTS}/…/content -> 200 (bob, same sha256)",
status == 200 and sha256_hex(payload) == sha256_hex(data),
f"{status} {hdrs.get('content-type')} {len(payload)} bytes",
)
flow.expect(
"outsider metadata",
"GET",
attachment_path,
404,
token=eve,
)
flow.expect(
"outsider content",
"GET",
f"{attachment_path}/content",
404,
token=eve,
)
flow.expect("logout", "DELETE", f"{SESSIONS}/current", 204, token=eve)
flow.expect(
"token after logout",
@@ -1868,6 +1946,493 @@ def cmd_s3_check() -> int:
return 0
# вложения (лаба 4): публичный fixture и пути API
FIXTURE_PNG = ROOT / "tests" / "fixtures" / "sample.png"
ATTACHMENTS = "/api/v1/attachments"
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
JPEG_SIGNATURE = b"\xff\xd8\xff"
# сколько раз скачивать через LB после остановки реплики: первые запросы
# может принять слот остановленной, пока LB её не исключил
FAILOVER_ATTEMPTS = 30
FAILOVER_PAUSE_S = 0.5
# сколько ждать, пока LB снова пометит вернувшуюся реплику UP
LB_UP_WAIT_S = 20
# ключ объекта: <база>/attachments/<id>/original (design change
# attachments, решение 4)
ATTACHMENT_KEY_PREFIX = "attachments"
ATTACHMENT_ORIGINAL = "original"
def call_bytes(
port: int,
method: str,
path: str,
*,
token: str | None = None,
data: bytes | None = None,
content_type: str | None = None,
timeout: float = 30,
) -> tuple[int, dict[str, str], bytes]:
"""Запрос с сырыми байтами в теле или ответе (загрузка, скачивание).
`urllib` напрямую к одной реплике ранний 413 на большом теле теряет
(обрыв при отправке): через LB ответ доходит (SKILL.md, Gotchas).
"""
headers = {}
if token is not None:
headers["Authorization"] = f"Bearer {token}"
if content_type is not None:
headers["Content-Type"] = content_type
request = urllib.request.Request(
base_url(port) + path,
data=data,
method=method,
headers=headers,
)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
status, hdrs = response.status, dict(response.headers)
payload = response.read()
except urllib.error.HTTPError as error:
status, hdrs, payload = error.code, dict(error.headers), error.read()
return status, {k.lower(): v for k, v in hdrs.items()}, payload
def image_type(data: bytes) -> str:
if data.startswith(PNG_SIGNATURE):
return "image/png"
if data.startswith(JPEG_SIGNATURE):
return "image/jpeg"
return "application/octet-stream"
def upload_bytes(
port: int,
token: str,
chat_id: str,
data: bytes,
*,
content_type: str,
filename: str,
) -> tuple[int, dict[str, str], object]:
query = urllib.parse.urlencode({"filename": filename})
status, hdrs, payload = call_bytes(
port,
"POST",
f"{CHATS}/{chat_id}/attachments?{query}",
token=token,
data=data,
content_type=content_type,
)
try:
parsed: object = json.loads(payload) if payload else None
except json.JSONDecodeError:
parsed = payload.decode(errors="replace")
return status, hdrs, parsed
def sha256_hex(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def cmd_upload(port: int, args: argparse.Namespace) -> int:
"""Загрузка файла: статус, `X-Instance-Id`, тело, SHA-256 файла."""
data = Path(args.file).read_bytes()
content_type = args.type or image_type(data)
status, hdrs, payload = upload_bytes(
port,
args.token,
args.chat,
data,
content_type=content_type,
filename=args.filename or Path(args.file).name,
)
print(status, "x-instance-id:", hdrs.get("x-instance-id"))
print(json.dumps(payload, ensure_ascii=False, indent=2))
print(f"file: {len(data)} bytes, sha256 {sha256_hex(data)}")
if status == 201 and isinstance(payload, dict):
print("sha256 matches:", payload.get("sha256") == sha256_hex(data))
return 0 if status < 400 else 2
def cmd_download(port: int, args: argparse.Namespace) -> int:
"""Скачивание оригинала: статус, тип, размер, SHA-256 полученного."""
path = f"{ATTACHMENTS}/{args.attachment}/content"
if args.variant is not None:
path += "?" + urllib.parse.urlencode({"variant": args.variant})
status, hdrs, payload = call_bytes(port, "GET", path, token=args.token)
print(
status,
"x-instance-id:",
hdrs.get("x-instance-id"),
"content-type:",
hdrs.get("content-type"),
"content-length:",
hdrs.get("content-length"),
)
if status != 200:
print(payload.decode(errors="replace"))
return 2
print(f"received: {len(payload)} bytes, sha256 {sha256_hex(payload)}")
if args.out:
Path(args.out).write_bytes(payload)
print(f"saved to {args.out}")
return 0
def attachment_people(
port: int,
tag: str,
) -> tuple[dict[str, str], dict[str, str], str] | None:
"""Синтетические Алиса, Боб, Ева и чат Алисы и Боба: (id, токены,
id чата). Пароли и токены не печатаются."""
ids: dict[str, str] = {}
tokens: dict[str, str] = {}
for name in ("alice", "bob", "eve"):
made = synthetic_user(port, f"{tag}{name}", f"Pw-{uuid.uuid4().hex}")
if made is None:
return None
ids[name], tokens[name] = str(made[0]["id"]), made[1]
status, _, chat = call(
port,
"POST",
CHATS,
token=tokens["alice"],
body={
"title": "attachments",
"member_ids": [ids["alice"], ids["bob"]],
},
)
if status != 201 or not isinstance(chat, dict):
print(f"create chat: {status}")
return None
return ids, tokens, str(chat["id"])
def compose_ps() -> str:
return compose(
"ps",
"--format",
"table {{.Name}}\t{{.Status}}",
).strip()
def cmd_attachment_failover(port: int, mode: str) -> int:
"""Спек `attachments`, «Принявшая реплика остановлена» (design change
`attachments`, решение 13): загрузка через LB, `scripts/stop-one.sh`
реплики, принявшей файл, скачивание через другую с тем же SHA-256,
404 постороннему; в `finally` — `make replicas`."""
if no_lb(port):
print("attachment-failover needs the stand with the load balancer")
return 2
data = FIXTURE_PNG.read_bytes()
print(f"mode: {mode}; fixture {FIXTURE_PNG.name}: {len(data)} bytes")
print("docker compose ps (before):")
print(compose_ps())
people = attachment_people(port, "af")
if people is None:
return 1
_, tokens, chat_id = people
rows: list[tuple[str, str, str, str]] = []
problems: list[str] = []
status, hdrs, attachment = upload_bytes(
port,
tokens["alice"],
chat_id,
data,
content_type="image/png",
filename=FIXTURE_PNG.name,
)
accepted_by = hdrs.get("x-instance-id", "")
rows.append(("alice uploads", "201", str(status), accepted_by))
if status != 201 or not isinstance(attachment, dict):
print(f"FAIL: upload {status}")
return 1
attachment_id = str(attachment["id"])
uploaded_sha = str(attachment["sha256"])
status, hdrs, message = call(
port,
"POST",
f"{CHATS}/{chat_id}/messages",
token=tokens["alice"],
body={"text": "", "attachment_ids": [attachment_id]},
extra=key_header(),
)
rows.append(
(
"alice sends message",
"201",
str(status),
hdrs.get("x-instance-id", ""),
),
)
try:
hook = subprocess.run(
[str(ROOT / "scripts" / "stop-one.sh")],
cwd=ROOT,
env=os.environ
| {"TARGET_INSTANCE_ID": accepted_by, "STOP_MODE": mode},
capture_output=True,
text=True,
check=False,
)
rows.append(
("stop-one.sh " + mode, "0", str(hook.returncode), accepted_by),
)
downloaded = b""
served_by = ""
meta_status = 0
for _ in range(FAILOVER_ATTEMPTS):
status, hdrs, payload = call_bytes(
port,
"GET",
f"{ATTACHMENTS}/{attachment_id}/content",
token=tokens["bob"],
)
if status == 200:
downloaded, served_by = payload, hdrs.get("x-instance-id", "")
break
time.sleep(FAILOVER_PAUSE_S)
rows.append(("bob downloads", "200", str(status), served_by))
meta_status, hdrs, meta = call(
port,
"GET",
f"{ATTACHMENTS}/{attachment_id}",
token=tokens["bob"],
)
rows.append(
(
"bob reads metadata",
"200",
str(meta_status),
hdrs.get("x-instance-id", ""),
),
)
for label, path in (
("eve reads metadata", f"{ATTACHMENTS}/{attachment_id}"),
("eve downloads", f"{ATTACHMENTS}/{attachment_id}/content"),
):
status, hdrs, _ = call_bytes(
port,
"GET",
path,
token=tokens["eve"],
)
rows.append(
(label, "404", str(status), hdrs.get("x-instance-id", "")),
)
if hook.returncode != 0:
problems.append(f"stop-one.sh: {hook.stderr.strip()}")
if served_by in ("", accepted_by):
problems.append("download was not served by another replica")
print(f"sha256 uploaded: {uploaded_sha}")
print(f"sha256 downloaded: {sha256_hex(downloaded)}")
if sha256_hex(downloaded) != uploaded_sha:
problems.append("sha256 of the downloaded original differs")
if isinstance(meta, dict) and meta != attachment:
problems.append("metadata differs from the upload response")
finally:
restore = subprocess.run(
["make", "replicas"],
cwd=ROOT,
capture_output=True,
text=True,
check=False,
)
rows.append(("make replicas", "0", str(restore.returncode), ""))
print("docker compose ps (after):")
print(compose_ps())
# make replicas ждёт healthy контейнера, а LB видит его по своим
# проверкам на секунды позже
replicas = len(compose("ps", "-q", "--status", "running", "api").split())
deadline = time.monotonic() + LB_UP_WAIT_S
up = 0
while time.monotonic() < deadline:
up = sum(1 for slot in lb_slots() if slot.get("status") == "UP")
if up >= replicas:
break
time.sleep(FAILOVER_PAUSE_S)
rows.append(("LB slots UP", str(replicas), str(up), ""))
width = max(len(step) for step, _, _, _ in rows)
print(f"{'step':<{width}} expected got x-instance-id")
failed = 0
for step, expected, got, instance in rows:
ok = expected == got
failed += not ok
print(
f"{step:<{width}} {expected:<8} {got:<4} {instance}"
+ ("" if ok else " FAIL"),
)
for problem in problems:
print(f"FAIL: {problem}")
if failed or problems:
return 1
print(
f"PASS: accepted by {accepted_by}, served by {served_by} after "
f"{mode}, sha256 matches, outsider gets 404",
)
return 0
def cmd_attachment_storage(port: int) -> int:
"""Спек `attachments`, «Байты не в БД и не на диске API» (design change
`attachments`, решение 13): колонки таблиц вложений, вид
`object_key`, объект в bucket, анонимный GET — 403, `docker diff`
реплик без файлов оригиналов."""
if no_lb(port):
print("attachment-storage needs the stand with the load balancer")
return 2
try:
stand = s3_stand()
config = json.loads(compose("config", "--format", "json"))
database = str(
config["services"]["api"]["environment"]["DATABASE__NAME"],
)
except (RuntimeError, KeyError, StopIteration, ValueError) as e:
print(f"FAIL: compose config of the stand: {e}")
return 1
people = attachment_people(port, "as")
if people is None:
return 1
_, tokens, chat_id = people
data = FIXTURE_PNG.read_bytes()
uploads = []
for number in range(2):
filename = f"storage-check-{uuid.uuid4().hex[:8]}-{number}.png"
status, hdrs, attachment = upload_bytes(
port,
tokens["alice"],
chat_id,
data,
content_type="image/png",
filename=filename,
)
if status != 201 or not isinstance(attachment, dict):
print(f"FAIL: upload {status}")
return 1
uploads.append((attachment, filename, hdrs.get("x-instance-id", "")))
rows: list[tuple[str, str, str]] = []
columns = stand_psql(
"SELECT table_name, column_name, data_type "
"FROM information_schema.columns WHERE table_schema = 'public' "
"AND table_name IN ('attachments', 'message_attachments') "
"ORDER BY table_name, ordinal_position;\n",
).splitlines()
print("columns of attachment tables:")
for line in columns:
print(" " + line.replace("|", " "))
binary = [
line.split("|")[1] for line in columns if line.endswith("|bytea")
]
rows.append(("bytea columns", "sha256", ",".join(binary) or "-"))
# id — UUID ответа API: безопасны в тексте SQL
ids = ", ".join(f"'{a['id']}'" for a, _, _ in uploads)
sha_length = stand_psql(
"SELECT coalesce(max(octet_length(sha256)), 0) FROM attachments "
f"WHERE id IN ({ids});\n",
).strip()
rows.append(("octet_length(sha256)", "32", sha_length))
keys = dict(
line.split("|")
for line in stand_psql(
f"SELECT id, object_key FROM attachments WHERE id IN ({ids});\n",
).splitlines()
)
for attachment, filename, instance in uploads:
attachment_id = str(attachment["id"])
key = keys.get(attachment_id, "")
expected = "/".join(
(
database,
ATTACHMENT_KEY_PREFIX,
attachment_id,
ATTACHMENT_ORIGINAL,
),
)
print(f"upload via {instance}: object_key {key}")
rows.append(("object_key form", expected, key))
rows.append(
("filename not in key", "no", "yes" if filename in key else "no"),
)
listing = weed_shell(
f"fs.ls -l /buckets/{stand['bucket']}/{database}/"
f"{ATTACHMENT_KEY_PREFIX}/{attachment_id}",
)
# «-rw-rw---- 1 seaweed seaweed <размер> <полный путь>»
sizes = [
parts[-2]
for parts in (line.split() for line in listing.splitlines())
if len(parts) > 2
and parts[-1] == f"/buckets/{stand['bucket']}/{key}"
]
rows.append(
(
"object in bucket, bytes",
str(attachment["size_bytes"]),
sizes[0] if sizes else "missing",
),
)
url = f"http://127.0.0.1:{stand['out_port']}/{stand['bucket']}/{key}"
rows.append(("anonymous GET of the key", "403", anonymous_code(url)))
status, _, payload = call_bytes(
port,
"GET",
f"{ATTACHMENTS}/{attachment_id}/content",
token=tokens["bob"],
)
print(
f" sha256 uploaded {attachment['sha256']}, downloaded by a "
f"member ({status}) {sha256_hex(payload)}",
)
rows.append(
(
"downloaded sha256 = uploaded",
"yes",
"yes" if sha256_hex(payload) == attachment["sha256"] else "no",
),
)
replicas = compose("ps", "-q", "api").split()
for container in replicas:
diff = subprocess.run(
["docker", "diff", container],
capture_output=True,
text=True,
check=False,
).stdout.splitlines()
suspicious = [
line
for line in diff
if any(
str(a["id"]) in line or name in line for a, name, _ in uploads
)
or line.lower().endswith((".png", ".jpg", ".jpeg", "/original"))
]
print(f"docker diff {container[:12]}: {len(diff)} changes")
for line in diff:
print(" " + line)
rows.append(
(f"original files in {container[:12]}", "0", str(len(suspicious))),
)
width = max(len(check) for check, _, _ in rows)
failed = 0
for check, expected, got in rows:
ok = expected == got
failed += not ok
print(
f"{check:<{width}} expected {expected} got {got}"
+ ("" if ok else " FAIL"),
)
print(f"sha256 of the fixture: {sha256_hex(data)}")
if failed:
print(f"FAIL: {failed} check(s) failed")
return 1
print(
"PASS: metadata in PostgreSQL, bytes only in the private bucket "
f"{stand['bucket']}, none in the API containers",
)
return 0
# stop-at-start: записи журнала, по которым видны этапы старта и остановки
STARTED_SERVER = "Started server process"
SERVER_RUNNING = "Uvicorn running on"
@@ -2233,6 +2798,23 @@ def main() -> int:
)
sub.add_parser("auth-storage")
sub.add_parser("s3-check")
upload = sub.add_parser("upload")
upload.add_argument("--token", required=True)
upload.add_argument("--chat", required=True)
upload.add_argument("--file", required=True)
upload.add_argument(
"--type",
help="Content-Type; по умолчанию — по сигнатуре",
)
upload.add_argument("--filename", help="по умолчанию — имя файла")
download = sub.add_parser("download")
download.add_argument("--token", required=True)
download.add_argument("--attachment", required=True)
download.add_argument("--out", help="сохранить полученные байты")
download.add_argument("--variant")
failover = sub.add_parser("attachment-failover")
failover.add_argument("--mode", choices=("stop", "kill"), default="stop")
sub.add_parser("attachment-storage")
stop = sub.add_parser("stop-at-start")
stop.add_argument("--image", default="mtusi-messenger:lab4")
stop.add_argument(
@@ -2305,6 +2887,14 @@ def main() -> int:
return cmd_auth_storage(port)
if args.cmd == "s3-check":
return cmd_s3_check()
if args.cmd == "upload":
return cmd_upload(port, args)
if args.cmd == "download":
return cmd_download(port, args)
if args.cmd == "attachment-failover":
return cmd_attachment_failover(port, args.mode)
if args.cmd == "attachment-storage":
return cmd_attachment_storage(port)
if args.cmd == "stop-at-start":
return cmd_stop_at_start(
args.image,