выполнение ЛР3 на 4
This commit is contained in:
@@ -0,0 +1,147 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import math
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def pct(values, p):
|
||||
return round(1000 * values[max(0, math.ceil(p * len(values)) - 1)], 1) if values else None
|
||||
|
||||
|
||||
def docker_stats():
|
||||
ids = subprocess.run(["docker", "compose", "ps", "-q"], cwd=ROOT, capture_output=True, text=True).stdout.split()
|
||||
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}", *ids],
|
||||
capture_output=True, text=True)
|
||||
return sorted(out.stdout.splitlines())
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument("--duration", type=float, default=25)
|
||||
p.add_argument("--concurrency", type=int, default=8)
|
||||
p.add_argument("--action", default=None, help="command run once at --action-at seconds")
|
||||
p.add_argument("--action-at", type=float, default=5)
|
||||
p.add_argument("--output", default=None)
|
||||
args = arguments("Load with an operator action in the middle", configure)
|
||||
boot = Client(args.base_url, timeout=10)
|
||||
alice, bob, _eve, chat = boot.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
|
||||
events = []
|
||||
confirmed = []
|
||||
lock = threading.Lock()
|
||||
t0 = time.monotonic()
|
||||
stop_at = t0 + args.duration
|
||||
action_info = {}
|
||||
|
||||
def worker(wid):
|
||||
c = Client(args.base_url, timeout=2)
|
||||
key, text, n = None, None, 0
|
||||
while time.monotonic() < stop_at:
|
||||
if key is None:
|
||||
key = uuid.uuid4().hex
|
||||
text = "chaos-%d-%d-%s" % (wid, n, key[:8])
|
||||
for kind in ("write", "read"):
|
||||
start = time.monotonic()
|
||||
try:
|
||||
if kind == "write":
|
||||
r = c.call("POST", path, 201, actor=alice, body={"text": text}, headers={"Idempotency-Key": key}, schema="Message")
|
||||
else:
|
||||
r = c.call("GET", path + "?limit=20", actor=bob, schema="MessagePage")
|
||||
ok, inst = True, r["headers"].get("X-Instance-Id")
|
||||
except Failure:
|
||||
ok, inst = False, None
|
||||
end = time.monotonic()
|
||||
with lock:
|
||||
events.append((start - t0, kind, ok, end - start, inst))
|
||||
if ok and kind == "write":
|
||||
confirmed.append(r["json"])
|
||||
if kind == "write" and ok:
|
||||
key, n = None, n + 1
|
||||
if not ok:
|
||||
time.sleep(0.05)
|
||||
|
||||
def action():
|
||||
time.sleep(args.action_at)
|
||||
action_info["started"] = time.monotonic() - t0
|
||||
proc = subprocess.run(shlex.split(args.action), cwd=ROOT, capture_output=True, text=True)
|
||||
action_info["finished"] = time.monotonic() - t0
|
||||
action_info["returncode"] = proc.returncode
|
||||
action_info["output_tail"] = proc.stdout.strip().splitlines()[-6:]
|
||||
|
||||
stats_mid = []
|
||||
threads = [threading.Thread(target=worker, args=(i,)) for i in range(args.concurrency)]
|
||||
if args.action:
|
||||
threads.append(threading.Thread(target=action))
|
||||
for t in threads:
|
||||
t.start()
|
||||
time.sleep(min(args.duration / 2, args.action_at + 3))
|
||||
stats_mid = docker_stats()
|
||||
for t in threads:
|
||||
t.join()
|
||||
elapsed = time.monotonic() - t0
|
||||
|
||||
ok_lat = sorted(e[3] for e in events if e[2])
|
||||
errors = [e for e in events if not e[2]]
|
||||
a0 = action_info.get("started")
|
||||
timeline = defaultdict(lambda: [0, 0])
|
||||
for e in events:
|
||||
timeline[int(e[0])][0 if e[2] else 1] += 1
|
||||
report = {
|
||||
"profile": "closed loop, %d workers, each: POST message (retry same key) + GET history; client timeout 2 s" % args.concurrency,
|
||||
"action": args.action, "action_started_s": a0 and round(a0, 2), "action_finished_s": action_info.get("finished") and round(action_info["finished"], 2),
|
||||
"action_returncode": action_info.get("returncode"), "action_output": action_info.get("output_tail"),
|
||||
"elapsed_s": round(elapsed, 2), "requests": len(events), "successful": len(ok_lat), "errors": len(errors),
|
||||
"error_ratio": round(len(errors) / len(events), 5) if events else None,
|
||||
"successful_rps": round(len(ok_lat) / elapsed, 1),
|
||||
"latency_ms_success": {"p50": pct(ok_lat, .50), "p95": pct(ok_lat, .95), "p99": pct(ok_lat, .99), "max": pct(ok_lat, 1)},
|
||||
"slow_over_500ms_after_action": sum(1 for e in events if e[2] and e[3] > .5 and a0 is not None and e[0] >= a0),
|
||||
"error_window_s": [round(errors[0][0] - (a0 or 0), 2), round(max(e[0] + e[3] for e in errors) - (a0 or 0), 2)] if errors else None,
|
||||
"recovery_s_after_action": None,
|
||||
"instances_before": dict(Counter(e[4] for e in events if e[2] and (a0 is None or e[0] < a0))),
|
||||
"instances_last_5s": dict(Counter(e[4] for e in events if e[2] and e[0] > elapsed - 5)),
|
||||
"timeline_ok_err_per_s": {k: v for k, v in sorted(timeline.items())},
|
||||
"docker_stats_mid": stats_mid,
|
||||
}
|
||||
if a0 is not None:
|
||||
bad_ends = [e[0] + e[3] for e in events if e[0] + e[3] >= a0 and (not e[2] or e[3] > 1)]
|
||||
report["recovery_s_after_action"] = round(max(bad_ends) - a0, 2) if bad_ends else 0.0
|
||||
|
||||
items, cursor = [], None
|
||||
while True:
|
||||
q = path + "?limit=100" + ("&cursor=" + quote(cursor, safe="") if cursor else "")
|
||||
page = boot.call("GET", q, actor=bob, schema="MessagePage")["json"]
|
||||
items += page["items"]
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
ids = Counter(m["id"] for m in items)
|
||||
texts = Counter(m["text"] for m in items)
|
||||
stored = {m["id"]: m for m in items}
|
||||
report["integrity"] = {
|
||||
"stored_messages": len(items), "confirmed_writes": len(confirmed),
|
||||
"duplicate_ids": sum(1 for n in ids.values() if n > 1), "duplicate_texts": sum(1 for n in texts.values() if n > 1),
|
||||
"confirmed_missing": sum(1 for m in confirmed if stored.get(m["id"]) != m),
|
||||
}
|
||||
text = json.dumps(report, ensure_ascii=False, indent=1)
|
||||
print(text)
|
||||
if args.output:
|
||||
Path(args.output).write_text(text + "\n")
|
||||
check(report["integrity"]["duplicate_texts"] == 0 and report["integrity"]["confirmed_missing"] == 0, "data integrity violated")
|
||||
check(action_info.get("returncode", 0) == 0, "action failed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def post(c, actor, chat, text, key, expected=201):
|
||||
return c.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", expected, actor=actor,
|
||||
body={"text": text}, headers={"Idempotency-Key": key},
|
||||
schema="Message" if expected == 201 else None)
|
||||
|
||||
|
||||
def history(c, actor, chat):
|
||||
return c.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100", actor=actor, schema="MessagePage")["json"]["items"]
|
||||
|
||||
|
||||
def db_count(chat_id):
|
||||
sql = "SELECT count(*) FROM messages WHERE chat_id = '%s'" % uuid.UUID(chat_id)
|
||||
out = subprocess.run(["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-tAX", "-c", sql],
|
||||
cwd=ROOT, capture_output=True, text=True)
|
||||
return int(out.stdout.strip()) if out.returncode == 0 else None
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument("--parallel", type=int, default=32)
|
||||
p.add_argument("--rounds", type=int, default=5)
|
||||
args = arguments("Concurrent idempotency through the LB", configure)
|
||||
c = Client(args.base_url, timeout=10)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
|
||||
for rnd in range(args.rounds):
|
||||
key = "par-%d-%s" % (rnd, uuid.uuid4().hex)
|
||||
text = "одновременно " + key
|
||||
barrier = threading.Barrier(args.parallel)
|
||||
results, errors = [], []
|
||||
|
||||
def worker():
|
||||
local = Client(args.base_url, timeout=10)
|
||||
barrier.wait()
|
||||
try:
|
||||
r = post(local, alice, chat, text, key)
|
||||
results.append((r["json"], r["headers"]["X-Instance-Id"]))
|
||||
except Failure as exc:
|
||||
errors.append(str(exc))
|
||||
|
||||
threads = [threading.Thread(target=worker) for _ in range(args.parallel)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
check(not errors, "concurrent replay failed: %s" % errors[:3])
|
||||
ids = {m["id"] for m, _ in results}
|
||||
instances = Counter(i for _, i in results)
|
||||
check(len(ids) == 1, "concurrent requests created %d messages" % len(ids))
|
||||
check(all(m == results[0][0] for m, _ in results), "replays returned different bodies")
|
||||
check(len(instances) >= 2, "all requests hit one replica; LB not balancing")
|
||||
stored = [m for m in history(c, bob, chat) if m["text"] == text]
|
||||
check(len(stored) == 1, "history has %d copies" % len(stored))
|
||||
print("ok - round %d: %d parallel requests, 1 message, replicas %s" % (rnd + 1, args.parallel, dict(instances)))
|
||||
|
||||
key = uuid.uuid4().hex
|
||||
first = post(c, alice, chat, "оригинал", key)["json"]
|
||||
for _ in range(4):
|
||||
post(c, alice, chat, "другой текст", key, expected=409)
|
||||
check(post(c, alice, chat, "оригинал", key)["json"] == first, "replay changed")
|
||||
print("ok - different body with same key -> 409, original replays unchanged")
|
||||
|
||||
other = post(c, bob, chat, "оригинал", key)["json"]
|
||||
check(other["id"] != first["id"] and other["sender_id"] == bob["id"], "key leaked across users")
|
||||
chat2 = c.call("POST", "/api/v1/chats", 201, actor=alice, body={"title": "второй", "member_ids": [alice["id"], bob["id"]]}, schema="Chat")["json"]
|
||||
third = post(c, alice, chat2, "оригинал", key)["json"]
|
||||
check(third["id"] != first["id"] and third["chat_id"] == chat2["id"], "key leaked across chats")
|
||||
print("ok - same key independent per user and per chat")
|
||||
|
||||
for bad in ("", "with space", "кириллица", "x" * 129, "a/b"):
|
||||
try:
|
||||
post(c, alice, chat, "bad key", bad, expected=400)
|
||||
except UnicodeEncodeError:
|
||||
pass
|
||||
c.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", 400, actor=alice, body={"text": "без ключа"})
|
||||
post(c, alice, chat, "ok", "A-Za-z0-9._:-" + "k" * 115)
|
||||
print("ok - missing/invalid Idempotency-Key -> 400, max-length key accepted")
|
||||
|
||||
post(c, eve, chat, "оригинал", key, expected=404)
|
||||
sid = Client(args.base_url)
|
||||
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=bob)
|
||||
post(sid, bob, chat, "оригинал", key, expected=401)
|
||||
print("ok - replay needs a valid session and chat access (404 outsider, 401 revoked)")
|
||||
|
||||
count = db_count(chat["id"])
|
||||
texts = Counter(m["text"] for m in history(c, alice, chat))
|
||||
check(all(n == 1 for t, n in texts.items() if t.startswith("одновременно")), "duplicates in history")
|
||||
print("ok - DB rows in chat: %s, history items: %d, no duplicate texts" % (count, sum(texts.values())))
|
||||
print("PASS: shared idempotency")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user