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
@@ -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,