lab6: observability — OTel Collector, Prometheus, Loki, Tempo, Grafana
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
"""Генерация тестовых сообщений для EXPLAIN.
|
||||
|
||||
Создаёт пользователя, чат и N сообщений. N по умолчанию 10 000.
|
||||
Запуск:
|
||||
python3 seed_messages.py --base-url http://localhost:8080 --count 10000
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
def call(base: str, method: str, path: str, headers: dict | None = None, body: dict | None = None) -> tuple[int, dict | None]:
|
||||
data = None
|
||||
h = dict(headers or {})
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(base + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=30)
|
||||
raw = resp.read()
|
||||
return resp.code, json.loads(raw) if raw else None
|
||||
except urllib.error.HTTPError as e:
|
||||
raw = e.read()
|
||||
try:
|
||||
return e.code, json.loads(raw) if raw else None
|
||||
except Exception:
|
||||
return e.code, None
|
||||
|
||||
|
||||
def main() -> None:
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--count", type=int, default=10000)
|
||||
p.add_argument("--batch", type=int, default=500, help="Сообщений между progress-логами")
|
||||
args = p.parse_args()
|
||||
base = args.base_url.rstrip("/")
|
||||
|
||||
username = "seed_" + uuid.uuid4().hex[:12]
|
||||
password = "seed-pass-1234567890"
|
||||
|
||||
# Регистрация
|
||||
code, user = call(base, "POST", "/api/v1/users", body={
|
||||
"username": username, "display_name": "Seed User", "password": password,
|
||||
})
|
||||
assert code == 201, f"register failed: {code} {user}"
|
||||
|
||||
# Логин
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
code, session = call(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred})
|
||||
assert code == 201, f"login failed: {code} {session}"
|
||||
token = session["token"]
|
||||
user_id = session["user"]["id"]
|
||||
|
||||
# Чат
|
||||
code, chat = call(base, "POST", "/api/v1/chats", headers={"Authorization": "Bearer " + token}, body={
|
||||
"title": "Seed chat", "member_ids": [user_id],
|
||||
})
|
||||
assert code == 201, f"chat failed: {code} {chat}"
|
||||
chat_id = chat["id"]
|
||||
print(f"chat_id: {chat_id}")
|
||||
print(f"seeding {args.count} messages...")
|
||||
|
||||
started = time.monotonic()
|
||||
for i in range(args.count):
|
||||
code, msg = call(
|
||||
base, "POST", f"/api/v1/chats/{chat_id}/messages",
|
||||
headers={"Authorization": "Bearer " + token},
|
||||
body={"text": f"seed-{i:06d}-{uuid.uuid4().hex[:8]}"},
|
||||
)
|
||||
assert code == 201, f"message {i} failed: {code} {msg}"
|
||||
if (i + 1) % args.batch == 0:
|
||||
elapsed = time.monotonic() - started
|
||||
rps = (i + 1) / elapsed
|
||||
print(f" {i + 1}/{args.count} ({rps:.0f} msg/s)")
|
||||
|
||||
elapsed = time.monotonic() - started
|
||||
print(f"done: {args.count} messages in {elapsed:.1f}s ({args.count / elapsed:.0f} msg/s)")
|
||||
print(f"chat_id: {chat_id}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,292 @@
|
||||
"""Негативные тесты для вложений (lab4 grade 4).
|
||||
|
||||
Запуск:
|
||||
python3 test_attachments_negative.py --base-url http://localhost:8080
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
import time
|
||||
|
||||
BASE = (
|
||||
sys.argv[sys.argv.index("--base-url") + 1]
|
||||
if "--base-url" in sys.argv
|
||||
else "http://localhost:8080"
|
||||
)
|
||||
|
||||
|
||||
def call(method, path, headers=None, body=None, raw=None):
|
||||
data = None
|
||||
h = dict(headers or {})
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
h["Content-Type"] = "application/json"
|
||||
elif raw is not None:
|
||||
data = raw
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=30)
|
||||
payload = resp.read()
|
||||
return resp.status, json.loads(payload) if payload else None, dict(resp.headers)
|
||||
except urllib.error.HTTPError as e:
|
||||
payload = e.read()
|
||||
try:
|
||||
return e.code, json.loads(payload) if payload else None, dict(e.headers)
|
||||
except Exception:
|
||||
return e.code, None, dict(e.headers)
|
||||
|
||||
|
||||
def make_user(label):
|
||||
username = f"att_{label}_{uuid.uuid4().hex[:10]}"
|
||||
password = "negative-pass-1234567890"
|
||||
code, user, _ = call("POST", "/api/v1/users", body={
|
||||
"username": username, "display_name": f"Att {label}", "password": password,
|
||||
})
|
||||
assert code == 201, f"register {label} failed: {code} {user}"
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
code, session, _ = call("POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + cred})
|
||||
assert code == 201, f"login {label} failed: {code}"
|
||||
return {
|
||||
"id": user["id"],
|
||||
"token": session["token"],
|
||||
}
|
||||
|
||||
|
||||
def make_chat(owner, member_ids=None):
|
||||
if member_ids is None:
|
||||
member_ids = [owner["id"]]
|
||||
code, chat, _ = call("POST", "/api/v1/chats",
|
||||
headers={"Authorization": "Bearer " + owner["token"]},
|
||||
body={"title": "Negative", "member_ids": member_ids})
|
||||
assert code == 201, f"chat failed: {code} {chat}"
|
||||
return chat["id"]
|
||||
|
||||
|
||||
def upload(token, chat_id, filename, data, content_type):
|
||||
return call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat_id}/attachments?filename={filename}",
|
||||
headers={"Authorization": "Bearer " + token, "Content-Type": content_type},
|
||||
raw=data,
|
||||
)
|
||||
|
||||
|
||||
def test_decompression_bomb():
|
||||
"""PNG 8200x5000 (41M пикселей) — маленький по размеру, но огромный по пикселям."""
|
||||
from PIL import Image
|
||||
import io as _io
|
||||
alice = make_user("bomb")
|
||||
chat = make_chat(alice)
|
||||
|
||||
img = Image.new("RGB", (8200, 5000), color=(255, 0, 0))
|
||||
buf = _io.BytesIO()
|
||||
img.save(buf, format="PNG", compress_level=9)
|
||||
data = buf.getvalue()
|
||||
assert len(data) < 500 * 1024, f"expected small compressed, got {len(data)}"
|
||||
|
||||
started = time.monotonic()
|
||||
code, _, _ = upload(alice["token"], chat, "bomb.png", data, "image/png")
|
||||
elapsed = time.monotonic() - started
|
||||
|
||||
assert code == 413, f"expected 413, got {code}"
|
||||
assert elapsed < 2.0, f"expected fast rejection (<2s), got {elapsed:.2f}s"
|
||||
print(f"PASS: decompression bomb -> 413 ({len(data)} bytes, {elapsed:.2f}s)")
|
||||
|
||||
|
||||
def test_invalid_cursor():
|
||||
"""Cursor с невалидным timestamp или UUID -> 400."""
|
||||
import base64 as _b64
|
||||
alice = make_user("cursor")
|
||||
chat = make_chat(alice)
|
||||
chat_id = chat
|
||||
|
||||
# Невалидный timestamp
|
||||
bad_t = _b64.urlsafe_b64encode(
|
||||
json.dumps({
|
||||
"s": f"chat:{chat_id}",
|
||||
"t": "not-a-time",
|
||||
"i": "00000000-0000-4000-8000-000000000000",
|
||||
}).encode()
|
||||
).decode().rstrip("=")
|
||||
code, _, _ = call(
|
||||
"GET", f"/api/v1/chats/{chat_id}/messages?cursor={bad_t}",
|
||||
headers={"Authorization": "Bearer " + alice["token"]},
|
||||
)
|
||||
assert code == 400, f"invalid timestamp: expected 400, got {code}"
|
||||
|
||||
# Невалидный UUID
|
||||
bad_i = _b64.urlsafe_b64encode(
|
||||
json.dumps({
|
||||
"s": f"chat:{chat_id}",
|
||||
"t": "2026-01-01T00:00:00.000000Z",
|
||||
"i": "not-a-uuid",
|
||||
}).encode()
|
||||
).decode().rstrip("=")
|
||||
code, _, _ = call(
|
||||
"GET", f"/api/v1/chats/{chat_id}/messages?cursor={bad_i}",
|
||||
headers={"Authorization": "Bearer " + alice["token"]},
|
||||
)
|
||||
assert code == 400, f"invalid uuid: expected 400, got {code}"
|
||||
|
||||
print("PASS: invalid cursor -> 400 (timestamp and uuid)")
|
||||
|
||||
|
||||
def test_filename_c1():
|
||||
"""Filename с C1 control (U+0085) -> 400."""
|
||||
from pathlib import Path
|
||||
fixture = Path(__file__).resolve().parent.parent / "tests/fixtures/sample.png"
|
||||
png = fixture.read_bytes()
|
||||
alice = make_user("c1")
|
||||
chat = make_chat(alice)
|
||||
|
||||
# filename = "c1\u0085.png" — C1 control U+0085
|
||||
code, _, _ = call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat}/attachments?filename=c1%C2%85.png",
|
||||
headers={
|
||||
"Authorization": "Bearer " + alice["token"],
|
||||
"Content-Type": "image/png",
|
||||
},
|
||||
raw=png,
|
||||
)
|
||||
assert code == 400, f"expected 400 for C1 filename, got {code}"
|
||||
print("PASS: C1 filename -> 400")
|
||||
|
||||
|
||||
def test_s3_unavailable():
|
||||
"""S3 down: readiness 503, upload 503."""
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
alice = make_user("s3down")
|
||||
chat = make_chat(alice)
|
||||
|
||||
# 1. Baseline: readiness 200
|
||||
code, _, _ = call("GET", "/health/ready")
|
||||
assert code == 200, f"readiness should be 200 before stop, got {code}"
|
||||
|
||||
# 2. Останавливаем S3
|
||||
try:
|
||||
subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", "stop", "s3"],
|
||||
check=True, capture_output=True, text=True,
|
||||
cwd=str(Path(__file__).resolve().parent.parent),
|
||||
timeout=30,
|
||||
)
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise SystemExit(f"failed to stop s3: {e.stderr}")
|
||||
|
||||
import time as _t
|
||||
_t.sleep(3)
|
||||
|
||||
try:
|
||||
# 3. Readiness должен быть 503
|
||||
code, body, _ = call("GET", "/health/ready")
|
||||
assert code == 503, f"readiness should be 503 with S3 down, got {code}"
|
||||
assert body and body["error"]["code"] == "unavailable", \
|
||||
f"expected unavailable, got {body}"
|
||||
|
||||
# 4. Upload должен быть 503
|
||||
fixture = Path(__file__).resolve().parent.parent / "tests/fixtures/sample.png"
|
||||
png = fixture.read_bytes()
|
||||
code, body, _ = upload(alice["token"], chat, "s3down.png", png, "image/png")
|
||||
assert code == 503, f"upload should be 503 with S3 down, got {code}"
|
||||
assert body and body["error"]["code"] == "unavailable", \
|
||||
f"expected unavailable, got {body}"
|
||||
|
||||
print("PASS: S3 down -> readiness 503, upload 503")
|
||||
finally:
|
||||
# 5. Возвращаем S3
|
||||
subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", "start", "s3"],
|
||||
check=False, capture_output=True, text=True,
|
||||
cwd=str(Path(__file__).resolve().parent.parent),
|
||||
timeout=30,
|
||||
)
|
||||
# Ждём готовности
|
||||
deadline = _t.monotonic() + 30
|
||||
while _t.monotonic() < deadline:
|
||||
code, _, _ = call("GET", "/health/ready")
|
||||
if code == 200:
|
||||
break
|
||||
_t.sleep(1)
|
||||
|
||||
|
||||
def main():
|
||||
alice = make_user("alice")
|
||||
bob = make_user("bob")
|
||||
eve = make_user("eve")
|
||||
chat_ab = make_chat(alice, [alice["id"], bob["id"]])
|
||||
chat_alice = make_chat(alice)
|
||||
|
||||
# 1. Oversize: > 10 MiB
|
||||
big = b"\x89PNG\r\n\x1a\n" + b"\x00" * (10 * 1024 * 1024 + 1)
|
||||
code, _, _ = upload(alice["token"], chat_ab, "big.png", big, "image/png")
|
||||
assert code == 413, f"oversize: expected 413, got {code}"
|
||||
print("PASS: oversize -> 413")
|
||||
|
||||
# 2. Corrupted: валидная сигнатура, битые данные
|
||||
corrupted = b"\x89PNG\r\n\x1a\n" + b"\xff" * 100
|
||||
code, _, _ = upload(alice["token"], chat_ab, "corrupted.png", corrupted, "image/png")
|
||||
assert code == 415, f"corrupted: expected 415, got {code}"
|
||||
print("PASS: corrupted -> 415")
|
||||
|
||||
# 3. MIME-spoofing: image/png, но текст
|
||||
spoofed = b"this is definitely not an image"
|
||||
code, _, _ = upload(alice["token"], chat_ab, "spoof.png", spoofed, "image/png")
|
||||
assert code == 415, f"mime spoof: expected 415, got {code}"
|
||||
print("PASS: mime spoofing -> 415")
|
||||
|
||||
# 4. Чужой attachment_id: eve скачивает вложение из chat_ab
|
||||
# Сначала загрузим настоящий PNG (тестовый fixture)
|
||||
from pathlib import Path
|
||||
fixture = Path(__file__).resolve().parent.parent / "tests/fixtures/sample.png"
|
||||
if not fixture.exists():
|
||||
raise SystemExit(f"fixture not found: {fixture}")
|
||||
png = fixture.read_bytes()
|
||||
code, att, _ = upload(alice["token"], chat_ab, "sample.png", png, "image/png")
|
||||
assert code == 201, f"upload fixture failed: {code} {att}"
|
||||
att_id = att["id"]
|
||||
|
||||
code, _, _ = call("GET", f"/api/v1/attachments/{att_id}",
|
||||
headers={"Authorization": "Bearer " + eve["token"]})
|
||||
assert code == 404, f"outsider metadata: expected 404, got {code}"
|
||||
code, _, _ = call("GET", f"/api/v1/attachments/{att_id}/content",
|
||||
headers={"Authorization": "Bearer " + eve["token"]})
|
||||
assert code == 404, f"outsider content: expected 404, got {code}"
|
||||
print("PASS: outsider attachment -> 404")
|
||||
|
||||
# 5. Вложение из другого чата
|
||||
# Загружаем в chat_alice, прикрепляем к сообщению в chat_ab
|
||||
code, att2, _ = upload(alice["token"], chat_alice, "other.png", png, "image/png")
|
||||
assert code == 201, f"upload to chat_alice failed: {code} {att2}"
|
||||
other_id = att2["id"]
|
||||
|
||||
code, _, _ = call(
|
||||
"POST", f"/api/v1/chats/{chat_ab}/messages",
|
||||
headers={
|
||||
"Authorization": "Bearer " + alice["token"],
|
||||
"Idempotency-Key": uuid.uuid4().hex,
|
||||
},
|
||||
body={"text": "cross-chat", "attachment_ids": [other_id]},
|
||||
)
|
||||
assert code == 404, f"cross-chat attachment: expected 404, got {code}"
|
||||
print("PASS: cross-chat attachment -> 404")
|
||||
|
||||
print("\nNew tests from reviewer feedback")
|
||||
test_decompression_bomb()
|
||||
test_invalid_cursor()
|
||||
test_filename_c1()
|
||||
|
||||
print("\nS3 unavailable")
|
||||
test_s3_unavailable()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+100
@@ -0,0 +1,100 @@
|
||||
"""Проверка отказа Valkey и корректности logout при недоступном кэше."""
|
||||
from __future__ import annotations
|
||||
import base64, json, subprocess, sys, time, urllib.error, urllib.request, uuid
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
||||
|
||||
def call(method, path, headers=None, body=None):
|
||||
data = None
|
||||
h = dict(headers or {})
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
r = urllib.request.urlopen(req, timeout=10)
|
||||
raw = r.read()
|
||||
return r.code, json.loads(raw) if raw else None
|
||||
except urllib.error.HTTPError as e:
|
||||
raw = e.read()
|
||||
try:
|
||||
return e.code, json.loads(raw) if raw else None
|
||||
except Exception:
|
||||
return e.code, None
|
||||
|
||||
def stop_cache():
|
||||
subprocess.run(COMPOSE + ["stop", "cache"], check=True)
|
||||
|
||||
def start_cache():
|
||||
subprocess.run(COMPOSE + ["start", "cache"], check=True)
|
||||
|
||||
def restart_api():
|
||||
subprocess.run(COMPOSE + ["restart", "api"], check=True)
|
||||
|
||||
def wait_ready(deadline=60):
|
||||
end = time.monotonic() + deadline
|
||||
while time.monotonic() < end:
|
||||
try:
|
||||
code, _ = call("GET", "/health/ready")
|
||||
if code == 200:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise SystemExit("API did not become ready")
|
||||
|
||||
def main():
|
||||
username = "cf_" + uuid.uuid4().hex[:10]
|
||||
password = "cache-fail-pass-1234567890"
|
||||
code, _ = call("POST", "/api/v1/users", body={
|
||||
"username": username, "display_name": "Cache Fail", "password": password,
|
||||
})
|
||||
assert code == 201, code
|
||||
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
code, session = call("POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + cred})
|
||||
assert code == 201, code
|
||||
token = session["token"]
|
||||
|
||||
# Токен работает
|
||||
code, _ = call("GET", "/api/v1/users/me",
|
||||
headers={"Authorization": "Bearer " + token})
|
||||
assert code == 200, code
|
||||
|
||||
# Останавливаем Valkey
|
||||
stop_cache()
|
||||
time.sleep(2)
|
||||
|
||||
# API должно работать в degraded mode
|
||||
code, _ = call("GET", "/api/v1/users/me",
|
||||
headers={"Authorization": "Bearer " + token})
|
||||
assert code == 200, f"degraded mode failed: {code}"
|
||||
print("PASS: API works with Valkey down (degraded mode)")
|
||||
|
||||
# Logout при недоступном Valkey должен вернуть 204
|
||||
code, _ = call("DELETE", "/api/v1/auth/sessions/current",
|
||||
headers={"Authorization": "Bearer " + token})
|
||||
assert code == 204, f"logout with cache down returned {code}"
|
||||
print("PASS: logout with cache down returned 204")
|
||||
|
||||
# Токен немедленно недействителен (проверка через БД)
|
||||
code, _ = call("GET", "/api/v1/users/me",
|
||||
headers={"Authorization": "Bearer " + token})
|
||||
assert code == 401, f"revoked token still works with cache down: {code}"
|
||||
print("PASS: revoked token rejected while cache down")
|
||||
|
||||
# Поднимаем Valkey, рестартуем API — критический регресс-тест
|
||||
start_cache()
|
||||
time.sleep(2)
|
||||
restart_api()
|
||||
wait_ready()
|
||||
|
||||
code, _ = call("GET", "/api/v1/users/me",
|
||||
headers={"Authorization": "Bearer " + token})
|
||||
assert code == 401, f"REGRESSION: revoked token resurrected after cache restart: {code}"
|
||||
print("PASS: revoked token still 401 after cache restart (regression fixed)")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,179 @@
|
||||
"""10 одновременных загрузок 10 MiB: все 202, все ready, RAM API.
|
||||
|
||||
Запуск:
|
||||
python3 student_tests/test_concurrent_uploads.py --base-url http://localhost:8080
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
BASE = (
|
||||
sys.argv[sys.argv.index("--base-url") + 1]
|
||||
if "--base-url" in sys.argv
|
||||
else "http://localhost:8080"
|
||||
)
|
||||
CONCURRENCY = 10
|
||||
SIZE_MB = 10
|
||||
API_CONTAINER = "mtusi2026lab5-api-1"
|
||||
|
||||
|
||||
def call(method, path, headers=None, body=None, raw=None, timeout=120):
|
||||
data = None
|
||||
h = dict(headers or {})
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
h["Content-Type"] = "application/json"
|
||||
elif raw is not None:
|
||||
data = raw
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=timeout)
|
||||
payload = resp.read()
|
||||
return resp.status, json.loads(payload) if payload else None
|
||||
except urllib.error.HTTPError as e:
|
||||
payload = e.read()
|
||||
try:
|
||||
return e.code, json.loads(payload) if payload else None
|
||||
except Exception:
|
||||
return e.code, None
|
||||
|
||||
|
||||
def make_user(label):
|
||||
username = f"conc_{label}_{uuid.uuid4().hex[:10]}"
|
||||
password = "conc-pass-1234567890"
|
||||
code, user = call("POST", "/api/v1/users", body={
|
||||
"username": username, "display_name": f"Conc {label}", "password": password,
|
||||
})
|
||||
assert code == 201, f"register failed: {code} {user}"
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
code, session = call("POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + cred})
|
||||
assert code == 201, f"login failed: {code}"
|
||||
code, chat = call("POST", "/api/v1/chats",
|
||||
headers={"Authorization": "Bearer " + session["token"]},
|
||||
body={"title": "Conc", "member_ids": [user["id"]]})
|
||||
assert code == 201, f"chat failed: {code}"
|
||||
return {"token": session["token"], "chat_id": chat["id"]}
|
||||
|
||||
|
||||
def measure_ram_mb(container):
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", container],
|
||||
capture_output=True, text=True, timeout=5,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
return None
|
||||
mem = result.stdout.strip().split("/")[0].strip()
|
||||
if "MiB" in mem:
|
||||
return float(mem.replace("MiB", "").strip())
|
||||
if "GiB" in mem:
|
||||
return float(mem.replace("GiB", "").strip()) * 1024
|
||||
if "KiB" in mem:
|
||||
return float(mem.replace("KiB", "").strip()) / 1024
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def make_png_of_size(size_bytes):
|
||||
from PIL import Image
|
||||
side = int((size_bytes / 3) ** 0.5)
|
||||
img = Image.new("RGB", (side, side), color=(200, 100, 50))
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="PNG", compress_level=0)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def main():
|
||||
print(f"=== concurrent uploads: {CONCURRENCY} × {SIZE_MB} MiB ===")
|
||||
user = make_user("user")
|
||||
png = make_png_of_size(SIZE_MB * 1024 * 1024)
|
||||
print(f"fixture size: {len(png)} bytes ({len(png) / 1024 / 1024:.2f} MiB)")
|
||||
|
||||
baseline = measure_ram_mb(API_CONTAINER)
|
||||
print(f"baseline RAM: {baseline:.1f} MiB" if baseline else "baseline RAM: unknown")
|
||||
|
||||
peak = baseline or 0.0
|
||||
stop = threading.Event()
|
||||
|
||||
def monitor():
|
||||
nonlocal peak
|
||||
while not stop.is_set():
|
||||
ram = measure_ram_mb(API_CONTAINER)
|
||||
if ram is not None:
|
||||
peak = max(peak, ram)
|
||||
time.sleep(0.2)
|
||||
|
||||
t = threading.Thread(target=monitor, daemon=True)
|
||||
t.start()
|
||||
|
||||
results = []
|
||||
lock = threading.Lock()
|
||||
barrier = threading.Barrier(CONCURRENCY)
|
||||
|
||||
def worker(i):
|
||||
barrier.wait()
|
||||
code, body = call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{user['chat_id']}/attachments?filename=conc-{i}.png",
|
||||
headers={
|
||||
"Authorization": "Bearer " + user["token"],
|
||||
"Content-Type": "image/png",
|
||||
},
|
||||
raw=png,
|
||||
)
|
||||
with lock:
|
||||
results.append((i, code, body))
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=CONCURRENCY) as pool:
|
||||
list(pool.map(worker, range(CONCURRENCY)))
|
||||
elapsed = time.monotonic() - started
|
||||
stop.set()
|
||||
t.join(timeout=2)
|
||||
|
||||
codes = {}
|
||||
for _, code, _ in results:
|
||||
codes[code] = codes.get(code, 0) + 1
|
||||
|
||||
print(f"\nUpload results:")
|
||||
print(f" duration: {elapsed:.2f}s")
|
||||
print(f" status codes: {codes}")
|
||||
print(f" peak RAM: {peak:.1f} MiB (baseline {baseline:.1f} MiB)")
|
||||
assert all(c == 202 for _, c, _ in results), f"not all 202: {codes}"
|
||||
|
||||
# Ждём все ready
|
||||
att_ids = [body["id"] for _, _, body in results]
|
||||
deadline = time.monotonic() + 120
|
||||
ready_count = 0
|
||||
while time.monotonic() < deadline:
|
||||
ready_count = 0
|
||||
for att_id in att_ids:
|
||||
code, att = call("GET", f"/api/v1/attachments/{att_id}",
|
||||
headers={"Authorization": "Bearer " + user["token"]})
|
||||
if code == 200 and att["status"] == "ready":
|
||||
ready_count += 1
|
||||
elif code == 200 and att["status"] == "failed":
|
||||
raise AssertionError(f"att {att_id} failed: {att.get('error_code')}")
|
||||
if ready_count == len(att_ids):
|
||||
break
|
||||
time.sleep(1)
|
||||
|
||||
assert ready_count == len(att_ids), f"only {ready_count}/{len(att_ids)} ready"
|
||||
print(f" all {len(att_ids)} ready in {time.monotonic() - (deadline - 120):.1f}s")
|
||||
print(f"\nPASS: {CONCURRENCY} concurrent uploads 202→ready, peak RAM {peak:.1f} MiB")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+127
@@ -0,0 +1,127 @@
|
||||
"""Проверка отказа PostgreSQL: таймаут запроса и восстановление."""
|
||||
from __future__ import annotations
|
||||
import base64, json, subprocess, sys, time, urllib.error, urllib.request, uuid
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
||||
|
||||
|
||||
def call(method, path, headers=None, body=None, timeout=10):
|
||||
data = None
|
||||
h = dict(headers or {})
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
r = urllib.request.urlopen(req, timeout=timeout)
|
||||
raw = r.read()
|
||||
return r.code, json.loads(raw) if raw else None
|
||||
except urllib.error.HTTPError as e:
|
||||
raw = e.read()
|
||||
try:
|
||||
return e.code, json.loads(raw) if raw else None
|
||||
except Exception:
|
||||
return e.code, None
|
||||
|
||||
|
||||
def stop_db():
|
||||
"""Останавливает контейнер Postgres. TCP-соединения рвутся, psycopg
|
||||
получает ошибку мгновенно — это честный сценарий 'БД упала'."""
|
||||
subprocess.run(COMPOSE + ["stop", "postgres"], check=True)
|
||||
|
||||
|
||||
def start_db():
|
||||
"""Поднимает Postgres. Не падает, если уже запущен."""
|
||||
subprocess.run(COMPOSE + ["start", "postgres"],
|
||||
capture_output=True, check=False)
|
||||
time.sleep(3)
|
||||
|
||||
|
||||
def restart_api():
|
||||
"""Пересоздаёт API, чтобы пул соединений не держал мёртвые сессии."""
|
||||
subprocess.run(COMPOSE + ["restart", "api"],
|
||||
capture_output=True, check=False)
|
||||
|
||||
|
||||
def wait_ready(deadline=60):
|
||||
end = time.monotonic() + deadline
|
||||
while time.monotonic() < end:
|
||||
try:
|
||||
code, _ = call("GET", "/health/ready", timeout=5)
|
||||
if code == 200:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise SystemExit("API did not become ready")
|
||||
|
||||
|
||||
def ensure_clean_state():
|
||||
"""Возвращает стек в рабочее состояние, если предыдущий запуск оставил
|
||||
Postgres остановленным или пул API в плохом состоянии."""
|
||||
subprocess.run(COMPOSE + ["start", "postgres"],
|
||||
capture_output=True, check=False)
|
||||
time.sleep(3)
|
||||
# API перезапускаем, потому что после stop Postgres пул мог забиться
|
||||
# мёртвыми соединениями, и первый запрос упадёт по PoolTimeout.
|
||||
restart_api()
|
||||
wait_ready()
|
||||
|
||||
|
||||
def main():
|
||||
ensure_clean_state()
|
||||
|
||||
# Регистрация и логин — до всякого stop, чтобы тест не падал на подготовке
|
||||
username = "dbf_" + uuid.uuid4().hex[:10]
|
||||
password = "db-fail-pass-1234567890"
|
||||
|
||||
code, _ = call("POST", "/api/v1/users", body={
|
||||
"username": username, "display_name": "DB Fail", "password": password,
|
||||
})
|
||||
assert code == 201, f"failed to create user before stop: {code}"
|
||||
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
code, session = call("POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + cred})
|
||||
assert code == 201, f"failed to login before stop: {code}"
|
||||
token = session["token"]
|
||||
|
||||
stop_db()
|
||||
try:
|
||||
time.sleep(0.5)
|
||||
|
||||
# Запрос к БД должен упасть быстро (TCP порван, psycopg сразу
|
||||
# получает ошибку соединения). Проверяем < 8 секунд.
|
||||
start = time.monotonic()
|
||||
try:
|
||||
code, _ = call("GET", "/api/v1/users/me",
|
||||
headers={"Authorization": "Bearer " + token}, timeout=15)
|
||||
except Exception as exc:
|
||||
elapsed = time.monotonic() - start
|
||||
raise SystemExit(f"request hung: {elapsed:.1f}s, {type(exc).__name__}")
|
||||
elapsed = time.monotonic() - start
|
||||
assert elapsed < 8, f"request took {elapsed:.1f}s (>8s), DB down not handled fast enough"
|
||||
assert code in (500, 503), f"expected 500/503 during DB down, got {code}"
|
||||
print(f"PASS: DB down returned {code} in {elapsed:.1f}s (<8s)")
|
||||
|
||||
# health/ready должен вернуть 503, пока БД недоступна
|
||||
code, _ = call("GET", "/health/ready", timeout=15)
|
||||
assert code == 503, f"expected 503 from ready, got {code}"
|
||||
print("PASS: /health/ready returned 503 during DB down")
|
||||
finally:
|
||||
# Гарантированно поднимаем Postgres даже при падении выше.
|
||||
start_db()
|
||||
# Перезапускаем API, чтобы пул пересоздал соединения с вернувшейся БД.
|
||||
restart_api()
|
||||
wait_ready()
|
||||
|
||||
# Проверяем, что данные и сессия сохранены после восстановления.
|
||||
code, _ = call("GET", "/api/v1/users/me",
|
||||
headers={"Authorization": "Bearer " + token})
|
||||
assert code == 200, f"session lost after DB recovery: {code}"
|
||||
print("PASS: session and data preserved after DB recovery")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Тест expiry: сессия истекает через SESSION_TTL_SECONDS.
|
||||
|
||||
Запуск:
|
||||
SESSION_TTL_SECONDS=2 docker compose up -d --build api
|
||||
python3 test_expiry.py --base-url http://localhost:8080
|
||||
|
||||
Тест создаёт пользователя, логинится, ждёт TTL+1 секунду, проверяет 401.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
BASE = sys.argv[sys.argv.index("--base-url") + 1] if "--base-url" in sys.argv else "http://localhost:8080"
|
||||
|
||||
|
||||
def call(method: str, path: str, headers: dict | None = None, body: dict | None = None) -> tuple[int, dict | None]:
|
||||
data = None
|
||||
h = dict(headers or {})
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=10)
|
||||
raw = resp.read()
|
||||
return resp.code, json.loads(raw) if raw else None
|
||||
except urllib.error.HTTPError as e:
|
||||
raw = e.read()
|
||||
try:
|
||||
return e.code, json.loads(raw) if raw else None
|
||||
except Exception:
|
||||
return e.code, None
|
||||
|
||||
|
||||
def main() -> None:
|
||||
username = "exp_" + uuid.uuid4().hex[:12]
|
||||
password = "expiry-pass-1234567890"
|
||||
|
||||
# Регистрация
|
||||
code, user = call("POST", "/api/v1/users", body={
|
||||
"username": username, "display_name": "Expiry Test", "password": password,
|
||||
})
|
||||
assert code == 201, f"register failed: {code} {user}"
|
||||
|
||||
# Логин
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
code, session = call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred})
|
||||
assert code == 201, f"login failed: {code} {session}"
|
||||
token = session["token"]
|
||||
print(f"session expires_at: {session['expires_at']}")
|
||||
|
||||
# Сразу после логина — токен работает
|
||||
code, me = call("GET", "/api/v1/users/me", headers={"Authorization": "Bearer " + token})
|
||||
assert code == 200, f"token should work immediately, got {code}"
|
||||
print("immediately after login: 200 OK")
|
||||
|
||||
# Ждём истечения
|
||||
time.sleep(3)
|
||||
code, err = call("GET", "/api/v1/users/me", headers={"Authorization": "Bearer " + token})
|
||||
assert code == 401, f"expired token must give 401, got {code}"
|
||||
print(f"after TTL: {code} (expected 401)")
|
||||
print("PASS: expiry — token invalidated after SESSION_TTL_SECONDS")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Повторная доставка ready-задачи: no-op, не создаёт дубли.
|
||||
|
||||
Создаёт attachment, ждёт ready, публикует тот же job повторно,
|
||||
проверяет, что variants не изменились и объекты в S3 не задублированы.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
BASE = (
|
||||
sys.argv[sys.argv.index("--base-url") + 1]
|
||||
if "--base-url" in sys.argv
|
||||
else "http://localhost:8080"
|
||||
)
|
||||
|
||||
|
||||
def call(method, path, headers=None, body=None, raw=None, timeout=30):
|
||||
data = None
|
||||
h = dict(headers or {})
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
h["Content-Type"] = "application/json"
|
||||
elif raw is not None:
|
||||
data = raw
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=timeout)
|
||||
payload = resp.read()
|
||||
return resp.status, json.loads(payload) if payload else None
|
||||
except urllib.error.HTTPError as e:
|
||||
payload = e.read()
|
||||
try:
|
||||
return e.code, json.loads(payload) if payload else None
|
||||
except Exception:
|
||||
return e.code, None
|
||||
|
||||
|
||||
def main():
|
||||
# 1. Регистрация, логин, чат
|
||||
username = "replay_" + uuid.uuid4().hex[:10]
|
||||
password = "replay-pass-1234567890"
|
||||
code, user = call("POST", "/api/v1/users", body={
|
||||
"username": username, "display_name": "Replay", "password": password,
|
||||
})
|
||||
assert code == 201, f"register failed: {code} {user}"
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
code, session = call("POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + cred})
|
||||
assert code == 201, f"login failed: {code}"
|
||||
token = session["token"]
|
||||
code, chat = call("POST", "/api/v1/chats",
|
||||
headers={"Authorization": "Bearer " + token},
|
||||
body={"title": "Replay", "member_ids": [user["id"]]})
|
||||
assert code == 201, f"chat failed: {code}"
|
||||
chat_id = chat["id"]
|
||||
|
||||
# 2. Upload
|
||||
fixture = (Path(__file__).resolve().parent.parent / "tests/fixtures/sample.png").read_bytes()
|
||||
code, att = call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat_id}/attachments?filename=sample.png",
|
||||
headers={"Authorization": "Bearer " + token, "Content-Type": "image/png"},
|
||||
raw=fixture,
|
||||
)
|
||||
assert code == 202, f"upload failed: {code}"
|
||||
att_id = att["id"]
|
||||
print(f"upload: 202 queued ({att_id})")
|
||||
|
||||
# 3. Ждём ready
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
code, att = call("GET", f"/api/v1/attachments/{att_id}",
|
||||
headers={"Authorization": "Bearer " + token})
|
||||
if code == 200 and att["status"] == "ready":
|
||||
break
|
||||
if code == 200 and att["status"] == "failed":
|
||||
raise AssertionError(f"failed: {att.get('error_code')}")
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
raise AssertionError("not ready in 60s")
|
||||
|
||||
variants_before = att["variants"]
|
||||
print(f"ready: {len(variants_before)} variants")
|
||||
|
||||
# 4. Повторная доставка: publish тот же job в broker
|
||||
import subprocess
|
||||
# job_id из БД
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", "exec", "-T", "postgres",
|
||||
"psql", "-U", "messenger", "-d", "messenger", "-t", "-A",
|
||||
"-c", f"SELECT job_id FROM jobs WHERE attachment_id = '{att_id}' LIMIT 1"],
|
||||
capture_output=True, text=True, cwd="/home/user/projects/lab5/mtusi2026lab5",
|
||||
)
|
||||
job_id = result.stdout.strip()
|
||||
assert job_id, f"job_id not found: {result.stderr}"
|
||||
print(f"job_id: {job_id}")
|
||||
|
||||
# Опубликовать тот же job через worker (pika)
|
||||
pub_result = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", "exec", "-T", "worker",
|
||||
"python3", "-c", f"""
|
||||
import os, json, pika
|
||||
params = pika.URLParameters(os.environ['BROKER_URL'])
|
||||
conn = pika.BlockingConnection(params)
|
||||
ch = conn.channel()
|
||||
ch.basic_publish('', 'attachment.process.v1', json.dumps({{
|
||||
'schema_version': 1, 'job_id': '{job_id}', 'type': 'attachment.process.v1',
|
||||
'attachment_id': '{att_id}', 'pipeline_version': 1, 'attempt': 1,
|
||||
'created_at': '2026-01-01T00:00:00Z'
|
||||
}}))
|
||||
conn.close()
|
||||
print('published')
|
||||
"""],
|
||||
capture_output=True, text=True, cwd="/home/user/projects/lab5/mtusi2026lab5",
|
||||
)
|
||||
print(f"replay publish: {pub_result.stdout.strip() or pub_result.stderr.strip()}")
|
||||
|
||||
# 5. Ждём 10 сек, проверяем variants
|
||||
time.sleep(10)
|
||||
code, att_after = call("GET", f"/api/v1/attachments/{att_id}",
|
||||
headers={"Authorization": "Bearer " + token})
|
||||
assert code == 200, f"get after failed: {code}"
|
||||
variants_after = att_after["variants"]
|
||||
assert variants_after == variants_before, \
|
||||
f"variants changed: {len(variants_before)} -> {len(variants_after)}"
|
||||
print(f"after replay: {len(variants_after)} variants (unchanged)")
|
||||
|
||||
# 6. Проверяем S3 — количество объектов не изменилось (root, mc ls)
|
||||
for prefix, ext in (("originals", "png"), ("thumbnails", "jpg"),
|
||||
("crops", "jpg"), ("optimized", "webp")):
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", "run", "--rm",
|
||||
"--entrypoint", "sh", "s3-init", "-c",
|
||||
f"mc alias set local http://s3:9000 $MINIO_ROOT_USER $MINIO_ROOT_PASSWORD >/dev/null && "
|
||||
f"mc stat local/messenger-attachments/{prefix}/{att_id}.{ext} 2>&1 | head -1"],
|
||||
capture_output=True, text=True, cwd="/home/user/projects/lab5/mtusi2026lab5",
|
||||
)
|
||||
out = (result.stdout + result.stderr).strip()
|
||||
assert "Name" in out or "Size" in out, f"missing {prefix}: {out}"
|
||||
print(f" {prefix}/{att_id}.{ext} exists")
|
||||
|
||||
print("PASS: idempotent replay — variants unchanged, no duplicates")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from pathlib import Path
|
||||
main()
|
||||
@@ -0,0 +1,115 @@
|
||||
"""Параллельная идемпотентность: N потоков посылают один POST с одним ключом.
|
||||
|
||||
Ожидаем: ровно одно сообщение создано, все ответы — одинаковые,
|
||||
дубликатов в истории нет.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
BASE = sys.argv[sys.argv.index("--base-url") + 1] if "--base-url" in sys.argv else "http://localhost:8080"
|
||||
THREADS = 10
|
||||
|
||||
|
||||
def call(method, path, headers=None, body=None):
|
||||
data = None
|
||||
h = dict(headers or {})
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=15)
|
||||
raw = resp.read()
|
||||
return resp.status, json.loads(raw) if raw else None, dict(resp.headers)
|
||||
except urllib.error.HTTPError as e:
|
||||
raw = e.read()
|
||||
try:
|
||||
return e.code, json.loads(raw) if raw else None, dict(e.headers)
|
||||
except Exception:
|
||||
return e.code, None, dict(e.headers)
|
||||
|
||||
|
||||
def main():
|
||||
username = "pario_" + uuid.uuid4().hex[:10]
|
||||
password = "parallel-pass-1234567890"
|
||||
|
||||
# Регистрация
|
||||
code, user, _ = call("POST", "/api/v1/users", body={
|
||||
"username": username, "display_name": "Parallel", "password": password,
|
||||
})
|
||||
assert code == 201, f"register failed: {code} {user}"
|
||||
user_id = user["id"]
|
||||
|
||||
# Логин
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
code, session, _ = call("POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + cred})
|
||||
assert code == 201, f"login failed: {code}"
|
||||
token = session["token"]
|
||||
|
||||
# Чат
|
||||
code, chat, _ = call("POST", "/api/v1/chats",
|
||||
headers={"Authorization": "Bearer " + token},
|
||||
body={"title": "Parallel test", "member_ids": [user_id]})
|
||||
assert code == 201, f"chat failed: {code}"
|
||||
chat_id = chat["id"]
|
||||
|
||||
# Параллельный POST с одним ключом
|
||||
idem_key = "parallel-" + uuid.uuid4().hex
|
||||
barrier = threading.Barrier(THREADS)
|
||||
results = []
|
||||
results_lock = threading.Lock()
|
||||
|
||||
def worker(i):
|
||||
barrier.wait() # стартуют одновременно
|
||||
code, body, headers = call(
|
||||
"POST", f"/api/v1/chats/{chat_id}/messages",
|
||||
headers={
|
||||
"Authorization": "Bearer " + token,
|
||||
"Idempotency-Key": idem_key,
|
||||
},
|
||||
body={"text": "parallel-message-same"}, # ← ОДИНАКОВЫЙ текст!
|
||||
)
|
||||
with results_lock:
|
||||
results.append((code, body))
|
||||
|
||||
with ThreadPoolExecutor(max_workers=THREADS) as pool:
|
||||
list(pool.map(worker, range(THREADS)))
|
||||
|
||||
# Анализ
|
||||
print(f"Results: {len(results)} responses")
|
||||
codes = {}
|
||||
for code, _ in results:
|
||||
codes[code] = codes.get(code, 0) + 1
|
||||
print(f"Status codes: {codes}")
|
||||
|
||||
# Проверка: ровно одно сообщение создано
|
||||
code, page, _ = call("GET", f"/api/v1/chats/{chat_id}/messages?limit=100",
|
||||
headers={"Authorization": "Bearer " + token})
|
||||
assert code == 200, f"history failed: {code}"
|
||||
messages = page["items"]
|
||||
print(f"Messages in history: {len(messages)}")
|
||||
|
||||
assert len(messages) == 1, f"expected exactly 1 message, got {len(messages)}"
|
||||
print("PASS: parallel idempotency — exactly one message created")
|
||||
|
||||
# Проверка: все ответы должны быть одинаковыми
|
||||
codes = [c for c, _ in results]
|
||||
bodies = [json.dumps(b, sort_keys=True) for _, b in results if b is not None]
|
||||
unique_bodies = set(bodies)
|
||||
print(f"Status codes: {dict((c, codes.count(c)) for c in set(codes))}")
|
||||
print(f"Unique response bodies: {len(unique_bodies)}")
|
||||
assert codes.count(201) == THREADS, f"expected all {THREADS} to be 201, got {codes.count(201)}"
|
||||
assert len(unique_bodies) == 1, f"expected same response body, got {len(unique_bodies)}"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Тест гонки регистрации: два параллельных POST /users с одним username.
|
||||
|
||||
Ожидаем: один 201, второй 409, в БД ровно один пользователь.
|
||||
Гонка гарантируется через threading.Barrier — оба запроса стартуют одновременно.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
BASE = sys.argv[sys.argv.index("--base-url") + 1] if "--base-url" in sys.argv else "http://localhost:8080"
|
||||
|
||||
|
||||
def post_user(username: str, display_name: str, password: str) -> int:
|
||||
"""Отправляет POST /users, возвращает HTTP-код."""
|
||||
body = json.dumps(
|
||||
{"username": username, "display_name": display_name, "password": password},
|
||||
ensure_ascii=False,
|
||||
).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
BASE + "/api/v1/users",
|
||||
data=body,
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=10)
|
||||
return resp.code
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code
|
||||
|
||||
|
||||
def main() -> None:
|
||||
username = "race_" + uuid.uuid4().hex[:12]
|
||||
password = "race-pass-1234567890"
|
||||
barrier = threading.Barrier(2)
|
||||
|
||||
def worker(display_name: str) -> int:
|
||||
barrier.wait() # старт одновременно
|
||||
return post_user(username, display_name, password)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
results = list(pool.map(worker, ["Первый", "Второй"]))
|
||||
|
||||
results.sort()
|
||||
print(f"HTTP codes: {results}")
|
||||
|
||||
assert results == [201, 409], f"expected [201, 409], got {results}"
|
||||
print(f"PASS: race — one 201, one 409 for username={username}")
|
||||
|
||||
def test_chat_rollback() -> None:
|
||||
"""Попытка создать чат с несуществующим участником → 400, чат не создан."""
|
||||
import base64
|
||||
|
||||
# Создаём пользователя
|
||||
username = "rollback_" + uuid.uuid4().hex[:8]
|
||||
password = "rollback-pass-1234567890"
|
||||
code = post_user(username, "Rollback", password)
|
||||
assert code == 201, f"failed to create user: {code}"
|
||||
|
||||
# Логинимся
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
req = urllib.request.Request(
|
||||
BASE + "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + cred},
|
||||
method="POST",
|
||||
)
|
||||
resp = urllib.request.urlopen(req)
|
||||
session = json.loads(resp.read())
|
||||
token = session["token"]
|
||||
user_id = session["user"]["id"]
|
||||
|
||||
# Пытаемся создать чат с несуществующим UUID
|
||||
fake_user = "00000000-0000-4000-8000-000000000000"
|
||||
body = json.dumps(
|
||||
{"title": "Bad chat", "member_ids": [user_id, fake_user]},
|
||||
ensure_ascii=False,
|
||||
).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
BASE + "/api/v1/chats",
|
||||
data=body,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": "Bearer " + token,
|
||||
},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
urllib.request.urlopen(req, timeout=10)
|
||||
code = 200
|
||||
except urllib.error.HTTPError as e:
|
||||
code = e.code
|
||||
|
||||
assert code == 400, f"expected 400 for unknown member, got {code}"
|
||||
|
||||
# Проверяем, что чат не создан — list chats не должен его содержать
|
||||
req = urllib.request.Request(
|
||||
BASE + "/api/v1/chats?limit=100",
|
||||
headers={"Authorization": "Bearer " + token},
|
||||
)
|
||||
resp = urllib.request.urlopen(req)
|
||||
page = json.loads(resp.read())
|
||||
titles = [c["title"] for c in page["items"]]
|
||||
assert "Bad chat" not in titles, f"chat was created despite failure: {titles}"
|
||||
|
||||
print("PASS: rollback — chat not created when member is unknown")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
test_chat_rollback()
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Проверка crop 128×128 и optimized WebP 1280×1280 (lab5 grade 4).
|
||||
|
||||
Запуск:
|
||||
python3 student_tests/test_variants.py --base-url http://localhost:8080
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
BASE = (
|
||||
sys.argv[sys.argv.index("--base-url") + 1]
|
||||
if "--base-url" in sys.argv
|
||||
else "http://localhost:8080"
|
||||
)
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def call(method, path, headers=None, body=None, raw=None, timeout=30):
|
||||
data = None
|
||||
h = dict(headers or {})
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
h["Content-Type"] = "application/json"
|
||||
elif raw is not None:
|
||||
data = raw
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=timeout)
|
||||
payload = resp.read()
|
||||
return resp.status, payload, dict(resp.headers)
|
||||
except urllib.error.HTTPError as e:
|
||||
payload = e.read()
|
||||
return e.code, payload, dict(e.headers)
|
||||
|
||||
|
||||
def jpeg_size(data: bytes) -> tuple[int, int]:
|
||||
assert data[:2] == b"\xff\xd8", "not a JPEG"
|
||||
i = 2
|
||||
sof = {0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf}
|
||||
while i < len(data):
|
||||
while i < len(data) and data[i] == 0xff:
|
||||
i += 1
|
||||
marker = data[i]
|
||||
i += 1
|
||||
if marker in {0xd9, 0xda}:
|
||||
break
|
||||
if marker in {0x01, 0xd8} or 0xd0 <= marker <= 0xd7:
|
||||
continue
|
||||
length = int.from_bytes(data[i:i+2], "big")
|
||||
if marker in sof:
|
||||
return (int.from_bytes(data[i+5:i+7], "big"),
|
||||
int.from_bytes(data[i+3:i+5], "big"))
|
||||
i += length
|
||||
raise AssertionError("JPEG SOF not found")
|
||||
|
||||
|
||||
def webp_size(data: bytes) -> tuple[int, int]:
|
||||
assert data[:4] == b"RIFF" and data[8:12] == b"WEBP", "not a WebP"
|
||||
# VP8L (lossless) или VP8 (lossy)
|
||||
chunk = data[12:16]
|
||||
if chunk == b"VP8 ":
|
||||
i = data.index(b"\x9d\x01\x2a", 20)
|
||||
w = int.from_bytes(data[i+3:i+5], "little") & 0x3fff
|
||||
h = int.from_bytes(data[i+5:i+7], "little") & 0x3fff
|
||||
return w, h
|
||||
if chunk == b"VP8L":
|
||||
b = data[21:25]
|
||||
bits = int.from_bytes(b, "little")
|
||||
w = (bits & 0x3FFF) + 1
|
||||
h = ((bits >> 14) & 0x3FFF) + 1
|
||||
return w, h
|
||||
raise AssertionError("unknown WebP chunk")
|
||||
|
||||
|
||||
def main():
|
||||
username = "variants_" + uuid.uuid4().hex[:10]
|
||||
password = "variants-pass-1234567890"
|
||||
code, _, _ = call("POST", "/api/v1/users", body={
|
||||
"username": username, "display_name": "Variants", "password": password,
|
||||
})
|
||||
assert code == 201, f"register failed: {code}"
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
code, payload, _ = call("POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + cred})
|
||||
assert code == 201, f"login failed: {code}"
|
||||
session = json.loads(payload)
|
||||
token = session["token"]
|
||||
user_id = session["user"]["id"]
|
||||
|
||||
code, payload, _ = call("POST", "/api/v1/chats",
|
||||
headers={"Authorization": "Bearer " + token},
|
||||
body={"title": "Variants", "member_ids": [user_id]})
|
||||
assert code == 201, f"chat failed: {code}"
|
||||
chat_id = json.loads(payload)["id"]
|
||||
|
||||
fixture = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
code, payload, _ = call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat_id}/attachments?filename=sample.png",
|
||||
headers={"Authorization": "Bearer " + token, "Content-Type": "image/png"},
|
||||
raw=fixture,
|
||||
)
|
||||
assert code == 202, f"upload failed: {code}"
|
||||
att_id = json.loads(payload)["id"]
|
||||
print(f"upload: 202 queued ({att_id})")
|
||||
|
||||
# Ждём ready
|
||||
deadline = time.monotonic() + 60
|
||||
att = None
|
||||
while time.monotonic() < deadline:
|
||||
code, payload, _ = call("GET", f"/api/v1/attachments/{att_id}",
|
||||
headers={"Authorization": "Bearer " + token})
|
||||
if code == 200:
|
||||
att = json.loads(payload)
|
||||
if att["status"] == "ready":
|
||||
break
|
||||
time.sleep(0.5)
|
||||
assert att and att["status"] == "ready", f"not ready: {att}"
|
||||
|
||||
variants = {v["name"]: v for v in att["variants"]}
|
||||
print(f"variants: {list(variants.keys())}")
|
||||
|
||||
# --- thumbnail ---
|
||||
assert "thumbnail" in variants, "missing thumbnail"
|
||||
code, thumb_bytes, headers = call(
|
||||
"GET", f"/api/v1/attachments/{att_id}/content?variant=thumbnail",
|
||||
headers={"Authorization": "Bearer " + token},
|
||||
)
|
||||
assert code == 200, f"thumbnail download: {code}"
|
||||
assert headers.get("content-type", "").startswith("image/jpeg")
|
||||
w, h = jpeg_size(thumb_bytes)
|
||||
assert (w, h) == (256, 160), f"thumbnail {w}x{h}, expected 256x160"
|
||||
print(f"PASS: thumbnail 256x160 ({len(thumb_bytes)} bytes)")
|
||||
|
||||
# --- crop ---
|
||||
assert "crop" in variants, "missing crop"
|
||||
code, crop_bytes, headers = call(
|
||||
"GET", f"/api/v1/attachments/{att_id}/content?variant=crop",
|
||||
headers={"Authorization": "Bearer " + token},
|
||||
)
|
||||
assert code == 200, f"crop download: {code}"
|
||||
assert headers.get("content-type", "").startswith("image/jpeg")
|
||||
w, h = jpeg_size(crop_bytes)
|
||||
assert (w, h) == (128, 128), f"crop {w}x{h}, expected 128x128"
|
||||
print(f"PASS: crop 128x128 ({len(crop_bytes)} bytes)")
|
||||
|
||||
# --- optimized ---
|
||||
assert "optimized" in variants, "missing optimized"
|
||||
code, opt_bytes, headers = call(
|
||||
"GET", f"/api/v1/attachments/{att_id}/content?variant=optimized",
|
||||
headers={"Authorization": "Bearer " + token},
|
||||
)
|
||||
assert code == 200, f"optimized download: {code}"
|
||||
assert headers.get("content-type", "").startswith("image/webp")
|
||||
w, h = webp_size(opt_bytes)
|
||||
# fixture 320x200 → вписан в 1280×1280 без увеличения → 320×200
|
||||
assert (w, h) == (320, 200), f"optimized {w}x{h}, expected 320x200 (no upscale)"
|
||||
print(f"PASS: optimized WebP {w}x{h} ({len(opt_bytes)} bytes)")
|
||||
|
||||
print("\nPASS: all variants — thumbnail, crop, optimized")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Демонстрация: worker остановлен → 202 queued → worker запущен → ready.
|
||||
|
||||
Требует docker compose. Запуск:
|
||||
python3 student_tests/test_worker_lifecycle.py --base-url http://localhost:8080
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
BASE = (
|
||||
sys.argv[sys.argv.index("--base-url") + 1]
|
||||
if "--base-url" in sys.argv
|
||||
else "http://localhost:8080"
|
||||
)
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def call(method, path, headers=None, body=None, raw=None):
|
||||
data = None
|
||||
h = dict(headers or {})
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
h["Content-Type"] = "application/json"
|
||||
elif raw is not None:
|
||||
data = raw
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=30)
|
||||
payload = resp.read()
|
||||
return resp.status, json.loads(payload) if payload else None, dict(resp.headers)
|
||||
except urllib.error.HTTPError as e:
|
||||
payload = e.read()
|
||||
try:
|
||||
return e.code, json.loads(payload) if payload else None, dict(e.headers)
|
||||
except Exception:
|
||||
return e.code, None, dict(e.headers)
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
return subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
check=check, capture_output=True, text=True, cwd=str(ROOT),
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
# 1. Регистрация, логин, чат
|
||||
username = "lifecycle_" + uuid.uuid4().hex[:10]
|
||||
password = "lifecycle-pass-1234567890"
|
||||
code, user, _ = call("POST", "/api/v1/users", body={
|
||||
"username": username, "display_name": "Lifecycle", "password": password,
|
||||
})
|
||||
assert code == 201, f"register failed: {code} {user}"
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
code, session, _ = call("POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + cred})
|
||||
assert code == 201, f"login failed: {code}"
|
||||
token = session["token"]
|
||||
code, chat, _ = call("POST", "/api/v1/chats",
|
||||
headers={"Authorization": "Bearer " + token},
|
||||
body={"title": "Lifecycle", "member_ids": [user["id"]]})
|
||||
assert code == 201, f"chat failed: {code}"
|
||||
chat_id = chat["id"]
|
||||
|
||||
# 2. Остановить worker
|
||||
compose("stop", "worker")
|
||||
print("worker stopped")
|
||||
|
||||
try:
|
||||
# 3. Upload — 202 queued
|
||||
fixture = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
code, att, _ = call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat_id}/attachments?filename=sample.png",
|
||||
headers={"Authorization": "Bearer " + token, "Content-Type": "image/png"},
|
||||
raw=fixture,
|
||||
)
|
||||
assert code == 202, f"upload expected 202, got {code}"
|
||||
assert att["status"] == "queued", f"expected queued, got {att['status']}"
|
||||
att_id = att["id"]
|
||||
print(f"upload: 202 queued ({att_id})")
|
||||
|
||||
# 4. Через 3 секунды — всё ещё queued
|
||||
time.sleep(3)
|
||||
code, att, _ = call("GET", f"/api/v1/attachments/{att_id}",
|
||||
headers={"Authorization": "Bearer " + token})
|
||||
assert code == 200, f"get failed: {code}"
|
||||
assert att["status"] == "queued", f"expected queued, got {att['status']}"
|
||||
print(f"after 3s: still queued")
|
||||
|
||||
# 5. Запустить worker
|
||||
try:
|
||||
compose("up", "-d", "--no-deps", "worker")
|
||||
except subprocess.CalledProcessError as exc:
|
||||
print(f"START FAILED: {exc.stderr}", file=sys.stderr)
|
||||
raise
|
||||
|
||||
# 6. Ждём ready (до 60 сек)
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
code, att, _ = call("GET", f"/api/v1/attachments/{att_id}",
|
||||
headers={"Authorization": "Bearer " + token})
|
||||
if code == 200 and att["status"] == "ready":
|
||||
break
|
||||
if code == 200 and att["status"] == "failed":
|
||||
raise AssertionError(f"attachment failed: {att['error_code']}")
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
raise AssertionError("attachment did not become ready in 60s")
|
||||
|
||||
# 7. Проверяем variants
|
||||
variants = [v for v in att["variants"] if v["name"] == "thumbnail"]
|
||||
assert len(variants) == 1, f"expected 1 thumbnail, got {len(variants)}"
|
||||
v = variants[0]
|
||||
assert (v["width"], v["height"]) == (256, 160), \
|
||||
f"thumbnail dimensions wrong: {v['width']}x{v['height']}"
|
||||
print(f"after worker start: ready, thumbnail {v['width']}x{v['height']}")
|
||||
|
||||
# 8. Скачиваем thumbnail (бинарный ответ)
|
||||
req = urllib.request.Request(
|
||||
BASE + f"/api/v1/attachments/{att_id}/content?variant=thumbnail",
|
||||
headers={"Authorization": "Bearer " + token},
|
||||
)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=30)
|
||||
except urllib.error.HTTPError as e:
|
||||
raise AssertionError(f"thumbnail download failed: {e.code}")
|
||||
thumb_bytes = resp.read()
|
||||
assert thumb_bytes[:2] == b"\xff\xd8", "not a JPEG"
|
||||
print(f"thumbnail downloaded: {len(thumb_bytes)} bytes, JPEG")
|
||||
finally:
|
||||
# 9. Гарантированно вернуть worker
|
||||
compose("up", "-d", "--no-deps", "worker", check=False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user