forked from mtusi2026/mtusi2026lab2
Мессенджер с Postgres, Redis, Valkey
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import httpx
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
|
||||
|
||||
def register(client: httpx.Client) -> dict:
|
||||
username = "u_" + uuid.uuid4().hex[:10]
|
||||
return client.post(
|
||||
f"{BASE}/api/v1/users",
|
||||
json={"username": username, "display_name": "Bench"},
|
||||
).json()
|
||||
|
||||
|
||||
def setup(history_size: int):
|
||||
with httpx.Client(timeout=120) as c:
|
||||
alice = register(c)
|
||||
bob = register(c)
|
||||
chat = c.post(
|
||||
f"{BASE}/api/v1/chats",
|
||||
json={"title": "bench", "member_ids": [alice["id"], bob["id"]]},
|
||||
headers={"X-User-Id": alice["id"]},
|
||||
).json()
|
||||
for i in range(history_size):
|
||||
c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": f"seed-{i}"},
|
||||
headers={"X-User-Id": alice["id"]},
|
||||
)
|
||||
return alice, bob, chat
|
||||
|
||||
|
||||
def measure(chat_id: str, actor_id: str, concurrency: int, duration: float = 5.0):
|
||||
latencies = []
|
||||
errors = 0
|
||||
lock = __import__("threading").Lock()
|
||||
|
||||
def worker(worker_id):
|
||||
nonlocal errors
|
||||
local_lat = []
|
||||
local_err = 0
|
||||
with httpx.Client(timeout=10) as c:
|
||||
deadline = time.monotonic() + duration
|
||||
i = 0
|
||||
while time.monotonic() < deadline:
|
||||
t0 = time.monotonic()
|
||||
try:
|
||||
if i % 10 == 0:
|
||||
r = c.get(
|
||||
f"{BASE}/api/v1/chats/{chat_id}/messages?limit=50",
|
||||
headers={"X-User-Id": actor_id},
|
||||
)
|
||||
else:
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat_id}/messages",
|
||||
json={"text": "load"},
|
||||
headers={"X-User-Id": actor_id},
|
||||
)
|
||||
if r.status_code not in (200, 201):
|
||||
local_err += 1
|
||||
else:
|
||||
local_lat.append(time.monotonic() - t0)
|
||||
except Exception:
|
||||
local_err += 1
|
||||
i += 1
|
||||
with lock:
|
||||
latencies.extend(local_lat)
|
||||
errors += local_err
|
||||
|
||||
t_start = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
list(pool.map(lambda w: worker(w), range(concurrency)))
|
||||
elapsed = time.monotonic() - t_start
|
||||
|
||||
latencies.sort()
|
||||
|
||||
def pct(p):
|
||||
if not latencies:
|
||||
return None
|
||||
idx = max(0, int(len(latencies) * p) - 1)
|
||||
return round(latencies[idx] * 1000, 3)
|
||||
|
||||
rps = len(latencies) / elapsed if elapsed else 0
|
||||
return {
|
||||
"concurrency": concurrency,
|
||||
"elapsed_s": round(elapsed, 2),
|
||||
"success": len(latencies),
|
||||
"errors": errors,
|
||||
"rps": round(rps, 2),
|
||||
"p50_ms": pct(0.50),
|
||||
"p95_ms": pct(0.95),
|
||||
"p99_ms": pct(0.99),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
results = []
|
||||
for history in (100, 1000, 10000):
|
||||
print(f"Setup history={history}...")
|
||||
alice, _, chat = setup(history)
|
||||
for conc in (1, 10, 50):
|
||||
print(f" measure history={history} concurrency={conc}...")
|
||||
m = measure(chat["id"], alice["id"], conc, duration=5.0)
|
||||
m["history_size"] = history
|
||||
results.append(m)
|
||||
print(" ", json.dumps(m, ensure_ascii=False))
|
||||
|
||||
with open("benchmark_results.json", "w", encoding="utf-8") as f:
|
||||
json.dump(results, f, ensure_ascii=False, indent=2)
|
||||
print("Saved to benchmark_results.json")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Cache stampede experiment.
|
||||
|
||||
Measures SQL calls and latency for parallel GET /messages with cold cache.
|
||||
Run twice: before and after single-flight protection.
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
EVIDENCE = Path(__file__).resolve().parent.parent / "evidence" / "cache_experiment.json"
|
||||
|
||||
|
||||
def register_and_login(client: httpx.Client) -> dict:
|
||||
username = "cache_" + uuid.uuid4().hex[:10]
|
||||
password = "Test-password-1234"
|
||||
r = client.post(
|
||||
f"{BASE}/api/v1/users",
|
||||
json={
|
||||
"username": username,
|
||||
"display_name": "Cache",
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
user = r.json()
|
||||
credential = base64.b64encode(
|
||||
(username + ":" + password).encode("utf-8")
|
||||
).decode("ascii")
|
||||
r = client.post(
|
||||
f"{BASE}/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + credential},
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
return {"id": user["id"], "token": r.json()["token"]}
|
||||
|
||||
|
||||
def auth(actor: dict) -> dict:
|
||||
return {"Authorization": "Bearer " + actor["token"]}
|
||||
|
||||
|
||||
def sql_calls_for_query(substring: str) -> int:
|
||||
"""Count SQL calls from pg_stat_statements matching substring."""
|
||||
sql = (
|
||||
"SELECT COALESCE(SUM(calls), 0) FROM pg_stat_statements "
|
||||
f"WHERE query ILIKE '%{substring}%';"
|
||||
)
|
||||
result = subprocess.run(
|
||||
[
|
||||
"docker", "compose", "exec", "-T", "postgres",
|
||||
"psql", "-U", "messenger", "-d", "messenger",
|
||||
"-t", "-A", "-c", sql,
|
||||
],
|
||||
capture_output=True, text=True, check=True,
|
||||
)
|
||||
return int(result.stdout.strip() or "0")
|
||||
|
||||
|
||||
def reset_pg_stats() -> None:
|
||||
subprocess.run(
|
||||
[
|
||||
"docker", "compose", "exec", "-T", "postgres",
|
||||
"psql", "-U", "messenger", "-d", "messenger",
|
||||
"-c", "SELECT pg_stat_statements_reset();",
|
||||
],
|
||||
capture_output=True, text=True, check=True,
|
||||
)
|
||||
|
||||
|
||||
def flush_cache() -> None:
|
||||
subprocess.run(
|
||||
[
|
||||
"docker", "compose", "exec", "-T", "valkey",
|
||||
"sh", "-c",
|
||||
"valkey-cli --scan --pattern 'messages:*' | xargs -r valkey-cli DEL",
|
||||
],
|
||||
capture_output=True, text=True, check=True,
|
||||
)
|
||||
|
||||
def run_parallel_gets(chat_id: str, token: str, concurrency: int = 50):
|
||||
"""Fire N parallel GET requests; return list of latencies and statuses."""
|
||||
results = []
|
||||
|
||||
def worker():
|
||||
with httpx.Client(timeout=15) as c:
|
||||
t0 = time.monotonic()
|
||||
r = c.get(
|
||||
f"{BASE}/api/v1/chats/{chat_id}/messages?limit=50",
|
||||
headers={"Authorization": "Bearer " + token},
|
||||
)
|
||||
dt = time.monotonic() - t0
|
||||
return dt, r.status_code
|
||||
|
||||
with ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
results = list(pool.map(lambda _: worker(), range(concurrency)))
|
||||
return results
|
||||
|
||||
|
||||
def main():
|
||||
label = os.getenv("LABEL", "before")
|
||||
concurrency = int(os.getenv("CONCURRENCY", "50"))
|
||||
|
||||
with httpx.Client(timeout=30) as c:
|
||||
alice = register_and_login(c)
|
||||
bob = register_and_login(c)
|
||||
chat = c.post(
|
||||
f"{BASE}/api/v1/chats",
|
||||
json={"title": "cache", "member_ids": [alice["id"], bob["id"]]},
|
||||
headers=auth(alice),
|
||||
).json()
|
||||
for i in range(100):
|
||||
c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": f"seed-{i:03d}"},
|
||||
headers=auth(alice),
|
||||
)
|
||||
|
||||
flush_cache()
|
||||
reset_pg_stats()
|
||||
time.sleep(0.5)
|
||||
|
||||
print(f"Running {concurrency} parallel GETs (label={label})...")
|
||||
started = time.monotonic()
|
||||
results = run_parallel_gets(chat["id"], alice["token"], concurrency)
|
||||
elapsed = time.monotonic() - started
|
||||
|
||||
latencies = sorted(dt for dt, _ in results)
|
||||
statuses = [s for _, s in results]
|
||||
ok_count = sum(1 for s in statuses if s == 200)
|
||||
errors = concurrency - ok_count
|
||||
|
||||
sql_calls = sql_calls_for_query("FROM messages")
|
||||
|
||||
def pct(p):
|
||||
idx = max(0, int(len(latencies) * p) - 1)
|
||||
return round(latencies[idx] * 1000, 2)
|
||||
|
||||
report = {
|
||||
"label": label,
|
||||
"concurrency": concurrency,
|
||||
"elapsed_s": round(elapsed, 3),
|
||||
"ok": ok_count,
|
||||
"errors": errors,
|
||||
"latency_ms": {
|
||||
"p50": pct(0.5),
|
||||
"p95": pct(0.95),
|
||||
"p99": pct(0.99),
|
||||
},
|
||||
"sql_calls_from_messages": sql_calls,
|
||||
}
|
||||
print(json.dumps(report, indent=2, ensure_ascii=False))
|
||||
|
||||
existing = []
|
||||
if EVIDENCE.exists():
|
||||
try:
|
||||
existing = json.loads(EVIDENCE.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
existing = []
|
||||
existing.append(report)
|
||||
EVIDENCE.parent.mkdir(parents=True, exist_ok=True)
|
||||
EVIDENCE.write_text(
|
||||
json.dumps(existing, indent=2, ensure_ascii=False),
|
||||
encoding="utf-8",
|
||||
)
|
||||
print(f"Saved to {EVIDENCE}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Populate a chat with 10000 messages and run EXPLAIN (ANALYZE, BUFFERS).
|
||||
|
||||
Saves the plan to evidence/explain.txt for the report.
|
||||
"""
|
||||
import base64
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
EVIDENCE = Path(__file__).resolve().parent.parent / "evidence" / "explain.txt"
|
||||
|
||||
|
||||
def register_and_login(client: httpx.Client) -> dict:
|
||||
username = "explain_" + uuid.uuid4().hex[:10]
|
||||
password = "Test-password-1234"
|
||||
r = client.post(
|
||||
f"{BASE}/api/v1/users",
|
||||
json={
|
||||
"username": username,
|
||||
"display_name": "Explain",
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
user = r.json()
|
||||
|
||||
credential = base64.b64encode(
|
||||
(username + ":" + password).encode("utf-8")
|
||||
).decode("ascii")
|
||||
r = client.post(
|
||||
f"{BASE}/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + credential},
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
session = r.json()
|
||||
return {"id": user["id"], "token": session["token"]}
|
||||
|
||||
|
||||
def auth(actor: dict) -> dict:
|
||||
return {"Authorization": "Bearer " + actor["token"]}
|
||||
|
||||
|
||||
def main():
|
||||
total = 10000
|
||||
print(f"Setting up {total} messages...")
|
||||
|
||||
with httpx.Client(timeout=120) as c:
|
||||
alice = register_and_login(c)
|
||||
bob = register_and_login(c)
|
||||
chat = c.post(
|
||||
f"{BASE}/api/v1/chats",
|
||||
json={"title": "explain", "member_ids": [alice["id"], bob["id"]]},
|
||||
headers=auth(alice),
|
||||
).json()
|
||||
|
||||
print(f"chat_id = {chat['id']}")
|
||||
|
||||
batch = 200
|
||||
started = time.monotonic()
|
||||
for i in range(0, total, batch):
|
||||
for j in range(batch):
|
||||
c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": f"msg-{i+j:05d}"},
|
||||
headers=auth(alice),
|
||||
)
|
||||
if (i + batch) % 2000 == 0:
|
||||
elapsed = time.monotonic() - started
|
||||
print(f" {i+batch}/{total} messages, {elapsed:.1f}s")
|
||||
|
||||
print(f"Setup done in {time.monotonic() - started:.1f}s")
|
||||
print(f"chat_id: {chat['id']}")
|
||||
|
||||
print("Run in psql:")
|
||||
print(f"""
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '{chat['id']}'
|
||||
AND (created_at, id) > ('2026-01-01T00:00:00Z'::timestamptz, '00000000-0000-0000-0000-000000000000'::uuid)
|
||||
ORDER BY created_at, id
|
||||
LIMIT 51;
|
||||
""")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,133 @@
|
||||
"""Cache consistency tests for Трек 1.
|
||||
|
||||
- read-after-write: after POST, GET sees the new message.
|
||||
- cache recovers after Redis restart.
|
||||
"""
|
||||
import base64
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
||||
|
||||
|
||||
def _register_and_login(client: httpx.Client) -> dict:
|
||||
username = "cch_" + uuid.uuid4().hex[:10]
|
||||
password = "Test-password-1234"
|
||||
r = client.post(
|
||||
f"{BASE}/api/v1/users",
|
||||
json={
|
||||
"username": username,
|
||||
"display_name": "Cache Test",
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
user = r.json()
|
||||
credential = base64.b64encode(
|
||||
(username + ":" + password).encode("utf-8")
|
||||
).decode("ascii")
|
||||
r = client.post(
|
||||
f"{BASE}/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + credential},
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
return {"id": user["id"], "token": r.json()["token"]}
|
||||
|
||||
|
||||
def _auth(actor: dict) -> dict:
|
||||
return {"Authorization": "Bearer " + actor["token"]}
|
||||
|
||||
|
||||
def test_read_after_write_sees_new_message():
|
||||
with httpx.Client() as c:
|
||||
alice = _register_and_login(c)
|
||||
bob = _register_and_login(c)
|
||||
chat = c.post(
|
||||
f"{BASE}/api/v1/chats",
|
||||
json={"title": "raw", "member_ids": [alice["id"], bob["id"]]},
|
||||
headers=_auth(alice),
|
||||
).json()
|
||||
|
||||
# Первый GET наполняет кэш
|
||||
r = c.get(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages?limit=50",
|
||||
headers=_auth(alice),
|
||||
)
|
||||
assert r.status_code == 200
|
||||
before = r.json()["items"]
|
||||
assert len(before) == 0
|
||||
|
||||
# POST нового сообщения
|
||||
text = "read-after-write-" + uuid.uuid4().hex[:8]
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=_auth(alice),
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
|
||||
# Второй GET — должен увидеть новое сообщение (не старый кэш)
|
||||
r = c.get(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages?limit=50",
|
||||
headers=_auth(alice),
|
||||
)
|
||||
assert r.status_code == 200
|
||||
after = r.json()["items"]
|
||||
texts = [m["text"] for m in after]
|
||||
assert text in texts, f"read-after-write failed: {texts}"
|
||||
|
||||
|
||||
def test_cache_recovers_after_valkey_restart():
|
||||
with httpx.Client() as c:
|
||||
alice = _register_and_login(c)
|
||||
bob = _register_and_login(c)
|
||||
chat = c.post(
|
||||
f"{BASE}/api/v1/chats",
|
||||
json={"title": "restart", "member_ids": [alice["id"], bob["id"]]},
|
||||
headers=_auth(alice),
|
||||
).json()
|
||||
for i in range(5):
|
||||
c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": f"msg-{i}"},
|
||||
headers=_auth(alice),
|
||||
)
|
||||
|
||||
# Прогрев кэша
|
||||
r = c.get(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages?limit=50",
|
||||
headers=_auth(alice),
|
||||
)
|
||||
assert r.status_code == 200
|
||||
before = r.json()["items"]
|
||||
assert len(before) == 5
|
||||
|
||||
# Перезапуск Valkey
|
||||
subprocess.run(COMPOSE + ["restart", "valkey"], check=True)
|
||||
time.sleep(3)
|
||||
|
||||
# Подождём восстановление
|
||||
for _ in range(30):
|
||||
try:
|
||||
with httpx.Client(timeout=2) as c:
|
||||
r = c.get(f"{BASE}/health/ready")
|
||||
if r.status_code == 200:
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
|
||||
# Снова читаем — тот же результат (из кэша или из БД)
|
||||
with httpx.Client() as c:
|
||||
r = c.get(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages?limit=50",
|
||||
headers=_auth(alice),
|
||||
)
|
||||
assert r.status_code == 200
|
||||
after = r.json()["items"]
|
||||
assert len(after) == 5
|
||||
assert [m["id"] for m in after] == [m["id"] for m in before]
|
||||
@@ -0,0 +1,73 @@
|
||||
import base64
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import httpx
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
|
||||
|
||||
def _register_and_login(client: httpx.Client) -> dict:
|
||||
username = "u_" + uuid.uuid4().hex[:10]
|
||||
password = "Test-password-" + uuid.uuid4().hex[:8]
|
||||
r = client.post(
|
||||
f"{BASE}/api/v1/users",
|
||||
json={
|
||||
"username": username,
|
||||
"display_name": "Тест",
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
user = r.json()
|
||||
credential = base64.b64encode(
|
||||
(username + ":" + password).encode("utf-8")
|
||||
).decode("ascii")
|
||||
r = client.post(
|
||||
f"{BASE}/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + credential},
|
||||
)
|
||||
session = r.json()
|
||||
return {"id": user["id"], "token": session["token"]}
|
||||
|
||||
|
||||
def test_concurrent_writes_are_not_lost():
|
||||
with httpx.Client() as c:
|
||||
alice = _register_and_login(c)
|
||||
bob = _register_and_login(c)
|
||||
chat = c.post(
|
||||
f"{BASE}/api/v1/chats",
|
||||
json={"title": "race", "member_ids": [alice["id"], bob["id"]]},
|
||||
headers={"Authorization": "Bearer " + alice["token"]},
|
||||
).json()
|
||||
|
||||
def worker(worker_id: int):
|
||||
with httpx.Client(timeout=10) as c:
|
||||
for i in range(10):
|
||||
c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": f"w{worker_id}-m{i}"},
|
||||
headers={"Authorization": "Bearer " + alice["token"]},
|
||||
)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
list(pool.map(worker, range(10)))
|
||||
|
||||
with httpx.Client() as c:
|
||||
all_ids = []
|
||||
cursor = None
|
||||
while True:
|
||||
params = {"limit": 100}
|
||||
if cursor:
|
||||
params["cursor"] = cursor
|
||||
r = c.get(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
||||
params=params,
|
||||
headers={"Authorization": "Bearer " + alice["token"]},
|
||||
)
|
||||
page = r.json()
|
||||
all_ids.extend(m["id"] for m in page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if not cursor:
|
||||
break
|
||||
|
||||
assert len(all_ids) == 100
|
||||
assert len(set(all_ids)) == 100
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Automatic resilience checks: expiry, Redis/DB unavailability.
|
||||
|
||||
Requires Docker: test stops the service, checks API behaviour, restarts it.
|
||||
Run: pytest student-tests/test_resilience.py -v -s
|
||||
"""
|
||||
import base64
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
||||
|
||||
|
||||
def _register_and_login(client: httpx.Client) -> dict:
|
||||
username = "res_" + uuid.uuid4().hex[:10]
|
||||
password = "Test-password-" + uuid.uuid4().hex[:8]
|
||||
r = client.post(
|
||||
f"{BASE}/api/v1/users",
|
||||
json={
|
||||
"username": username,
|
||||
"display_name": "Res",
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
user = r.json()
|
||||
|
||||
credential = base64.b64encode(
|
||||
(username + ":" + password).encode("utf-8")
|
||||
).decode("ascii")
|
||||
r = client.post(
|
||||
f"{BASE}/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + credential},
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
session = r.json()
|
||||
return {
|
||||
"id": user["id"],
|
||||
"username": username,
|
||||
"password": password,
|
||||
"token": session["token"],
|
||||
}
|
||||
|
||||
|
||||
def _wait_ready(timeout: float = 60.0) -> None:
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with httpx.Client(timeout=2) as c:
|
||||
r = c.get(f"{BASE}/health/ready")
|
||||
if r.status_code == 200:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise RuntimeError("API did not become ready in time")
|
||||
|
||||
|
||||
def _compose(*args: str) -> None:
|
||||
subprocess.run(COMPOSE + list(args), check=True)
|
||||
|
||||
|
||||
def test_expiry_invalidates_session(monkeypatch):
|
||||
"""Session expires when SESSION_TTL_SECONDS is very small."""
|
||||
_compose("up", "-d", "--build", "api")
|
||||
_wait_ready()
|
||||
|
||||
with httpx.Client(timeout=5) as c:
|
||||
actor = _register_and_login(c)
|
||||
r = c.get(
|
||||
f"{BASE}/api/v1/users/me",
|
||||
headers={"Authorization": "Bearer " + actor["token"]},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
|
||||
# Restart API with 2-second TTL
|
||||
_compose("stop", "api")
|
||||
subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", "rm", "-f", "api"],
|
||||
check=False,
|
||||
)
|
||||
subprocess.run(
|
||||
[
|
||||
"docker", "compose", "--env-file", ".env",
|
||||
"run", "-d", "--name", "api-short-ttl",
|
||||
"-e", "SESSION_TTL_SECONDS=2",
|
||||
"-p", "127.0.0.1:8080:8080",
|
||||
"api",
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
_wait_ready()
|
||||
|
||||
with httpx.Client(timeout=5) as c:
|
||||
fresh = _register_and_login(c)
|
||||
r = c.get(
|
||||
f"{BASE}/api/v1/users/me",
|
||||
headers={"Authorization": "Bearer " + fresh["token"]},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
print("Waiting 4 seconds for expiry...")
|
||||
time.sleep(4)
|
||||
r = c.get(
|
||||
f"{BASE}/api/v1/users/me",
|
||||
headers={"Authorization": "Bearer " + fresh["token"]},
|
||||
)
|
||||
assert r.status_code == 401, f"expected 401 after expiry, got {r.status_code}"
|
||||
|
||||
subprocess.run(["docker", "stop", "api-short-ttl"], check=False)
|
||||
subprocess.run(["docker", "rm", "api-short-ttl"], check=False)
|
||||
_compose("up", "-d", "--build", "api")
|
||||
_wait_ready()
|
||||
|
||||
|
||||
def test_redis_unavailable_returns_503():
|
||||
"""When Valkey is down, /health/ready returns 503."""
|
||||
_compose("up", "-d", "--build")
|
||||
_wait_ready()
|
||||
|
||||
_compose("stop", "valkey")
|
||||
time.sleep(3)
|
||||
|
||||
try:
|
||||
with httpx.Client(timeout=5) as c:
|
||||
r = c.get(f"{BASE}/health/ready")
|
||||
assert r.status_code == 503, f"expected 503, got {r.status_code}"
|
||||
body = r.json()
|
||||
assert body["error"]["code"] == "unavailable"
|
||||
finally:
|
||||
_compose("start", "valkey")
|
||||
_wait_ready()
|
||||
|
||||
|
||||
def test_postgres_unavailable_returns_503():
|
||||
"""When PostgreSQL is down, /health/ready returns 503."""
|
||||
_compose("up", "-d", "--build")
|
||||
_wait_ready()
|
||||
|
||||
_compose("stop", "postgres")
|
||||
time.sleep(3)
|
||||
|
||||
try:
|
||||
with httpx.Client(timeout=5) as c:
|
||||
r = c.get(f"{BASE}/health/ready")
|
||||
assert r.status_code == 503, f"expected 503, got {r.status_code}"
|
||||
body = r.json()
|
||||
assert body["error"]["code"] == "unavailable"
|
||||
finally:
|
||||
_compose("start", "postgres")
|
||||
_wait_ready()
|
||||
@@ -0,0 +1,264 @@
|
||||
import base64
|
||||
import uuid
|
||||
import httpx
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
|
||||
|
||||
def _register_and_login(client: httpx.Client) -> dict:
|
||||
username = "u_" + uuid.uuid4().hex[:10]
|
||||
password = "Test-password-" + uuid.uuid4().hex[:8]
|
||||
r = client.post(
|
||||
f"{BASE}/api/v1/users",
|
||||
json={
|
||||
"username": username,
|
||||
"display_name": "Тест",
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
user = r.json()
|
||||
|
||||
credential = base64.b64encode(
|
||||
(username + ":" + password).encode("utf-8")
|
||||
).decode("ascii")
|
||||
r = client.post(
|
||||
f"{BASE}/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + credential},
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
session = r.json()
|
||||
return {
|
||||
"id": user["id"],
|
||||
"username": username,
|
||||
"password": password,
|
||||
"token": session["token"],
|
||||
}
|
||||
|
||||
|
||||
def _auth(actor: dict) -> dict:
|
||||
return {"Authorization": "Bearer " + actor["token"]}
|
||||
|
||||
|
||||
def test_invalid_json_returns_400():
|
||||
with httpx.Client() as c:
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/users",
|
||||
content=b"{not json at all",
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
body = r.json()
|
||||
assert body["error"]["code"] == "invalid_request"
|
||||
assert "X-Request-Id" in r.headers
|
||||
|
||||
|
||||
def test_duplicate_username_returns_409():
|
||||
with httpx.Client() as c:
|
||||
actor = _register_and_login(c)
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/users",
|
||||
json={
|
||||
"username": actor["username"],
|
||||
"display_name": "Другой",
|
||||
"password": "Another-password-123",
|
||||
},
|
||||
)
|
||||
assert r.status_code == 409
|
||||
assert r.json()["error"]["code"] == "conflict"
|
||||
|
||||
|
||||
def test_empty_message_returns_400():
|
||||
with httpx.Client() as c:
|
||||
alice = _register_and_login(c)
|
||||
bob = _register_and_login(c)
|
||||
chat = c.post(
|
||||
f"{BASE}/api/v1/chats",
|
||||
json={"title": "t", "member_ids": [alice["id"], bob["id"]]},
|
||||
headers=_auth(alice),
|
||||
).json()
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": ""},
|
||||
headers=_auth(alice),
|
||||
)
|
||||
assert r.status_code == 400
|
||||
|
||||
|
||||
def test_outsider_gets_404_not_403():
|
||||
with httpx.Client() as c:
|
||||
alice = _register_and_login(c)
|
||||
bob = _register_and_login(c)
|
||||
eve = _register_and_login(c)
|
||||
chat = c.post(
|
||||
f"{BASE}/api/v1/chats",
|
||||
json={"title": "t", "member_ids": [alice["id"], bob["id"]]},
|
||||
headers=_auth(alice),
|
||||
).json()
|
||||
r = c.get(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}",
|
||||
headers=_auth(eve),
|
||||
)
|
||||
assert r.status_code == 404
|
||||
r2 = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "вторжение"},
|
||||
headers=_auth(eve),
|
||||
)
|
||||
assert r2.status_code == 404
|
||||
|
||||
|
||||
def test_pagination_walks_all_pages():
|
||||
with httpx.Client() as c:
|
||||
alice = _register_and_login(c)
|
||||
bob = _register_and_login(c)
|
||||
chat = c.post(
|
||||
f"{BASE}/api/v1/chats",
|
||||
json={"title": "t", "member_ids": [alice["id"], bob["id"]]},
|
||||
headers=_auth(alice),
|
||||
).json()
|
||||
sent_ids = []
|
||||
for i in range(5):
|
||||
m = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": f"msg-{i}"},
|
||||
headers=_auth(alice),
|
||||
).json()
|
||||
sent_ids.append(m["id"])
|
||||
|
||||
collected = []
|
||||
cursor = None
|
||||
while True:
|
||||
params = {"limit": 2}
|
||||
if cursor:
|
||||
params["cursor"] = cursor
|
||||
r = c.get(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
||||
params=params,
|
||||
headers=_auth(alice),
|
||||
)
|
||||
assert r.status_code == 200, r.text
|
||||
page = r.json()
|
||||
collected.extend(m["id"] for m in page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if not cursor:
|
||||
break
|
||||
assert collected == sent_ids
|
||||
|
||||
|
||||
def test_wrong_password_returns_401():
|
||||
with httpx.Client() as c:
|
||||
actor = _register_and_login(c)
|
||||
bad = base64.b64encode(
|
||||
(actor["username"] + ":wrong-password-1234").encode("utf-8")
|
||||
).decode("ascii")
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + bad},
|
||||
)
|
||||
assert r.status_code == 401
|
||||
assert "WWW-Authenticate" in r.headers
|
||||
assert r.headers["WWW-Authenticate"].lower().startswith("basic")
|
||||
|
||||
|
||||
def test_logout_invalidates_token():
|
||||
with httpx.Client() as c:
|
||||
actor = _register_and_login(c)
|
||||
r = c.delete(
|
||||
f"{BASE}/api/v1/auth/sessions/current",
|
||||
headers=_auth(actor),
|
||||
)
|
||||
assert r.status_code == 204
|
||||
r = c.get(f"{BASE}/api/v1/users/me", headers=_auth(actor))
|
||||
assert r.status_code == 401
|
||||
|
||||
|
||||
def test_x_user_id_ignored_with_bearer():
|
||||
with httpx.Client() as c:
|
||||
alice = _register_and_login(c)
|
||||
bob = _register_and_login(c)
|
||||
r = c.get(
|
||||
f"{BASE}/api/v1/users/me",
|
||||
headers={
|
||||
"Authorization": "Bearer " + alice["token"],
|
||||
"X-User-Id": bob["id"],
|
||||
},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
assert r.json()["id"] == alice["id"]
|
||||
|
||||
|
||||
def test_basic_on_business_endpoint_returns_401():
|
||||
with httpx.Client() as c:
|
||||
actor = _register_and_login(c)
|
||||
credential = base64.b64encode(
|
||||
(actor["username"] + ":" + actor["password"]).encode("utf-8")
|
||||
).decode("ascii")
|
||||
r = c.get(
|
||||
f"{BASE}/api/v1/users/me",
|
||||
headers={"Authorization": "Basic " + credential},
|
||||
)
|
||||
assert r.status_code == 401
|
||||
|
||||
def test_race_duplicate_username_only_one_wins():
|
||||
"""Гонка: два параллельных POST /users с одинаковым username.
|
||||
|
||||
Ожидание: один 201, второй 409. В БД ровно один пользователь.
|
||||
"""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
username = "race_" + uuid.uuid4().hex[:10]
|
||||
password = "Test-password-1234"
|
||||
|
||||
def register():
|
||||
with httpx.Client(timeout=10) as c:
|
||||
return c.post(
|
||||
f"{BASE}/api/v1/users",
|
||||
json={
|
||||
"username": username,
|
||||
"display_name": "Race",
|
||||
"password": password,
|
||||
},
|
||||
).status_code
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
statuses = list(pool.map(lambda _: register(), range(2)))
|
||||
|
||||
assert sorted(statuses) == [201, 409], f"got statuses {statuses}"
|
||||
|
||||
credential = base64.b64encode(
|
||||
(username + ":" + password).encode("utf-8")
|
||||
).decode("ascii")
|
||||
with httpx.Client() as c:
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + credential},
|
||||
)
|
||||
assert r.status_code == 201, "победитель должен уметь логиниться"
|
||||
assert r.json()["user"]["username"] == username
|
||||
|
||||
|
||||
def test_rollback_chat_with_unknown_member():
|
||||
"""Составная операция создания чата с несуществующим участником.
|
||||
|
||||
Ожидание: 400, чат не создан, в БД ничего не осталось.
|
||||
"""
|
||||
with httpx.Client() as c:
|
||||
alice = _register_and_login(c)
|
||||
fake_id = str(uuid.uuid4())
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats",
|
||||
json={
|
||||
"title": "Не должно создаться",
|
||||
"member_ids": [alice["id"], fake_id],
|
||||
},
|
||||
headers=_auth(alice),
|
||||
)
|
||||
assert r.status_code == 400, r.text
|
||||
|
||||
chats = c.get(
|
||||
f"{BASE}/api/v1/chats?limit=100",
|
||||
headers=_auth(alice),
|
||||
).json()
|
||||
titles = [ch["title"] for ch in chats["items"]]
|
||||
assert "Не должно создаться" not in titles, "чат создан несмотря на ошибку"
|
||||
Reference in New Issue
Block a user