forked from mtusi2026/mtusi2026lab5
Очереди и асинхронная обработка изображений, трек 1
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,186 @@
|
||||
import argparse
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from PIL import Image
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
||||
EVIDENCE = Path(__file__).resolve().parent.parent / "evidence"
|
||||
WORKER_CONTAINER = "mtusi2026lab5-worker-1"
|
||||
SIZES = {
|
||||
"small": (320, 200),
|
||||
"medium": (1280, 800),
|
||||
"large": (4000, 3000),
|
||||
}
|
||||
|
||||
|
||||
def _png(size):
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", size, (64, 128, 192)).save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _user(c):
|
||||
u = "qb_" + uuid.uuid4().hex[:10]
|
||||
p = "Test-password-1234"
|
||||
c.post(f"{BASE}/api/v1/users", json={"username": u, "display_name": "Q", "password": p})
|
||||
cred = base64.b64encode(f"{u}:{p}".encode()).decode()
|
||||
s = c.post(f"{BASE}/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred}).json()
|
||||
return {"id": s["user"]["id"], "token": s["token"]}
|
||||
|
||||
|
||||
def _auth(a):
|
||||
return {"Authorization": "Bearer " + a["token"]}
|
||||
|
||||
|
||||
def _worker_mem():
|
||||
out = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", WORKER_CONTAINER],
|
||||
capture_output=True, text=True,
|
||||
).stdout.strip()
|
||||
if not out or "/" not in out:
|
||||
return None
|
||||
v = out.split("/")[0].strip()
|
||||
units = {"B": 1, "KiB": 1024, "Ki": 1024, "MiB": 1024**2, "Mi": 1024**2,
|
||||
"GiB": 1024**3, "Gi": 1024**3}
|
||||
for u in sorted(units, key=len, reverse=True):
|
||||
if v.endswith(u):
|
||||
return round(int(float(v[: -len(u)]) * units[u]) / 1024**2, 1)
|
||||
return None
|
||||
|
||||
|
||||
def _restart_worker(prefetch):
|
||||
env = dict(os.environ)
|
||||
env["PREFETCH_COUNT"] = str(prefetch)
|
||||
subprocess.run(
|
||||
COMPOSE + ["up", "-d", "--force-recreate", "worker"],
|
||||
env=env, check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
)
|
||||
time.sleep(5)
|
||||
|
||||
|
||||
def _start_worker(prefetch):
|
||||
env = dict(os.environ)
|
||||
env["PREFETCH_COUNT"] = str(prefetch)
|
||||
subprocess.run(
|
||||
COMPOSE + ["up", "-d", "--force-recreate", "worker"],
|
||||
env=env, check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
)
|
||||
|
||||
|
||||
def _percentiles(values, ps=(0.5, 0.95, 0.99)):
|
||||
if not values:
|
||||
return {f"p{int(p*100)}": None for p in ps}
|
||||
s = sorted(values)
|
||||
return {f"p{int(p*100)}": round(s[max(0, int(len(s)*p)-1)], 3) for p in ps}
|
||||
|
||||
|
||||
def run(prefetch, size_name, files, output):
|
||||
size = SIZES[size_name]
|
||||
data = _png(size)
|
||||
with httpx.Client(timeout=30) as c:
|
||||
a = _user(c)
|
||||
b = _user(c)
|
||||
chat = c.post(
|
||||
f"{BASE}/api/v1/chats",
|
||||
json={"title": f"qb-{prefetch}-{size_name}", "member_ids": [a["id"], b["id"]]},
|
||||
headers=_auth(a),
|
||||
).json()
|
||||
chat_id = chat["id"]
|
||||
|
||||
_restart_worker(prefetch)
|
||||
|
||||
uploads = []
|
||||
started = time.monotonic()
|
||||
with httpx.Client(timeout=30) as c:
|
||||
for i in range(files):
|
||||
t = time.monotonic()
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat_id}/attachments",
|
||||
params={"filename": f"f{i}.png"},
|
||||
content=data,
|
||||
headers={**_auth(a), "Content-Type": "image/png"},
|
||||
)
|
||||
if r.status_code != 202:
|
||||
print(f"upload failed: {r.status_code} {r.text[:100]}", file=sys.stderr)
|
||||
continue
|
||||
uploads.append({"id": r.json()["id"], "t_upload": t})
|
||||
|
||||
states = {u["id"]: {"t_upload": u["t_upload"], "t_processing": None, "t_ready": None}
|
||||
for u in uploads}
|
||||
deadline = time.monotonic() + 600
|
||||
pending = set(states)
|
||||
with httpx.Client(timeout=10) as c:
|
||||
while pending and time.monotonic() < deadline:
|
||||
for att_id in list(pending):
|
||||
r = c.get(f"{BASE}/api/v1/attachments/{att_id}", headers=_auth(a))
|
||||
if r.status_code != 200:
|
||||
continue
|
||||
st = r.json()["status"]
|
||||
now = time.monotonic()
|
||||
if st == "processing" and states[att_id]["t_processing"] is None:
|
||||
states[att_id]["t_processing"] = now
|
||||
if st in ("ready", "failed"):
|
||||
if states[att_id]["t_processing"] is None:
|
||||
states[att_id]["t_processing"] = now
|
||||
states[att_id]["t_ready"] = now
|
||||
pending.discard(att_id)
|
||||
if pending:
|
||||
time.sleep(0.2)
|
||||
|
||||
finished = time.monotonic()
|
||||
rss = _worker_mem()
|
||||
|
||||
queue_lags = [
|
||||
s["t_processing"] - s["t_upload"]
|
||||
for s in states.values() if s["t_processing"] is not None
|
||||
]
|
||||
ready_times = [
|
||||
s["t_ready"] - s["t_upload"]
|
||||
for s in states.values() if s["t_ready"] is not None
|
||||
]
|
||||
duration = finished - started
|
||||
ok = len(ready_times)
|
||||
report = {
|
||||
"prefetch": prefetch,
|
||||
"size": size_name,
|
||||
"files_requested": files,
|
||||
"files_ok": ok,
|
||||
"files_failed": files - ok,
|
||||
"duration_s": round(duration, 3),
|
||||
"throughput_files_per_s": round(ok / duration, 3) if duration else None,
|
||||
"queue_lag_s": _percentiles(queue_lags),
|
||||
"time_to_ready_s": _percentiles(ready_times),
|
||||
"worker_rss_mib": rss,
|
||||
}
|
||||
out = Path(output)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
print(json.dumps(report, indent=2, ensure_ascii=False))
|
||||
_start_worker(prefetch)
|
||||
return report
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--prefetch", type=int, required=True)
|
||||
parser.add_argument("--size", choices=list(SIZES), required=True)
|
||||
parser.add_argument("--files", type=int, default=50)
|
||||
parser.add_argument("--output", required=True)
|
||||
args = parser.parse_args()
|
||||
run(args.prefetch, args.size, args.files, args.output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,101 @@
|
||||
import argparse
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from PIL import Image
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
||||
EVIDENCE = Path(__file__).resolve().parent.parent / "evidence"
|
||||
|
||||
|
||||
def _png(size=(1280, 800)):
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", size, (128, 64, 192)).save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _user(c):
|
||||
u = "qr_" + uuid.uuid4().hex[:10]
|
||||
p = "Test-password-1234"
|
||||
c.post(f"{BASE}/api/v1/users", json={"username": u, "display_name": "Q", "password": p})
|
||||
cred = base64.b64encode(f"{u}:{p}".encode()).decode()
|
||||
s = c.post(f"{BASE}/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred}).json()
|
||||
return {"id": s["user"]["id"], "token": s["token"]}
|
||||
|
||||
|
||||
def _auth(a):
|
||||
return {"Authorization": "Bearer " + a["token"]}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--files", type=int, default=100)
|
||||
parser.add_argument("--output", default="evidence/queue-recovery.json")
|
||||
args = parser.parse_args()
|
||||
|
||||
data = _png()
|
||||
with httpx.Client(timeout=30) as c:
|
||||
a = _user(c)
|
||||
b = _user(c)
|
||||
chat = c.post(
|
||||
f"{BASE}/api/v1/chats",
|
||||
json={"title": "recovery", "member_ids": [a["id"], b["id"]]},
|
||||
headers=_auth(a),
|
||||
).json()
|
||||
chat_id = chat["id"]
|
||||
|
||||
subprocess.run(COMPOSE + ["stop", "worker"], check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
ids = []
|
||||
with httpx.Client(timeout=30) as c:
|
||||
for i in range(args.files):
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat_id}/attachments",
|
||||
params={"filename": f"f{i}.png"},
|
||||
content=data,
|
||||
headers={**_auth(a), "Content-Type": "image/png"},
|
||||
)
|
||||
if r.status_code == 202:
|
||||
ids.append(r.json()["id"])
|
||||
print(f"uploaded {len(ids)} files, queue accumulated", flush=True)
|
||||
|
||||
time.sleep(10)
|
||||
subprocess.run(COMPOSE + ["start", "worker"], check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
worker_started = time.monotonic()
|
||||
|
||||
deadline = time.monotonic() + 600
|
||||
pending = set(ids)
|
||||
with httpx.Client(timeout=10) as c:
|
||||
while pending and time.monotonic() < deadline:
|
||||
for att_id in list(pending):
|
||||
r = c.get(f"{BASE}/api/v1/attachments/{att_id}", headers=_auth(a))
|
||||
if r.status_code != 200:
|
||||
continue
|
||||
if r.json()["status"] in ("ready", "failed"):
|
||||
pending.discard(att_id)
|
||||
if pending:
|
||||
time.sleep(0.5)
|
||||
finished = time.monotonic()
|
||||
report = {
|
||||
"files": args.files,
|
||||
"finished": args.files - len(pending),
|
||||
"pending_after_timeout": len(pending),
|
||||
"recovery_time_s": round(finished - worker_started, 3),
|
||||
}
|
||||
out = Path(args.output)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
print(json.dumps(report, indent=2, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,191 @@
|
||||
import base64
|
||||
import io
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
from PIL import Image
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
|
||||
|
||||
def _register_and_login(client: httpx.Client) -> dict:
|
||||
username = "att_" + uuid.uuid4().hex[:10]
|
||||
password = "Test-password-1234"
|
||||
r = client.post(
|
||||
f"{BASE}/api/v1/users",
|
||||
json={"username": username, "display_name": "A", "password": password},
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
user = r.json()
|
||||
cred = base64.b64encode((username + ":" + password).encode()).decode()
|
||||
r = client.post(
|
||||
f"{BASE}/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + cred},
|
||||
)
|
||||
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 _idem(actor: dict) -> dict:
|
||||
return {**_auth(actor), "Idempotency-Key": uuid.uuid4().hex}
|
||||
|
||||
|
||||
def _png(w: int = 320, h: int = 200, color=(255, 0, 0)) -> bytes:
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (w, h), color).save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _chat(client: httpx.Client, owner: dict, *members: dict) -> dict:
|
||||
member_ids = [owner["id"]] + [m["id"] for m in members]
|
||||
r = client.post(
|
||||
f"{BASE}/api/v1/chats",
|
||||
json={"title": "att", "member_ids": member_ids},
|
||||
headers=_auth(owner),
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def _upload(client, actor, chat_id, data, filename="x.png", content_type="image/png"):
|
||||
return client.post(
|
||||
f"{BASE}/api/v1/chats/{chat_id}/attachments",
|
||||
params={"filename": filename},
|
||||
content=data,
|
||||
headers={**_auth(actor), "Content-Type": content_type},
|
||||
)
|
||||
|
||||
|
||||
def test_oversize_returns_413():
|
||||
with httpx.Client(timeout=30) as c:
|
||||
a = _register_and_login(c)
|
||||
b = _register_and_login(c)
|
||||
chat = _chat(c, a, b)
|
||||
big = b"\x89PNG\r\n\x1a\n" + b"\x00" * (10 * 1024 * 1024)
|
||||
r = _upload(c, a, chat["id"], big, filename="big.png")
|
||||
assert r.status_code == 413, r.text
|
||||
assert r.json()["error"]["code"] == "payload_too_large"
|
||||
|
||||
|
||||
def test_corrupted_image_returns_415():
|
||||
with httpx.Client(timeout=10) as c:
|
||||
a = _register_and_login(c)
|
||||
b = _register_and_login(c)
|
||||
chat = _chat(c, a, b)
|
||||
data = _png()[:50]
|
||||
r = _upload(c, a, chat["id"], data)
|
||||
assert r.status_code == 415, r.text
|
||||
assert r.json()["error"]["code"] == "unsupported_media_type"
|
||||
|
||||
|
||||
def test_mime_spoof_returns_415():
|
||||
with httpx.Client(timeout=10) as c:
|
||||
a = _register_and_login(c)
|
||||
b = _register_and_login(c)
|
||||
chat = _chat(c, a, b)
|
||||
r = _upload(c, a, chat["id"], b"not an image at all")
|
||||
assert r.status_code == 415, r.text
|
||||
assert r.json()["error"]["code"] == "unsupported_media_type"
|
||||
|
||||
|
||||
def test_bad_filename_returns_400():
|
||||
with httpx.Client(timeout=10) as c:
|
||||
a = _register_and_login(c)
|
||||
b = _register_and_login(c)
|
||||
chat = _chat(c, a, b)
|
||||
r = _upload(c, a, chat["id"], _png(), filename="../etc/passwd")
|
||||
assert r.status_code == 400, r.text
|
||||
assert r.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
def test_empty_file_returns_415():
|
||||
with httpx.Client(timeout=10) as c:
|
||||
a = _register_and_login(c)
|
||||
b = _register_and_login(c)
|
||||
chat = _chat(c, a, b)
|
||||
r = _upload(c, a, chat["id"], b"")
|
||||
assert r.status_code == 415, r.text
|
||||
|
||||
|
||||
def test_outsider_cannot_download():
|
||||
with httpx.Client(timeout=10) as c:
|
||||
a = _register_and_login(c)
|
||||
b = _register_and_login(c)
|
||||
eve = _register_and_login(c)
|
||||
chat = _chat(c, a, b)
|
||||
att = _upload(c, a, chat["id"], _png()).json()
|
||||
r = c.get(f"{BASE}/api/v1/attachments/{att['id']}", headers=_auth(eve))
|
||||
assert r.status_code == 404
|
||||
r = c.get(f"{BASE}/api/v1/attachments/{att['id']}/content", headers=_auth(eve))
|
||||
assert r.status_code == 404
|
||||
|
||||
|
||||
def test_attach_foreign_attachment_returns_404():
|
||||
with httpx.Client(timeout=10) as c:
|
||||
a = _register_and_login(c)
|
||||
b = _register_and_login(c)
|
||||
chat1 = _chat(c, a, b)
|
||||
chat2 = _chat(c, a, b)
|
||||
att = _upload(c, a, chat1["id"], _png()).json()
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat2['id']}/messages",
|
||||
json={"text": "hi", "attachment_ids": [att["id"]]},
|
||||
headers=_idem(a),
|
||||
)
|
||||
assert r.status_code == 404, r.text
|
||||
|
||||
|
||||
def test_empty_text_without_attachments_returns_400():
|
||||
with httpx.Client(timeout=10) as c:
|
||||
a = _register_and_login(c)
|
||||
b = _register_and_login(c)
|
||||
chat = _chat(c, a, b)
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": ""},
|
||||
headers=_idem(a),
|
||||
)
|
||||
assert r.status_code == 400, r.text
|
||||
assert r.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
def test_empty_text_with_attachment_returns_201():
|
||||
with httpx.Client(timeout=10) as c:
|
||||
a = _register_and_login(c)
|
||||
b = _register_and_login(c)
|
||||
chat = _chat(c, a, b)
|
||||
att = _upload(c, a, chat["id"], _png()).json()
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": "", "attachment_ids": [att["id"]]},
|
||||
headers=_idem(a),
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
assert r.json()["attachment_ids"] == [att["id"]]
|
||||
|
||||
|
||||
def test_user_error_is_not_500():
|
||||
with httpx.Client(timeout=10) as c:
|
||||
a = _register_and_login(c)
|
||||
b = _register_and_login(c)
|
||||
chat = _chat(c, a, b)
|
||||
cases = [
|
||||
(_upload(c, a, chat["id"], b"not image"), 415),
|
||||
(_upload(c, a, chat["id"], b""), 415),
|
||||
(_upload(c, a, chat["id"], _png(), filename="../x"), 400),
|
||||
(
|
||||
c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": ""},
|
||||
headers=_idem(a),
|
||||
),
|
||||
400,
|
||||
),
|
||||
]
|
||||
for response, expected in cases:
|
||||
assert response.status_code == expected, response.text
|
||||
assert response.status_code < 500
|
||||
@@ -0,0 +1,129 @@
|
||||
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-" + uuid.uuid4().hex[:8]
|
||||
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 _auth_idem(actor: dict) -> dict:
|
||||
return {
|
||||
"Authorization": "Bearer " + actor["token"],
|
||||
"Idempotency-Key": uuid.uuid4().hex,
|
||||
}
|
||||
|
||||
|
||||
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()
|
||||
|
||||
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
|
||||
|
||||
text = "read-after-write-" + uuid.uuid4().hex[:8]
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": text},
|
||||
headers=_auth_idem(alice),
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
|
||||
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):
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": f"msg-{i}"},
|
||||
headers=_auth_idem(alice),
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
|
||||
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
|
||||
|
||||
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,134 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
from PIL import Image
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
|
||||
|
||||
def _user(c):
|
||||
u = "ps_" + uuid.uuid4().hex[:10]
|
||||
p = "Test-password-1234"
|
||||
r = c.post(f"{BASE}/api/v1/users", json={"username": u, "display_name": "P", "password": p})
|
||||
assert r.status_code == 201, r.text
|
||||
user = r.json()
|
||||
cred = base64.b64encode(f"{u}:{p}".encode()).decode()
|
||||
s = c.post(f"{BASE}/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred}).json()
|
||||
return {"id": user["id"], "token": s["token"]}
|
||||
|
||||
|
||||
def _auth(a):
|
||||
return {"Authorization": "Bearer " + a["token"]}
|
||||
|
||||
|
||||
def _png(w=320, h=200):
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (w, h), (0, 255, 0)).save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _chat(c, a, b):
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats",
|
||||
json={"title": "ps", "member_ids": [a["id"], b["id"]]},
|
||||
headers=_auth(a),
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def test_presigned_happy_path():
|
||||
with httpx.Client(timeout=30) as c:
|
||||
a = _user(c)
|
||||
b = _user(c)
|
||||
chat = _chat(c, a, b)
|
||||
data = _png()
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/attachments/presign",
|
||||
params={"filename": "p.png", "size": len(data), "content_type": "image/png"},
|
||||
headers=_auth(a),
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
presign = r.json()
|
||||
put = httpx.put(presign["upload_url"], content=data, headers={"Content-Type": "image/png"})
|
||||
assert put.status_code == 200, put.text
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/attachments/{presign['attachment_id']}/complete",
|
||||
headers=_auth(a),
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
att = r.json()
|
||||
assert att["status"] == "ready"
|
||||
assert att["sha256"] == hashlib.sha256(data).hexdigest()
|
||||
dl = c.get(f"{BASE}/api/v1/attachments/{att['id']}/content", headers=_auth(b))
|
||||
assert dl.status_code == 200
|
||||
assert dl.content == data
|
||||
|
||||
|
||||
def test_presigned_bad_signature_rejected():
|
||||
with httpx.Client(timeout=30) as c:
|
||||
a = _user(c)
|
||||
b = _user(c)
|
||||
chat = _chat(c, a, b)
|
||||
data = _png()
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/attachments/presign",
|
||||
params={"filename": "p.png", "size": len(data), "content_type": "image/png"},
|
||||
headers=_auth(a),
|
||||
)
|
||||
url = r.json()["upload_url"]
|
||||
bad = url.replace("X-Amz-Signature=", "X-Amz-Signature=deadbeef")
|
||||
put = httpx.put(bad, content=data, headers={"Content-Type": "image/png"})
|
||||
assert put.status_code == 403, put.text
|
||||
|
||||
|
||||
def test_presigned_complete_without_upload_409():
|
||||
with httpx.Client(timeout=10) as c:
|
||||
a = _user(c)
|
||||
b = _user(c)
|
||||
chat = _chat(c, a, b)
|
||||
data = _png()
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/attachments/presign",
|
||||
params={"filename": "p.png", "size": len(data), "content_type": "image/png"},
|
||||
headers=_auth(a),
|
||||
)
|
||||
att_id = r.json()["attachment_id"]
|
||||
r = c.post(f"{BASE}/api/v1/attachments/{att_id}/complete", headers=_auth(a))
|
||||
assert r.status_code == 409, r.text
|
||||
|
||||
|
||||
def test_presigned_outsider_404():
|
||||
with httpx.Client(timeout=10) as c:
|
||||
a = _user(c)
|
||||
b = _user(c)
|
||||
eve = _user(c)
|
||||
chat = _chat(c, a, b)
|
||||
data = _png()
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/attachments/presign",
|
||||
params={"filename": "p.png", "size": len(data), "content_type": "image/png"},
|
||||
headers=_auth(a),
|
||||
)
|
||||
att_id = r.json()["attachment_id"]
|
||||
r = c.post(f"{BASE}/api/v1/attachments/{att_id}/complete", headers=_auth(eve))
|
||||
assert r.status_code == 404, r.text
|
||||
|
||||
|
||||
def test_proxy_endpoint_still_works():
|
||||
with httpx.Client(timeout=10) as c:
|
||||
a = _user(c)
|
||||
b = _user(c)
|
||||
chat = _chat(c, a, b)
|
||||
data = _png()
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/attachments",
|
||||
params={"filename": "proxy.png"},
|
||||
content=data,
|
||||
headers={**_auth(a), "Content-Type": "image/png"},
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
assert r.json()["status"] == "ready"
|
||||
@@ -0,0 +1,84 @@
|
||||
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):
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
||||
json={"text": f"w{worker_id}-m{i}"},
|
||||
headers={
|
||||
"Authorization": "Bearer " + alice["token"],
|
||||
"Idempotency-Key": uuid.uuid4().hex,
|
||||
},
|
||||
)
|
||||
if r.status_code != 201:
|
||||
print(f"POST FAIL w{worker_id}-m{i}: {r.status_code} {r.text[:200]}")
|
||||
|
||||
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()
|
||||
if r.status_code != 200 or "items" not in page:
|
||||
print(f"GET FAIL: {r.status_code} {r.text[:500]}")
|
||||
print(f"chat_id: {chat['id']}")
|
||||
print(f"alice_token: {alice['token'][:30]}...")
|
||||
raise AssertionError(f"GET messages failed: {r.status_code}")
|
||||
all_ids.extend(m["id"] for m in page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if not cursor:
|
||||
break
|
||||
|
||||
print(f"Got {len(all_ids)} messages, unique: {len(set(all_ids))}")
|
||||
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 _auth_idem(actor: dict) -> dict:
|
||||
return {
|
||||
"Authorization": "Bearer " + actor["token"],
|
||||
"Idempotency-Key": uuid.uuid4().hex,
|
||||
}
|
||||
|
||||
|
||||
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_idem(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_idem(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_idem(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():
|
||||
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():
|
||||
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
|
||||
@@ -0,0 +1,100 @@
|
||||
import base64
|
||||
import io
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
from PIL import Image
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
||||
|
||||
|
||||
def _user(c):
|
||||
u = "crash_" + uuid.uuid4().hex[:10]
|
||||
p = "Test-password-1234"
|
||||
c.post(f"{BASE}/api/v1/users", json={"username": u, "display_name": "C", "password": p})
|
||||
cred = base64.b64encode(f"{u}:{p}".encode()).decode()
|
||||
s = c.post(f"{BASE}/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred}).json()
|
||||
return {"id": s["user"]["id"], "token": s["token"]}
|
||||
|
||||
|
||||
def _auth(a):
|
||||
return {"Authorization": "Bearer " + a["token"]}
|
||||
|
||||
|
||||
def _png():
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (320, 200), (0, 128, 255)).save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _wait_ready(c, att_id, token, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
r = c.get(f"{BASE}/api/v1/attachments/{att_id}", headers=_auth({"token": token}))
|
||||
if r.status_code == 200 and r.json()["status"] == "ready":
|
||||
return r.json()
|
||||
time.sleep(0.5)
|
||||
raise AssertionError("attachment did not become ready")
|
||||
|
||||
|
||||
def _delete_variant(chat_id, att_id, name):
|
||||
key = f"{name}s/{chat_id}/{att_id}.jpg"
|
||||
script = "from app.s3 import s3\ns3.remove('" + key + "')\nprint('removed')\n"
|
||||
subprocess.run(
|
||||
COMPOSE + ["exec", "-T", "worker", "python", "-c", script],
|
||||
check=True,
|
||||
)
|
||||
|
||||
|
||||
def test_worker_recovers_after_ack_lost():
|
||||
with httpx.Client(timeout=30) as c:
|
||||
a = _user(c)
|
||||
b = _user(c)
|
||||
chat = c.post(
|
||||
f"{BASE}/api/v1/chats",
|
||||
json={"title": "crash", "member_ids": [a["id"], b["id"]]},
|
||||
headers=_auth(a),
|
||||
).json()
|
||||
data = _png()
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/chats/{chat['id']}/attachments",
|
||||
params={"filename": "c.png"},
|
||||
content=data,
|
||||
headers={**_auth(a), "Content-Type": "image/png"},
|
||||
)
|
||||
assert r.status_code == 202, r.text
|
||||
att = r.json()
|
||||
att_id = att["id"]
|
||||
|
||||
_wait_ready(c, att_id, a["token"])
|
||||
before = c.get(f"{BASE}/api/v1/attachments/{att_id}", headers=_auth(a)).json()
|
||||
thumb1 = c.get(
|
||||
f"{BASE}/api/v1/attachments/{att_id}/content?variant=thumbnail",
|
||||
headers=_auth(a),
|
||||
)
|
||||
assert thumb1.status_code == 200
|
||||
|
||||
_delete_variant(chat["id"], att_id, "thumbnail")
|
||||
|
||||
subprocess.run(
|
||||
COMPOSE + ["exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-c",
|
||||
f"UPDATE attachments SET status='failed', error_code='ack_lost' WHERE id='{att_id}'"],
|
||||
check=True,
|
||||
)
|
||||
|
||||
r = c.post(
|
||||
f"{BASE}/api/v1/attachments/{att_id}/replay",
|
||||
headers=_auth(a),
|
||||
)
|
||||
assert r.status_code == 202, r.text
|
||||
|
||||
ready = _wait_ready(c, att_id, a["token"])
|
||||
thumb2 = c.get(
|
||||
f"{BASE}/api/v1/attachments/{att_id}/content?variant=thumbnail",
|
||||
headers=_auth(a),
|
||||
)
|
||||
assert thumb2.status_code == 200
|
||||
assert ready["variants"] == before["variants"], "variants changed after replay"
|
||||
Reference in New Issue
Block a user