Реализовать лабораторную 4 на оценку 5

Добавить приватное S3-хранилище, вложения, presigned upload, reconciler и доказательства.
This commit is contained in:
Чиняева
2026-11-07 01:37:21 +03:00
parent ec540a1a72
commit f39ae06ef3
69 changed files with 5254 additions and 31 deletions
+68
View File
@@ -0,0 +1,68 @@
# Студенческие проверки lab4
Все проверки, кроме `rollback_chat.py`, `explain_history.py` и `pool_settings.py`,
запускаются на хосте и обращаются к API через LB. Три проверки используют `psycopg`
и запускаются внутри одного контейнера API. Для новых проверок нужны `Pillow` и
`boto3` (см. `requirements-dev.txt`).
```sh
# 1. Одна сессия обслуживается минимум двумя реальными репликами
python student-tests/instance_spread.py --base-url http://localhost:8080
# 2. Конкурентный повтор одного Idempotency-Key через разные реплики
python student-tests/idempotency_race.py --base-url http://localhost:8080 --workers 20
# 3. Негативная аутентификация и logout (перенесено из lab2)
python student-tests/auth_negative.py --base-url http://localhost:8080
# 4. Гонка регистрации одного username (перенесено из lab2)
python student-tests/race_username.py --base-url http://localhost:8080 --workers 8
# 5. Откат составной операции (внутри контейнера; --index обязателен при replicas>1)
docker compose exec -T --index 1 api python student-tests/rollback_chat.py
# 6. EXPLAIN на 10 000 сообщений (внутри контейнера)
docker compose exec -T --index 1 api python student-tests/explain_history.py \
--output /tmp/explain_history.txt
# 7. Пул и SQL-таймауты (внутри контейнера)
docker compose exec -T --index 1 api python student-tests/pool_settings.py
# Lab4: негативные сценарии вложений
python student-tests/attachments_negative.py --base-url http://localhost:8080
# Lab4: 10 одновременных загрузок и пик RAM API
python student-tests/upload_memory.py --base-url http://localhost:8080 \
--output evidence/upload-memory.json
# Lab4/5: presigned direct upload и обязательный proxy fallback
python student-tests/presigned_flow.py --base-url http://localhost:8080
# Lab5 track 1: сравнение трафика/RAM API proxy vs direct на двух размерах
python student-tests/transfer_compare.py --base-url http://localhost:8080 \
--output evidence/transfer-compare.json
# Lab4: приватный bucket и отсутствие опубликованных admin UI
python student-tests/private_bucket.py --base-url http://localhost:8080
# Lab4/5: reconciler, grace period, очистка incomplete upload
python student-tests/reconcile_orphans.py --base-url http://localhost:8080
```
`instance_spread.py` проверяет не только заголовок, но и то, что запись, принятая
одной репликой, читается через другую. `idempotency_race.py` отправляет один ключ
параллельно, проверяет ровно один Message, 409 на другой body, 400 на отсутствующий
ключ и независимость scope по пользователю и чату.
`attachments_negative.py` проверяет лимит 10 MiB, пустое/повреждённое изображение,
подмену MIME, лимит 40 млн пикселей, опасные имена файлов, чужой attachment_id и
вложение из другого чата. `upload_memory.py` измеряет пик памяти контейнеров API
через `docker stats` при 10 параллельных загрузках. `presigned_flow.py` проверяет
короткую подпись, complete, checksum, owner-only, идемпотентность и отрицательные
сценарии. `reconcile_orphans.py` внедряет orphan-объект и незавершённую загрузку,
показывает dry-run, безопасный grace period и повторный `--apply`.
`fault_matrix.py` из lab2 не включён в основной набор: при отказе PostgreSQL/Redis
nginx исключает нездоровые API-реплики и сам возвращает 502/503 без JSON-тела,
что является корректным поведением LB, но не проверкой формата ошибки API.
Проверка отказов зависимостей для lab4 описана в `REPORT.md`.
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env python3
"""Lab4 negative attachment checks: size, corruption, MIME, ownership, chat scope."""
from __future__ import annotations
import argparse
import io
import struct
import uuid
import zlib
from urllib.parse import quote
from PIL import Image
from common import HttpClient, assert_status, error_code
MAX_UPLOAD = 10_485_760
def _png_chunk(kind: bytes, data: bytes) -> bytes:
return (
len(data).to_bytes(4, "big")
+ kind
+ data
+ struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
)
def png_bytes(width: int = 320, height: int = 200) -> bytes:
buffer = io.BytesIO()
Image.new("RGB", (width, height), (30, 120, 200)).save(buffer, format="PNG")
return buffer.getvalue()
def jpeg_bytes(width: int = 320, height: int = 200) -> bytes:
buffer = io.BytesIO()
Image.new("RGB", (width, height), (200, 80, 30)).save(buffer, format="JPEG")
return buffer.getvalue()
def png_header(width: int, height: int) -> bytes:
"""Valid signature/IHDR/IEND; enough for the pixel budget check, no decode."""
return (
b"\x89PNG\r\n\x1a\n"
+ _png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ _png_chunk(b"IEND", b"")
)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
args = parser.parse_args()
client = HttpClient(args.base_url)
alice, alice_reg = client.register()
bob, bob_reg = client.register()
eve, _eve_reg = client.register()
alice_token = client.login(alice_reg)["token"]
bob_token = client.login(bob_reg)["token"]
eve_token = client.login(_eve_reg)["token"]
status, _h, chat, _r = client.call(
"POST",
"/api/v1/chats",
body={"title": "Attachment negatives", "member_ids": [alice["id"], bob["id"]]},
token=alice_token,
)
assert_status(status, 201, "create chat")
status, _h, other_chat, _r = client.call(
"POST",
"/api/v1/chats",
body={"title": "Another chat", "member_ids": [alice["id"], bob["id"]]},
token=alice_token,
)
assert_status(status, 201, "create other chat")
def upload(content: bytes, content_type: str, filename: str, token=alice_token, chat_id=None):
path = (
"/api/v1/chats/"
+ (chat_id or chat["id"])
+ "/attachments?filename="
+ quote(filename, safe="")
)
return client.raw(
"POST",
path,
data=content,
headers={"Authorization": "Bearer " + token, "Content-Type": content_type},
)
def expect(result, expected: int, label: str) -> dict:
status, headers, payload, _raw = result
assert_status(status, expected, label)
if status >= 400:
if not isinstance(payload, dict) or payload.get("error", {}).get("code") in (None, "internal_error"):
raise AssertionError(f"{label}: expected a typed user error, got {payload!r}")
if payload["error"]["request_id"] != headers.get("X-Request-Id"):
raise AssertionError(f"{label}: request_id mismatch")
return payload
png = png_bytes()
jpeg = jpeg_bytes()
attachment = expect(upload(png, "image/png", "ok.png"), 201, "valid PNG")
if attachment["status"] != "ready":
raise AssertionError("valid PNG did not become ready")
expect(
upload(b"\x89PNG\r\n\x1a\n" + b"x" * (MAX_UPLOAD + 1), "image/png", "big.png"),
413,
"oversized body",
)
expect(upload(b"", "image/png", "empty.png"), 415, "empty body")
expect(upload(b"\x89PNG\r\n\x1a\nnot-an-image", "image/png", "broken.png"), 415, "corrupted PNG")
expect(upload(jpeg, "image/png", "spoof.png"), 415, "JPEG bytes declared as PNG")
expect(upload(png, "image/jpeg", "spoof.jpg"), 415, "PNG bytes declared as JPEG")
expect(upload(png, "text/plain", "plain.txt"), 415, "unsupported content type")
expect(upload(png_header(10_000, 5_000), "image/png", "huge.png"), 413, "pixel budget")
expect(upload(png, "image/png", "../escape.png"), 400, "path traversal filename")
expect(upload(png, "image/png", "a/b.png"), 400, "slash filename")
expect(upload(png, "image/png", "a\\b.png"), 400, "backslash filename")
# A member of the chat still gets 404 for an unknown attachment id.
missing_id = str(uuid.uuid4())
status, _h, payload, _r = client.call(
"GET", "/api/v1/attachments/" + missing_id, token=bob_token
)
assert_status(status, 404, "unknown attachment metadata")
if error_code(payload) == "internal_error":
raise AssertionError("unknown attachment leaked a 500")
# A non-member cannot read metadata or bytes.
for suffix in ("", "/content"):
status, _h, payload, _r = client.call(
"GET", "/api/v1/attachments/" + attachment["id"] + suffix, token=eve_token
)
assert_status(status, 404, "outsider attachment read")
if error_code(payload) == "internal_error":
raise AssertionError("outsider read leaked a 500")
# Uploading into another chat and linking it here must be a 404, not a 500.
foreign = expect(upload(png, "image/png", "foreign.png", chat_id=other_chat["id"]), 201, "other-chat upload")
status, _h, payload, _r = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
body={"text": "", "attachment_ids": [foreign["id"]]},
token=alice_token,
headers={"Idempotency-Key": uuid.uuid4().hex},
)
assert_status(status, 404, "attachment from another chat")
if error_code(payload) == "internal_error":
raise AssertionError("cross-chat attachment leaked a 500")
# Duplicate and too-many ids are request errors, not 500.
status, _h, _p, _r = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
body={"text": "", "attachment_ids": [attachment["id"], attachment["id"]]},
token=alice_token,
headers={"Idempotency-Key": uuid.uuid4().hex},
)
assert_status(status, 400, "duplicate attachment ids")
status, _h, _p, _r = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
body={"text": "", "attachment_ids": [attachment["id"]] * 11},
token=alice_token,
headers={"Idempotency-Key": uuid.uuid4().hex},
)
assert_status(status, 400, "too many attachment ids")
print("PASS: lab4 attachment negatives (size, corruption, MIME, filename, ownership, chat scope)")
if __name__ == "__main__":
main()
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Wrong password, Basic-on-business-endpoint, logout and reuse checks."""
from __future__ import annotations
import argparse
import base64
from common import HttpClient, assert_status, error_code
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
args = parser.parse_args()
client = HttpClient(args.base_url)
user, registration = client.register()
wrong = base64.b64encode(
(registration["username"] + ":wrong-password-value").encode("utf-8")
).decode("ascii")
status, headers, payload, _ = client.call(
"POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + wrong}
)
assert_status(status, 401, "wrong password")
assert error_code(payload) == "unauthorized"
assert headers.get("WWW-Authenticate", "").lower().startswith("basic")
good = base64.b64encode(
(registration["username"] + ":" + registration["password"]).encode("utf-8")
).decode("ascii")
status, headers, _, _ = client.call(
"GET", "/api/v1/users/me", headers={"Authorization": "Basic " + good}
)
assert_status(status, 401, "Basic on business endpoint")
assert headers.get("WWW-Authenticate", "").lower().startswith("bearer")
session = client.login(registration)
token = session["token"]
status, _, me, _ = client.call("GET", "/api/v1/users/me", token=token)
assert_status(status, 200, "login")
assert me["id"] == user["id"]
status, _, _, raw = client.call("DELETE", "/api/v1/auth/sessions/current", token=token)
assert_status(status, 204, "logout")
assert raw == b"", "204 must have an empty body"
status, headers, payload, _ = client.call("GET", "/api/v1/users/me", token=token)
assert_status(status, 401, "token after logout")
assert error_code(payload) == "unauthorized"
assert headers.get("WWW-Authenticate", "").lower().startswith("bearer")
status, _, _, _ = client.call("DELETE", "/api/v1/auth/sessions/current", token=token)
assert_status(status, 401, "second logout")
print("PASS: wrong password, Basic rejection, logout and token reuse checks")
if __name__ == "__main__":
main()
+96
View File
@@ -0,0 +1,96 @@
#!/usr/bin/env python3
"""Small standard-library HTTP helpers for the student checks."""
from __future__ import annotations
import base64
import json
import os
import uuid
import urllib.error
import urllib.request
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
class HttpClient:
def __init__(self, base_url: str | None = None):
self.base = (base_url or BASE_URL).rstrip("/")
def call(self, method: str, path: str, body=None, token: str | None = None, headers=None):
h = {"Accept": "application/json"}
data = None
if body is not None:
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
h["Content-Type"] = "application/json"
if token:
h["Authorization"] = "Bearer " + token
h.update(headers or {})
request = urllib.request.Request(self.base + path, data=data, headers=h, method=method)
try:
response = urllib.request.urlopen(request, timeout=10)
except urllib.error.HTTPError as error:
response = error
with response:
raw = response.read()
payload = None
if raw:
try:
payload = json.loads(raw)
except ValueError:
payload = None
return response.code, response.headers, payload, raw
def raw(self, method: str, path: str, data: bytes | None = None, headers=None, timeout=60):
"""Send raw bytes (uploads, presigned PUT) and return status/headers/json/raw."""
h = {"Accept": "application/json"}
h.update(headers or {})
url = path if path.startswith(("http://", "https://")) else self.base + path
request = urllib.request.Request(url, data=data, headers=h, method=method)
try:
response = urllib.request.urlopen(request, timeout=timeout)
except urllib.error.HTTPError as error:
response = error
with response:
raw = response.read()
payload = None
if raw:
try:
payload = json.loads(raw)
except ValueError:
payload = None
return response.code, response.headers, payload, raw
def register(self) -> tuple[dict, dict]:
suffix = uuid.uuid4().hex[:12]
registration = {
"username": "st_" + suffix,
"display_name": "Студент " + suffix,
"password": "T3st-" + uuid.uuid4().hex,
}
status, _headers, user, _raw = self.call("POST", "/api/v1/users", registration)
if status != 201:
raise AssertionError(f"registration failed: HTTP {status}")
return user, registration
def login(self, registration: dict) -> dict:
credential = base64.b64encode(
(registration["username"] + ":" + registration["password"]).encode("utf-8")
).decode("ascii")
status, _headers, session, _raw = self.call(
"POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + credential}
)
if status != 201:
raise AssertionError(f"login failed: HTTP {status}")
return session
def assert_status(actual: int, expected: int, label: str) -> None:
if actual != expected:
raise AssertionError(f"{label}: expected HTTP {expected}, received {actual}")
def error_code(payload) -> str | None:
if not isinstance(payload, dict):
return None
error = payload.get("error")
return error.get("code") if isinstance(error, dict) else None
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python3
"""Expiry check: run against an API with SESSION_TTL_SECONDS=2 (or pass --wait)."""
from __future__ import annotations
import argparse
import time
from common import HttpClient, assert_status, error_code
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--wait", type=float, default=3.0)
args = parser.parse_args()
client = HttpClient(args.base_url)
user, registration = client.register()
session = client.login(registration)
token = session["token"]
status, headers, payload, _ = client.call("GET", "/api/v1/users/me", token=token)
assert_status(status, 200, "fresh session")
assert payload["id"] == user["id"], "wrong current user"
time.sleep(args.wait)
status, headers, payload, _ = client.call("GET", "/api/v1/users/me", token=token)
assert_status(status, 401, "expired session")
assert error_code(payload) == "unauthorized", "expired session must be unauthorized"
assert headers.get("WWW-Authenticate", "").lower().startswith("bearer"), "missing Bearer challenge"
print("PASS: expired session is rejected with 401 and Bearer challenge")
if __name__ == "__main__":
main()
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Create 10 000 synthetic messages and record EXPLAIN (ANALYZE, BUFFERS).
Run inside the API container (psycopg is installed there):
docker compose exec -T api python student-tests/explain_history.py \
--output /app/evidence/explain_history.txt
The evidence directory is mounted read-only in the container, so the example
below is normally executed with a writable bind mount or copied out.
"""
from __future__ import annotations
import argparse
import os
import uuid
from datetime import datetime, timezone
from pathlib import Path
import psycopg
MESSAGES = 10_000
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--database-url", default=os.environ.get("DATABASE_URL"))
parser.add_argument("--output", default="evidence/explain_history.txt")
parser.add_argument("--messages", type=int, default=MESSAGES)
args = parser.parse_args()
if not args.database_url:
raise SystemExit("DATABASE_URL is required")
tag = uuid.uuid4().hex[:10]
user_id = uuid.uuid4()
chat_id = uuid.uuid4()
with psycopg.connect(args.database_url) as conn:
conn.execute(
"INSERT INTO users (id, username, display_name, password_hash) VALUES (%s, %s, %s, %s)",
(user_id, "perf_" + tag, "Performance synthetic", "not-a-real-password-hash"),
)
conn.execute("INSERT INTO chats (id, title) VALUES (%s, %s)", (chat_id, "perf-" + tag))
conn.execute(
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)", (chat_id, user_id)
)
conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), %s, %s, 'synthetic message ' || g,
timestamptz '2026-01-01 00:00:00+00' + (g || ' milliseconds')::interval
FROM generate_series(1, %s) AS g
""",
(chat_id, user_id, args.messages),
)
total = conn.execute(
"SELECT count(*) FROM messages WHERE chat_id = %s", (chat_id,)
).fetchone()[0]
conn.execute("ANALYZE messages")
cursor = conn.execute(
"""
SELECT created_at, id FROM messages
WHERE chat_id = %s ORDER BY created_at, id
OFFSET %s LIMIT 1
""",
(chat_id, max(0, args.messages - 500)),
).fetchone()
plan_rows = conn.execute(
"""
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = %s AND (created_at, id) > (%s, %s)
ORDER BY created_at, id
LIMIT 51
""",
(chat_id, cursor[0], cursor[1]),
).fetchall()
conn.commit()
plan = "\n".join(row[0] for row in plan_rows)
if "messages_chat_created_at_id_idx" not in plan:
raise AssertionError("history query did not use the keyset index:\n" + plan)
if "Seq Scan" in plan:
raise AssertionError("history query performed a sequential scan:\n" + plan)
header = (
"# EXPLAIN (ANALYZE, BUFFERS) for keyset history pagination\n"
f"generated_at_utc: {datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')}\n"
f"messages_in_chat: {total}\n"
f"chat_id: {chat_id}\n"
"query: WHERE chat_id = ? AND (created_at, id) > (?, ?) "
"ORDER BY created_at, id LIMIT 51\n\n"
)
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(header + plan + "\n", encoding="utf-8")
print(header + plan)
print(f"PASS: index used on {total} messages; evidence written to {output}")
if __name__ == "__main__":
main()
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env python3
"""Dependency-failure matrix: Redis and PostgreSQL outages must be bounded.
The check uses the local Compose project. It stops one dependency, verifies
503 (never 200 and never a trusted anonymous request), starts it again, waits
for readiness and confirms the original bearer session still works after the
Redis restart (AOF persistence).
"""
from __future__ import annotations
import argparse
import os
import subprocess
import time
from pathlib import Path
from common import HttpClient, assert_status, error_code
ROOT = Path(__file__).resolve().parents[1]
def compose(*args: str) -> None:
subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT,
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def wait_ready(client: HttpClient, expected: int, seconds: float = 90) -> None:
deadline = time.monotonic() + seconds
last = None
while time.monotonic() < deadline:
try:
status, _, _, _ = client.call("GET", "/health/ready")
last = status
if status == expected:
return
except OSError:
last = "connection error"
time.sleep(0.5)
raise AssertionError(f"readiness did not become {expected}; last={last}")
def expect_503(client: HttpClient, path: str, token: str | None, label: str) -> None:
status, _headers, payload, _raw = client.call("GET", path, token=token)
if status != 503:
raise AssertionError(f"{label}: expected 503, received {status}")
if error_code(payload) != "unavailable":
raise AssertionError(f"{label}: expected unavailable error code")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
args = parser.parse_args()
client = HttpClient(args.base_url)
user, registration = client.register()
session = client.login(registration)
token = session["token"]
results = []
try:
compose("stop", "redis")
expect_503(client, "/health/ready", None, "Redis down readiness")
expect_503(client, "/api/v1/users/me", token, "Redis down authenticated request")
results.append("redis down: readiness=503, bearer request=503")
started = time.monotonic()
compose("start", "redis")
wait_ready(client, 200)
redis_recovery = round(time.monotonic() - started, 2)
status, _, me, _ = client.call("GET", "/api/v1/users/me", token=token)
assert_status(status, 200, "session after Redis restart")
if me["id"] != user["id"]:
raise AssertionError("session identity changed after Redis restart")
results.append(f"redis up: readiness=200 in {redis_recovery}s, same token=200 (AOF persistence)")
compose("stop", "postgres")
time.sleep(1)
expect_503(client, "/health/ready", None, "PostgreSQL down readiness")
expect_503(client, "/api/v1/users/me", token, "PostgreSQL down authenticated request")
results.append("postgres down: readiness=503, bearer request=503")
started = time.monotonic()
compose("start", "postgres")
wait_ready(client, 200)
postgres_recovery = round(time.monotonic() - started, 2)
status, _, me, _ = client.call("GET", "/api/v1/users/me", token=token)
assert_status(status, 200, "session after PostgreSQL restart")
results.append(f"postgres up: readiness=200 in {postgres_recovery}s, same token=200")
finally:
compose("start", "redis")
compose("start", "postgres")
for line in results:
print("OBSERVED:", line)
print("PASS: dependency loss produced only bounded 503 responses; no anonymous trust")
if __name__ == "__main__":
main()
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env python3
"""Concurrent shared-key replay across replicas plus scope/conflict checks."""
from __future__ import annotations
import argparse
import uuid
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from common import HttpClient
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--workers", type=int, default=20)
args = parser.parse_args()
client = HttpClient(args.base_url)
alice, alice_registration = client.register()
bob, bob_registration = client.register()
alice_token = client.login(alice_registration)["token"]
bob_token = client.login(bob_registration)["token"]
status, _headers, chat, _ = client.call(
"POST",
"/api/v1/chats",
body={"title": "Idempotency race", "member_ids": [alice["id"], bob["id"]]},
token=alice_token,
)
if status != 201:
raise AssertionError(f"chat creation failed: HTTP {status}")
key = uuid.uuid4().hex
text = "concurrent replay " + key
path = "/api/v1/chats/" + chat["id"] + "/messages"
def send_same_body(_index: int):
return client.call(
"POST", path, body={"text": text}, token=alice_token,
headers={"Idempotency-Key": key},
)
with ThreadPoolExecutor(max_workers=args.workers) as pool:
results = list(pool.map(send_same_body, range(args.workers)))
statuses = Counter(status for status, _h, _p, _r in results)
statuses.pop(200, None)
if set(statuses) != {201}:
raise AssertionError(f"concurrent replay statuses are not all 201: {dict(statuses)}")
ids = {payload["id"] for _s, _h, payload, _r in results}
if len(ids) != 1:
raise AssertionError(f"concurrent replay created {len(ids)} messages instead of 1")
instances = {
headers.get("X-Instance-Id", "")
for _s, headers, _p, _r in results
if headers.get("X-Instance-Id")
}
if len(instances) < 2:
raise AssertionError("concurrent replay did not reach at least two replicas")
message_id = next(iter(ids))
status, _headers, page, _ = client.call(
"GET", path + "?limit=100", token=bob_token
)
if status != 200:
raise AssertionError(f"history read failed: HTTP {status}")
matching = [m for m in page["items"] if m["id"] == message_id]
if len(matching) != 1:
raise AssertionError("history contains a duplicate or a missing replayed message")
# Same key, different canonical body -> 409.
status, _headers, payload, _ = client.call(
"POST", path, body={"text": text + " different"}, token=alice_token,
headers={"Idempotency-Key": key},
)
if status != 409 or payload.get("error", {}).get("code") != "conflict":
raise AssertionError(f"different body with the same key returned HTTP {status}, expected 409")
# Missing / malformed key -> 400.
for headers in ({}, {"Idempotency-Key": "bad key with spaces"}):
status, _headers, payload, _ = client.call(
"POST", path, body={"text": "no valid key"}, token=alice_token, headers=headers
)
if status != 400 or payload.get("error", {}).get("code") != "invalid_request":
raise AssertionError(f"invalid Idempotency-Key returned HTTP {status}, expected 400")
# Scope includes the user: the same key by another user is independent.
status, _headers, bob_message, _ = client.call(
"POST", path, body={"text": "bob independent"}, token=bob_token,
headers={"Idempotency-Key": key},
)
if status != 201 or bob_message["sender_id"] != bob["id"]:
raise AssertionError(f"another user's identical key was not independent: HTTP {status}")
# Scope includes the path: the same key in another chat is independent.
status, _headers, other_chat, _ = client.call(
"POST",
"/api/v1/chats",
body={"title": "Second chat", "member_ids": [alice["id"], bob["id"]]},
token=alice_token,
)
if status != 201:
raise AssertionError(f"second chat creation failed: HTTP {status}")
status, _headers, other_message, _ = client.call(
"POST",
"/api/v1/chats/" + other_chat["id"] + "/messages",
body={"text": "same key another chat"},
token=alice_token,
headers={"Idempotency-Key": key},
)
if status != 201 or other_message["id"] == message_id:
raise AssertionError(f"same key in another chat was not independent: HTTP {status}")
print("concurrent_workers:", args.workers)
print("statuses:", dict(statuses))
print("instances:", ", ".join(sorted(instances)))
print("PASS: shared idempotency creates exactly one message and respects all scopes")
if __name__ == "__main__":
main()
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""Prove that one session is served by at least two real API replicas via the LB."""
from __future__ import annotations
import argparse
from collections import Counter
from common import HttpClient
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--requests", type=int, default=60)
args = parser.parse_args()
client = HttpClient(args.base_url)
alice, alice_registration = client.register()
bob, _bob_registration = client.register()
alice_session = client.login(alice_registration)
token = alice_session["token"]
status, _headers, chat, _ = client.call(
"POST",
"/api/v1/chats",
body={"title": "Replica spread", "member_ids": [alice["id"], bob["id"]]},
token=token,
)
if status != 201:
raise AssertionError(f"chat creation failed: HTTP {status}")
instances: Counter[str] = Counter()
for _ in range(args.requests):
status, headers, me, _ = client.call("GET", "/api/v1/users/me", token=token)
if status != 200 or me["id"] != alice["id"]:
raise AssertionError("existing session did not work through the LB")
instance = headers.get("X-Instance-Id", "")
if not instance:
raise AssertionError("missing X-Instance-Id on an API response")
if not headers.get("X-Request-Id"):
raise AssertionError("missing X-Request-Id on an API response")
instances[instance] += 1
if len(instances) < 2:
raise AssertionError(
"fewer than two API instances observed; check LB discovery / replica count"
)
# A write accepted by one replica must be visible from any other replica.
for index, instance in enumerate(instances):
status, headers, message, _ = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
body={"text": f"replica-write-{index}"},
token=token,
headers={"Idempotency-Key": f"spread-{index}-{alice['id']}"},
)
if status != 201:
raise AssertionError(f"message write failed through {instance}: HTTP {status}")
status, _headers, page, _ = client.call(
"GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100", token=token
)
if status != 200 or not any(m["id"] == message["id"] for m in page["items"]):
raise AssertionError("message written by one replica is not readable")
print("instances:", ", ".join(f"{name}={count}" for name, count in sorted(instances.items())))
print("PASS: one session served by >=2 API replicas with a shared datastore")
if __name__ == "__main__":
main()
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Print the effective PostgreSQL timeouts and pool limits.
Run inside the API container:
docker compose exec -T api python student-tests/pool_settings.py
"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app import db
def main() -> None:
db.pool().open(wait=True, timeout=5)
db.apply_migrations()
with db.pool().connection() as conn:
statement = conn.execute("SHOW statement_timeout").fetchone()["statement_timeout"]
idle = conn.execute("SHOW idle_in_transaction_session_timeout").fetchone()[
"idle_in_transaction_session_timeout"
]
lock = conn.execute("SHOW lock_timeout").fetchone()["lock_timeout"]
stats = db.pool().get_stats()
print("statement_timeout =", statement)
print("idle_in_transaction_session_timeout =", idle)
print("lock_timeout =", lock)
print("pool_min =", stats["pool_min"])
print("pool_max =", stats["pool_max"])
print("pool_size =", stats["pool_size"])
print("pool_available =", stats["pool_available"])
print("PASS: bounded pool and SQL timeouts are active")
if __name__ == "__main__":
main()
+203
View File
@@ -0,0 +1,203 @@
#!/usr/bin/env python3
"""Lab5 track 1: presigned direct upload plus the mandatory proxy fallback."""
from __future__ import annotations
import argparse
import hashlib
import io
import uuid
from PIL import Image
from common import HttpClient, assert_status, error_code
def png_bytes(width: int = 640, height: int = 400) -> bytes:
buffer = io.BytesIO()
Image.new("RGB", (width, height), (20, 160, 90)).save(buffer, format="PNG")
return buffer.getvalue()
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
args = parser.parse_args()
client = HttpClient(args.base_url)
alice, alice_reg = client.register()
bob, bob_reg = client.register()
alice_token = client.login(alice_reg)["token"]
bob_token = client.login(bob_reg)["token"]
status, _h, chat, _r = client.call(
"POST",
"/api/v1/chats",
body={"title": "Presigned upload", "member_ids": [alice["id"], bob["id"]]},
token=alice_token,
)
assert_status(status, 201, "create chat")
content = png_bytes()
digest = hashlib.sha256(content).hexdigest()
body = {
"filename": "direct.png",
"content_type": "image/png",
"size_bytes": len(content),
"sha256": digest,
}
status, _h, presign, _r = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/attachments/presign",
body=body,
token=alice_token,
)
assert_status(status, 201, "presign")
if presign["method"] != "PUT" or not presign["upload_url"].startswith("http"):
raise AssertionError("presign response is missing a usable PUT URL")
# The mandatory proxy endpoint still works.
status, _h, proxy, _r = client.raw(
"POST",
"/api/v1/chats/" + chat["id"] + "/attachments?filename=proxy.png",
data=content,
headers={"Authorization": "Bearer " + alice_token, "Content-Type": "image/png"},
)
assert_status(status, 201, "proxy upload remains available")
# Direct PUT to the private bucket through the short-lived signature.
status, _h, _p, _r = client.raw(
"PUT",
presign["upload_url"],
data=content,
headers=presign["headers"],
)
assert_status(status, 200, "presigned PUT")
status, _h, ready, _r = client.call(
"POST",
"/api/v1/attachments/" + presign["attachment_id"] + "/complete",
body={"sha256": digest, "size_bytes": len(content)},
token=alice_token,
)
assert_status(status, 200, "complete")
if ready["status"] != "ready" or ready["sha256"] != digest:
raise AssertionError("completed attachment is not ready with the expected checksum")
# A chat member can read the bytes through the API; no redirect is used.
status, headers, _p, raw = client.raw(
"GET",
"/api/v1/attachments/" + presign["attachment_id"] + "/content",
headers={"Authorization": "Bearer " + bob_token},
)
assert_status(status, 200, "download direct upload")
if raw != content or headers.get_content_type() != "image/png":
raise AssertionError("direct-upload download differs from the original")
# Complete is idempotent for the same parameters.
status, _h, again, _r = client.call(
"POST",
"/api/v1/attachments/" + presign["attachment_id"] + "/complete",
body={"sha256": digest, "size_bytes": len(content)},
token=alice_token,
)
assert_status(status, 200, "idempotent complete")
if again["id"] != ready["id"]:
raise AssertionError("idempotent complete returned another attachment")
# Negative: a ready attachment cannot be completed with different values.
for payload, label in (
({"sha256": "0" * 64, "size_bytes": len(content)}, "ready checksum mismatch"),
({"sha256": digest, "size_bytes": len(content) + 1}, "ready size mismatch"),
):
status, _h, error, _r = client.call(
"POST",
"/api/v1/attachments/" + presign["attachment_id"] + "/complete",
body=payload,
token=alice_token,
)
assert_status(status, 409, label)
if error_code(error) == "internal_error":
raise AssertionError(label + " leaked a 500")
# Negative: wrong bytes that are never promoted (checksum/size mismatch).
for wrong, label in (
(png_bytes(641, 400), "checksum mismatch"),
(content + b"x", "size mismatch"),
):
status, _h, bad_upload, _r = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/attachments/presign",
body=body,
token=alice_token,
)
assert_status(status, 201, label + " presign")
status, _h, _p, _r = client.raw(
"PUT",
bad_upload["upload_url"],
data=wrong,
headers=bad_upload["headers"],
)
assert_status(status, 200, label + " PUT")
status, _h, error, _r = client.call(
"POST",
"/api/v1/attachments/" + bad_upload["attachment_id"] + "/complete",
body={"sha256": digest, "size_bytes": len(content)},
token=alice_token,
)
assert_status(status, 400, label)
if error_code(error) == "internal_error":
raise AssertionError(label + " leaked a 500")
# Negative: another user cannot complete Alice's pending upload.
status, _h, pending, _r = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/attachments/presign",
body=body,
token=alice_token,
)
assert_status(status, 201, "second presign")
status, _h, error, _r = client.call(
"POST",
"/api/v1/attachments/" + pending["attachment_id"] + "/complete",
body={"sha256": digest, "size_bytes": len(content)},
token=bob_token,
)
assert_status(status, 404, "foreign complete")
if error_code(error) == "internal_error":
raise AssertionError("foreign complete leaked a 500")
# Negative: completing before PUT is a typed 409.
status, _h, error, _r = client.call(
"POST",
"/api/v1/attachments/" + pending["attachment_id"] + "/complete",
body={"sha256": digest, "size_bytes": len(content)},
token=alice_token,
)
assert_status(status, 409, "incomplete direct upload")
if error_code(error) == "internal_error":
raise AssertionError("incomplete upload leaked a 500")
# Negative: bad presign input.
for bad, expected in (
({**body, "content_type": "image/gif"}, 415),
({**body, "size_bytes": 10_485_761}, 400),
({**body, "sha256": "ABC"}, 400),
({**body, "filename": "../x.png"}, 400),
):
status, _h, error, _r = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/attachments/presign",
body=bad,
token=alice_token,
)
assert_status(status, expected, "bad presign input")
if error_code(error) == "internal_error":
raise AssertionError("bad presign input leaked a 500")
print(
"PASS: presigned upload, complete, checksum verification, proxy fallback, "
"idempotency and negative cases"
)
if __name__ == "__main__":
main()
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""Lab4 infrastructure checks: private bucket and no published admin UIs."""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import urllib.error
import urllib.request
import uuid
from pathlib import Path
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
ROOT = Path(__file__).resolve().parents[1]
def read_env() -> dict[str, str]:
values = dict(os.environ)
path = ROOT / ".env"
if path.is_file():
for line in path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
values.setdefault(key.strip(), value.strip())
return values
def s3_client(env: dict[str, str]):
return boto3.client(
"s3",
endpoint_url=env["S3_PUBLIC_ENDPOINT"],
region_name=env.get("S3_REGION", "us-east-1"),
aws_access_key_id=env["S3_ACCESS_KEY_ID"],
aws_secret_access_key=env["S3_SECRET_ACCESS_KEY"],
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
)
def check_public_ports() -> None:
result = subprocess.run(
["docker", "compose", "--env-file", ".env", "ps", "--format", "json"],
cwd=ROOT,
capture_output=True,
text=True,
timeout=30,
)
if result.returncode != 0:
raise AssertionError("could not inspect compose publishers")
services = [json.loads(line) for line in result.stdout.splitlines() if line.strip()]
for service in services:
name = service.get("Service") or service.get("Name", "")
publishers = service.get("Publishers") or []
published = [p for p in publishers if p.get("PublishedPort")]
if name == "seaweedfs":
ports = {int(p["PublishedPort"]) for p in published}
if ports != {int(os.environ.get("S3_PORT", read_env().get("S3_PORT", "9000")))}:
raise AssertionError(f"unexpected published SeaweedFS ports: {ports}")
elif name in ("api", "postgres", "redis", "migrate", "s3-init"):
if published:
raise AssertionError(f"{name} publishes a host port: {published}")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
args = parser.parse_args()
del args
env = read_env()
for key in ("S3_PUBLIC_ENDPOINT", "S3_BUCKET", "S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY"):
if not env.get(key):
raise AssertionError(f"missing {key} in environment/.env")
client = s3_client(env)
key = "reconcile-tests/private-bucket-" + uuid.uuid4().hex
client.put_object(Bucket=env["S3_BUCKET"], Key=key, Body=b"private", ContentType="text/plain")
try:
url = env["S3_PUBLIC_ENDPOINT"].rstrip("/") + "/" + env["S3_BUCKET"] + "/" + key
try:
urllib.request.urlopen(url, timeout=10)
except urllib.error.HTTPError as error:
if error.code not in (401, 403):
raise AssertionError(f"anonymous GET returned HTTP {error.code}, expected 403") from error
else:
raise AssertionError("anonymous GET succeeded on a private bucket")
for operation in ("create_bucket", "delete_bucket"):
try:
if operation == "create_bucket":
client.create_bucket(Bucket="forbidden-" + uuid.uuid4().hex[:12])
else:
client.delete_bucket(Bucket=env["S3_BUCKET"])
except ClientError as error:
if "AccessDenied" not in str(error):
raise AssertionError(f"{operation} failed with an unexpected error: {error}") from error
else:
raise AssertionError(f"restricted identity was allowed to {operation}")
finally:
client.delete_object(Bucket=env["S3_BUCKET"], Key=key)
check_public_ports()
print("PASS: bucket rejects anonymous reads; API identity cannot administer it; no admin UI is published")
if __name__ == "__main__":
main()
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Concurrent registration with the same username: one 201, the rest 409."""
from __future__ import annotations
import argparse
import uuid
from concurrent.futures import ThreadPoolExecutor
from common import HttpClient, assert_status, error_code
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--workers", type=int, default=8)
args = parser.parse_args()
client = HttpClient(args.base_url)
username = "race_" + uuid.uuid4().hex[:16]
body = {
"username": username,
"display_name": "Race candidate",
"password": "T3st-" + uuid.uuid4().hex,
}
def register(_index: int):
status, _, payload, _ = client.call("POST", "/api/v1/users", body)
return status, error_code(payload)
with ThreadPoolExecutor(max_workers=args.workers) as executor:
results = list(executor.map(register, range(args.workers)))
statuses = [status for status, _code in results]
if statuses.count(201) != 1 or statuses.count(409) != args.workers - 1:
raise AssertionError(f"expected one 201 and {args.workers - 1} conflicts, got {statuses}")
for status, code in results:
if status == 409 and code != "conflict":
raise AssertionError("409 must carry conflict code")
session = client.login(body)
assert session["user"]["username"] == username
print(f"PASS: {args.workers} concurrent registrations produced exactly one user and one session")
if __name__ == "__main__":
main()
+166
View File
@@ -0,0 +1,166 @@
#!/usr/bin/env python3
"""Lab4/Lab5 evidence: safe S3/PostgreSQL reconciliation with a grace period."""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import uuid
from pathlib import Path
import boto3
from botocore.config import Config
from common import HttpClient, assert_status
ROOT = Path(__file__).resolve().parents[1]
def read_env() -> dict[str, str]:
values = dict(os.environ)
path = ROOT / ".env"
if path.is_file():
for line in path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
values.setdefault(key.strip(), value.strip())
return values
def s3_client(env: dict[str, str]):
return boto3.client(
"s3",
endpoint_url=env["S3_PUBLIC_ENDPOINT"],
region_name=env.get("S3_REGION", "us-east-1"),
aws_access_key_id=env["S3_ACCESS_KEY_ID"],
aws_secret_access_key=env["S3_SECRET_ACCESS_KEY"],
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
)
def reconcile(extra: list[str]) -> dict:
result = subprocess.run(
[
"docker",
"compose",
"--env-file",
".env",
"--profile",
"tools",
"run",
"--rm",
"--no-deps",
"reconcile",
"python",
"-m",
"app.reconcile",
*extra,
],
cwd=ROOT,
capture_output=True,
text=True,
timeout=120,
)
if result.returncode != 0:
raise AssertionError(
"reconciler failed: " + (result.stderr or result.stdout)[-500:]
)
for line in reversed(result.stdout.splitlines()):
line = line.strip()
if line.startswith("{"):
return json.loads(line)
raise AssertionError("reconciler did not print a JSON summary")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
args = parser.parse_args()
env = read_env()
client = s3_client(env)
bucket = env["S3_BUCKET"]
# 1. A fresh orphan is reported by a dry-run and is not deleted.
orphan_key = "reconcile-tests/orphan-" + uuid.uuid4().hex
client.put_object(Bucket=bucket, Key=orphan_key, Body=b"orphan", ContentType="text/plain")
dry = reconcile(
["--dry-run", "--orphan-grace-seconds", "0", "--pending-grace-seconds", "0"]
)
if dry["orphans_stale_deleted"] < 1:
raise AssertionError("dry-run did not report the injected orphan")
client.head_object(Bucket=bucket, Key=orphan_key)
# 2. A fresh orphan inside the default grace window is kept by --apply.
kept_key = "reconcile-tests/kept-" + uuid.uuid4().hex
client.put_object(Bucket=bucket, Key=kept_key, Body=b"kept", ContentType="text/plain")
kept = reconcile(
["--apply", "--orphan-grace-seconds", "86400", "--pending-grace-seconds", "86400"]
)
if kept["orphans_fresh_kept"] < 1:
raise AssertionError("grace-window orphan was not reported as kept")
client.head_object(Bucket=bucket, Key=kept_key)
# 3. --apply with grace 0 removes both injected objects.
applied = reconcile(
["--apply", "--orphan-grace-seconds", "0", "--pending-grace-seconds", "0"]
)
if applied["orphans_stale_deleted"] < 2:
raise AssertionError("apply did not delete the injected orphans")
for key in (orphan_key, kept_key):
try:
client.head_object(Bucket=bucket, Key=key)
except Exception:
pass
else:
raise AssertionError("orphan still exists after apply")
# 4. An interrupted presigned upload is removed with its metadata row.
http = HttpClient(args.base_url)
alice, alice_reg = http.register()
token = http.login(alice_reg)["token"]
status, _h, chat, _r = http.call(
"POST",
"/api/v1/chats",
body={"title": "Reconcile pending", "member_ids": [alice["id"]]},
token=token,
)
assert_status(status, 201, "create chat")
import hashlib
import io
from PIL import Image
buffer = io.BytesIO()
Image.new("RGB", (32, 32), (10, 20, 30)).save(buffer, format="PNG")
png = buffer.getvalue()
digest = hashlib.sha256(png).hexdigest()
status, _h, pending, _r = http.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/attachments/presign",
body={
"filename": "pending.png",
"content_type": "image/png",
"size_bytes": len(png),
"sha256": digest,
},
token=token,
)
assert_status(status, 201, "presign pending")
pending_summary = reconcile(
["--apply", "--orphan-grace-seconds", "86400", "--pending-grace-seconds", "0"]
)
if pending_summary["stale_pending_deleted"] < 1:
raise AssertionError("stale pending upload was not removed")
status, _h, _p, _r = http.call(
"GET", "/api/v1/attachments/" + pending["attachment_id"], token=token
)
assert_status(status, 404, "pending metadata removed")
print("PASS: dry-run/apply reconciliation, grace period, orphan cleanup, stale pending cleanup")
if __name__ == "__main__":
main()
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
"""Prove that a failure after the chat insert rolls back the whole chat.
Run inside the API container (psycopg is installed there):
docker compose exec -T api python student-tests/rollback_chat.py
A temporary trigger aborts the second chat_members insert. The API must
return a bounded 500 and leave no chat row, because chat + membership share
one transaction.
"""
from __future__ import annotations
import argparse
import os
import uuid
import psycopg
from common import HttpClient, assert_status, error_code
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--database-url", default=os.environ.get("DATABASE_URL"))
args = parser.parse_args()
if not args.database_url:
raise SystemExit("DATABASE_URL is required")
client = HttpClient(args.base_url)
actor, actor_registration = client.register()
victim, _victim_registration = client.register()
session = client.login(actor_registration)
token = session["token"]
title = "rollback-" + uuid.uuid4().hex
function_name = "test_fail_member_" + uuid.uuid4().hex[:8]
victim_id = str(uuid.UUID(victim["id"]))
with psycopg.connect(args.database_url, autocommit=True) as conn:
conn.execute(
f"""
CREATE FUNCTION {function_name}() RETURNS trigger AS $$
BEGIN
IF NEW.user_id = '{victim_id}'::uuid THEN
RAISE EXCEPTION 'injected membership failure';
END IF;
RETURN NEW;
END
$$ LANGUAGE plpgsql
"""
)
conn.execute(
f"CREATE TRIGGER {function_name} BEFORE INSERT ON chat_members "
f"FOR EACH ROW EXECUTE FUNCTION {function_name}()"
)
try:
status, _, payload, _ = client.call(
"POST",
"/api/v1/chats",
{"title": title, "member_ids": [actor["id"], victim["id"]]},
token=token,
)
assert_status(status, 500, "injected membership failure")
if error_code(payload) != "internal_error":
raise AssertionError("unexpected error code for injected failure")
rows = conn.execute("SELECT count(*) FROM chats WHERE title = %s", (title,)).fetchone()
if rows[0] != 0:
raise AssertionError("chat survived a failed membership transaction")
finally:
conn.execute(f"DROP TRIGGER IF EXISTS {function_name} ON chat_members")
conn.execute(f"DROP FUNCTION IF EXISTS {function_name}()")
status, _, chat, _ = client.call(
"POST",
"/api/v1/chats",
{"title": title + "-ok", "member_ids": [actor["id"], victim["id"]]},
token=token,
)
assert_status(status, 201, "chat after trigger cleanup")
assert set(chat["member_ids"]) == {actor["id"], victim["id"]}
print("PASS: failed membership insert rolled back the chat; subsequent create is atomic")
if __name__ == "__main__":
main()
+199
View File
@@ -0,0 +1,199 @@
#!/usr/bin/env python3
"""Lab5 track 1: compare API traffic/RAM for proxy vs presigned direct upload."""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import math
import os
import re
import subprocess
import threading
import time
from PIL import Image
from common import HttpClient, assert_status
MEM_RE = re.compile(r"([0-9.]+)\s*(B|KiB|MiB|GiB)")
def make_png(target_bytes: int) -> bytes:
pixels = max(1, target_bytes // 3)
width = max(32, int(math.sqrt(pixels * 1.4)))
height = max(32, pixels // width)
image = Image.frombytes("RGB", (width, height), os.urandom(width * height * 3))
buffer = io.BytesIO()
image.save(buffer, format="PNG", compress_level=1)
return buffer.getvalue()
def api_containers(prefix: str) -> list[str]:
try:
result = subprocess.run(
["docker", "ps", "--filter", "name=" + prefix, "--format", "{{.Names}}"],
capture_output=True,
text=True,
timeout=10,
)
except (OSError, subprocess.SubprocessError):
return []
return [line.strip() for line in result.stdout.splitlines() if line.strip()]
def api_net_bytes(names: list[str]) -> dict[str, int]:
total = 0
for name in names:
try:
result = subprocess.run(
["docker", "exec", name, "cat", "/proc/net/dev"],
capture_output=True,
text=True,
timeout=10,
)
except (OSError, subprocess.SubprocessError):
continue
for line in result.stdout.splitlines():
if "eth0:" not in line:
continue
fields = line.split("eth0:")[1].split()
# RX bytes is field 0; TX bytes is field 8.
total += int(fields[0]) + int(fields[8])
return {"total": total}
def memory_mib(text: str) -> float | None:
match = MEM_RE.search(text)
if not match:
return None
return float(match.group(1)) * {"B": 1 / 1024 / 1024, "KiB": 1 / 1024, "MiB": 1, "GiB": 1024}[match.group(2)]
def api_mem_mib(prefix: str) -> float:
try:
result = subprocess.run(
["docker", "stats", "--no-stream", "--format", "{{.Name}} {{.MemUsage}}"],
capture_output=True,
text=True,
timeout=10,
)
except (OSError, subprocess.SubprocessError):
return 0.0
total = 0.0
for line in result.stdout.splitlines():
name, _, mem = line.partition(" ")
if prefix in name:
value = memory_mib(mem)
if value is not None:
total += value
return total
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--container-prefix", default="mtusi-lab4-api")
parser.add_argument("--output", default="")
args = parser.parse_args()
client = HttpClient(args.base_url)
alice, alice_reg = client.register()
token = client.login(alice_reg)["token"]
status, _h, chat, _r = client.call(
"POST",
"/api/v1/chats",
body={"title": "Transfer comparison", "member_ids": [alice["id"]]},
token=token,
)
assert_status(status, 201, "create chat")
names = api_containers(args.container_prefix)
results = []
for target in (512 * 1024, 4 * 1024 * 1024):
content = make_png(target)
digest = hashlib.sha256(content).hexdigest()
# Proxy: client -> API -> S3, all bytes pass through the API process.
before = api_net_bytes(names)["total"]
mem_before = api_mem_mib(args.container_prefix)
status, _h, _p, _r = client.raw(
"POST",
"/api/v1/chats/" + chat["id"] + "/attachments?filename=proxy.png",
data=content,
headers={"Authorization": "Bearer " + token, "Content-Type": "image/png"},
timeout=120,
)
assert_status(status, 201, "proxy upload")
after = api_net_bytes(names)["total"]
mem_after = api_mem_mib(args.container_prefix)
proxy = {
"file_bytes": len(content),
"api_network_bytes": after - before,
"api_memory_growth_mib": round(max(0.0, mem_after - mem_before), 2),
"client_to_api_bytes": len(content),
"client_to_s3_bytes": 0,
}
# Direct: presign, client -> S3, then complete reads the object once to
# verify the checksum. The public API never receives the file body.
status, _h, presign, _r = client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/attachments/presign",
body={
"filename": "direct.png",
"content_type": "image/png",
"size_bytes": len(content),
"sha256": digest,
},
token=token,
)
assert_status(status, 201, "presign")
status, _h, _p, _r = client.raw(
"PUT", presign["upload_url"], data=content, headers=presign["headers"], timeout=120
)
assert_status(status, 200, "direct PUT")
before = api_net_bytes(names)["total"]
mem_before = api_mem_mib(args.container_prefix)
peak = {"value": mem_before}
stop = threading.Event()
def sampler() -> None:
while not stop.is_set():
peak["value"] = max(peak["value"], api_mem_mib(args.container_prefix))
time.sleep(0.1)
thread = threading.Thread(target=sampler, daemon=True)
thread.start()
status, _h, _p, _r = client.call(
"POST",
"/api/v1/attachments/" + presign["attachment_id"] + "/complete",
body={"sha256": digest, "size_bytes": len(content)},
token=token,
)
stop.set()
thread.join(timeout=2)
assert_status(status, 200, "complete")
after = api_net_bytes(names)["total"]
direct = {
"file_bytes": len(content),
"api_network_bytes": after - before,
"api_memory_peak_mib": round(peak["value"], 2),
"api_memory_growth_mib": round(max(0.0, peak["value"] - mem_before), 2),
"client_to_api_bytes": 0,
"client_to_s3_bytes": len(content),
}
results.append({"proxy": proxy, "direct": direct})
summary = {"container_prefix": args.container_prefix, "sizes": results}
print(json.dumps(summary, ensure_ascii=False, sort_keys=True))
if args.output:
with open(args.output, "w", encoding="utf-8") as handle:
json.dump(summary, handle, ensure_ascii=False, indent=2, sort_keys=True)
print("PASS: measured proxy vs direct API traffic and memory at two file sizes")
if __name__ == "__main__":
main()
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env python3
"""Lab4 experiment: 10+ concurrent uploads with API container peak memory.
The uploads are streamed to an ephemeral file and decoded under a bounded
semaphore, so this test looks for a flat memory profile rather than a linear
growth with concurrency.
"""
from __future__ import annotations
import argparse
import io
import json
import os
import re
import subprocess
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from PIL import Image
from common import HttpClient, assert_status
MEM_RE = re.compile(r"([0-9.]+)\s*(B|KiB|MiB|GiB)")
def make_png(width: int, height: int) -> bytes:
# Random pixels compress poorly, giving a realistic multi-MiB upload.
image = Image.frombytes("RGB", (width, height), os.urandom(width * height * 3))
buffer = io.BytesIO()
image.save(buffer, format="PNG", compress_level=1)
return buffer.getvalue()
def memory_mib(text: str) -> float | None:
match = MEM_RE.search(text)
if not match:
return None
value = float(match.group(1))
unit = match.group(2)
return value * {"B": 1 / 1024 / 1024, "KiB": 1 / 1024, "MiB": 1, "GiB": 1024}[unit]
def sample_api_memory(prefix: str) -> dict[str, float]:
try:
result = subprocess.run(
[
"docker",
"stats",
"--no-stream",
"--format",
"{{.Name}} {{.MemUsage}}",
],
capture_output=True,
text=True,
timeout=10,
)
except (OSError, subprocess.SubprocessError):
return {}
if result.returncode != 0:
return {}
usage = {}
for line in result.stdout.splitlines():
name, _, mem = line.partition(" ")
if prefix in name:
value = memory_mib(mem)
if value is not None:
usage[name] = value
return usage
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--workers", type=int, default=10)
parser.add_argument("--width", type=int, default=1400)
parser.add_argument("--height", type=int, default=1000)
parser.add_argument("--container-prefix", default="mtusi-lab4-api")
parser.add_argument("--output", default="")
args = parser.parse_args()
client = HttpClient(args.base_url)
alice, alice_reg = client.register()
alice_token = client.login(alice_reg)["token"]
status, _h, chat, _r = client.call(
"POST",
"/api/v1/chats",
body={"title": "Upload memory experiment", "member_ids": [alice["id"]]},
token=alice_token,
)
assert_status(status, 201, "create chat")
content = make_png(args.width, args.height)
peak: dict[str, float] = {}
stop = threading.Event()
def sampler() -> None:
while not stop.is_set():
for name, value in sample_api_memory(args.container_prefix).items():
peak[name] = max(peak.get(name, 0.0), value)
time.sleep(0.2)
sampler_thread = threading.Thread(target=sampler, name="memory-sampler", daemon=True)
sampler_thread.start()
baseline = sample_api_memory(args.container_prefix)
def upload(index: int):
return client.raw(
"POST",
"/api/v1/chats/" + chat["id"] + "/attachments?filename=load-%d.png" % index,
data=content,
headers={"Authorization": "Bearer " + alice_token, "Content-Type": "image/png"},
timeout=120,
)
started = time.monotonic()
with ThreadPoolExecutor(max_workers=args.workers) as pool:
results = list(pool.map(upload, range(args.workers)))
elapsed = time.monotonic() - started
stop.set()
sampler_thread.join(timeout=2)
statuses = [status for status, _h, _p, _r in results]
assert_status(min(statuses), 201, "concurrent uploads")
if max(statuses) != 201:
raise AssertionError(f"some uploads failed: {statuses}")
summary = {
"workers": args.workers,
"file_bytes": len(content),
"elapsed_seconds": round(elapsed, 3),
"successful_uploads": len(statuses),
"baseline_mib": {k: round(v, 2) for k, v in baseline.items()},
"peak_mib": {k: round(v, 2) for k, v in peak.items()},
"peak_growth_mib": {
k: round(peak.get(k, 0.0) - baseline.get(k, 0.0), 2) for k in peak
},
}
print(json.dumps(summary, ensure_ascii=False, sort_keys=True))
if args.output:
with open(args.output, "w", encoding="utf-8") as handle:
json.dump(summary, handle, ensure_ascii=False, indent=2, sort_keys=True)
print("PASS: concurrent uploads completed; inspect peak_mib for the bounded-memory claim")
if __name__ == "__main__":
main()