forked from mtusi2026/mtusi2026lab4
код из lab3
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
import base64, json, sys, urllib.error, urllib.request, uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
BASE = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
|
||||
PWD = "correct-horse-battery-staple"
|
||||
|
||||
|
||||
def call(method, path, body=None, token=None, basic=None, key=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
req = urllib.request.Request(BASE + path, data=data, method=method)
|
||||
if body is not None:
|
||||
req.add_header("Content-Type", "application/json")
|
||||
if token:
|
||||
req.add_header("Authorization", "Bearer " + token)
|
||||
if basic:
|
||||
req.add_header("Authorization", "Basic " + base64.b64encode(basic.encode()).decode())
|
||||
if key:
|
||||
req.add_header("Idempotency-Key", key)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
raw = r.read()
|
||||
return r.status, r.headers.get("X-Instance-Id"), json.loads(raw) if raw else None
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.headers.get("X-Instance-Id"), None
|
||||
|
||||
|
||||
ok = True
|
||||
def check(name, cond, info=""):
|
||||
global ok
|
||||
ok &= bool(cond)
|
||||
print(("PASS" if cond else "FAIL"), name, info)
|
||||
|
||||
|
||||
name = "lb_" + uuid.uuid4().hex[:10]
|
||||
s, _, user = call("POST", "/api/v1/users", {"username": name, "display_name": "LB check", "password": PWD})
|
||||
s, _, sess = call("POST", "/api/v1/auth/sessions", basic=f"{name}:{PWD}")
|
||||
token = sess["token"]
|
||||
|
||||
# один токен разные реплики
|
||||
inst = {call("GET", "/api/v1/users/me", token=token)[1] for _ in range(12)}
|
||||
check("one token served by >=2 replicas", len(inst) >= 2, sorted(inst))
|
||||
|
||||
s, _, chat = call("POST", "/api/v1/chats", {"title": "lb", "member_ids": [user["id"]]}, token=token)
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
# конкурентные повторы с одним ключом через lb
|
||||
key = "conc-" + uuid.uuid4().hex
|
||||
with ThreadPoolExecutor(30) as ex:
|
||||
res = list(ex.map(lambda _: call("POST", path, {"text": "race"}, token=token, key=key), range(30)))
|
||||
ids = {r[2]["id"] for r in res if r[2]}
|
||||
check("concurrent same key: all 201", all(r[0] == 201 for r in res), sorted({r[0] for r in res}))
|
||||
check("concurrent same key: one message id", len(ids) == 1, len(ids))
|
||||
check("concurrent requests hit >=2 replicas", len({r[1] for r in res}) >= 2, sorted({r[1] for r in res}))
|
||||
|
||||
# последовательный повтор на разных репликах
|
||||
key2 = "seq-" + uuid.uuid4().hex
|
||||
seq = [call("POST", path, {"text": "seq"}, token=token, key=key2) for _ in range(6)]
|
||||
check("sequential repeat: same id", len({r[2]["id"] for r in seq}) == 1)
|
||||
check("sequential repeat: >=2 replicas", len({r[1] for r in seq}) >= 2, sorted({r[1] for r in seq}))
|
||||
check("different body, same key -> 409", call("POST", path, {"text": "other"}, token=token, key=key2)[0] == 409)
|
||||
|
||||
s, _, page = call("GET", path + "?limit=100", token=token)
|
||||
check("history has exactly 2 messages", len(page["items"]) == 2, len(page["items"]))
|
||||
|
||||
sys.exit(0 if ok else 1)
|
||||
Reference in New Issue
Block a user