Реализовать лабораторную работу 3

This commit is contained in:
Никита
2026-11-02 18:55:53 +03:00
parent 0ab3a341aa
commit d2ff198781
109 changed files with 25218 additions and 27 deletions
+87
View File
@@ -0,0 +1,87 @@
"""Replica failures and sequential replacement under a continuous mixed workload."""
import argparse
import json
import time
from pathlib import Path
import sys
from cluster import alias, api_ids, docker, inspect, rolling_replace, wait_api
from compose_helpers import ROOT, compose, sql
from client import Client, check, run
from traffic import traffic, public_report
def verify_messages(chat, confirmations):
rows = json.loads(sql("SELECT coalesce(json_agg(json_build_object('id', id, 'text', text)), '[]') FROM messages WHERE chat_id = '" + chat["id"] + "';"))
saved = {row["id"]: row["text"] for row in rows}
check(all(saved.get(identifier) == text for identifier, text in confirmations), "confirmed message lost or changed")
check(len({row["text"] for row in rows}) == len(rows), "uncertain retry created duplicate text")
return {"confirmed_writes": len(confirmations), "stored_messages": len(rows), "no_duplicate_text": True}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://127.0.0.1:18080")
args = parser.parse_args()
wait_api(args.base_url, 2)
c = Client(args.base_url)
report = {"verified_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "failures": []}
try:
for position, mode in enumerate(("graceful", "immediate")):
targets = api_ids()
target = targets[position]
target_alias = alias(target)
alice, bob, eve, chat = c.bootstrap()
def stop():
docker("stop", "--time", "8" if mode == "graceful" else "0", target)
return {"container": target, "instance": target_alias, "running_after_action": inspect(target)["State"]["Running"]}
print("Testing " + mode + " stop of " + target[:12], flush=True)
measured = traffic(args.base_url, alice, chat, duration=16, concurrency=8,
action=stop, retry_uncertain=True)
action = measured["actions"][0]
check(not action["result"]["running_after_action"], "selected process was not stopped")
after = [row for row in measured["_samples"] if row[0] >= action["finished_after_seconds"] and row[1] == "write" and row[2] == 201]
check(after, "no confirmed writes after replica stopped")
recovery = after[0][0] - action["started_after_seconds"]
check(recovery <= 10, "writes did not recover in 10 seconds")
check(all(row[4] != target_alias for row in after[-5:]), "stopped replica still observed")
integrity = verify_messages(chat, measured["_confirmed"])
report["failures"].append({**public_report(measured), "mode": mode,
"recovery_seconds": round(recovery, 3), "integrity": integrity})
compose("start", "api")
wait_api(args.base_url, 2)
print("Building replacement image", flush=True)
compose("build", "--build-arg", "BUILD_REVISION=rolling-" + str(time.time_ns()), "api", timeout=180)
alice, bob, eve, chat = c.bootstrap()
print("Testing sequential replacement under mixed traffic", flush=True)
measured = traffic(args.base_url, alice, chat, duration=45, concurrency=8,
action=lambda: rolling_replace(args.base_url, build=False), retry_uncertain=True)
replacements = measured["actions"][0]["result"]
check(len(replacements) == 2, "not every replica was replaced")
check(all(row["old_container"] != row["new_container"] and row["old_image"] != row["new_image"]
for row in replacements), "replacement did not deploy a new image")
check(measured["actions"][0]["finished_after_seconds"] < 43, "replacement outlasted load window")
report["rolling_update"] = {**public_report(measured), "integrity": verify_messages(chat, measured["_confirmed"])}
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
containers = [inspect(container) for container in api_ids()]
check(all(not info["HostConfig"]["PortBindings"] for info in containers), "API ports published outside LB")
check(all(info["HostConfig"]["NanoCpus"] > 0 and info["HostConfig"]["Memory"] > 0 for info in containers), "missing API resource limit")
report["infrastructure"] = {
"api_ports_published": False,
"api_containers": [{"id": info["Id"], "image": info["Image"],
"cpu_limit": info["HostConfig"]["NanoCpus"] / 1e9,
"memory_limit": info["HostConfig"]["Memory"]} for info in containers],
"migrations": sql("SELECT string_agg(version::text, ',' ORDER BY version) FROM schema_migrations;")
}
(ROOT / "evidence" / "availability.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
print(json.dumps(report, ensure_ascii=False, indent=2))
finally:
compose("start", "api")
if __name__ == "__main__":
run(main)
+135
View File
@@ -0,0 +1,135 @@
import csv
import io
import json
import subprocess
import time
from urllib.request import urlopen
from compose_helpers import ROOT, compose
def docker(*args, input=None, timeout=90):
return subprocess.run(["docker", *args], input=input, text=True, capture_output=True,
check=True, timeout=timeout).stdout.strip()
def api_ids():
return compose("ps", "-q", "api").splitlines()
def inspect(container):
return json.loads(docker("inspect", container))[0]
def alias(container):
headers = docker("exec", container, "curl", "-fsS", "-D", "-", "-o", "/dev/null",
"http://127.0.0.1:8080/health/live")
return next(line.split(":", 1)[1].strip() for line in headers.splitlines()
if line.lower().startswith("x-instance-id:"))
def runtime(command):
lb = compose("ps", "-q", "lb")
return docker("exec", "-i", lb, "nc", "-w", "2", "127.0.0.1", "9999",
input=command + "\n", timeout=5)
def stats():
return list(csv.DictReader(io.StringIO(runtime("show stat").lstrip("# "))))
def servers():
return [row for row in stats() if row["pxname"] == "messenger" and row["svname"].startswith("api")]
def wait_api(base_url, expected, timeout=45):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
rows = servers()
up = [row for row in rows if row["status"] == "UP"]
if len(up) == expected:
with urlopen(base_url + "/health/ready", timeout=2) as response:
if response.status == 200:
return
except (OSError, subprocess.SubprocessError, StopIteration):
pass
time.sleep(.25)
raise RuntimeError("API replicas did not become ready")
def recreate(replicas=2, cpus=1, memory="384m", pool=20, batching=True, database_cpus=.5):
import os
environment = dict(os.environ, API_REPLICAS=str(replicas), API_CPUS=str(cpus),
API_MEMORY=memory, DB_POOL_SIZE=str(pool), MESSAGE_BATCHING=str(batching).lower(),
POSTGRES_CPUS=str(database_cpus))
subprocess.run([str(ROOT / "scripts/compose.sh"), "up", "-d", "--no-deps",
"--scale", "api=" + str(replicas), "--force-recreate", "api"],
cwd=ROOT, env=environment, capture_output=True, text=True, check=True, timeout=90)
def counters():
result = {}
for service in ("api", "postgres", "lb", "redis"):
for container in compose("ps", "-q", service).splitlines():
info = inspect(container)
data = docker("exec", container, "cat", "/sys/fs/cgroup/cpu.stat",
"/sys/fs/cgroup/memory.current").splitlines()
values = dict(line.split() for line in data[:-1])
result[container] = {
"service": service, "name": info["Name"].lstrip("/"),
"cpu_seconds": int(values["usage_usec"]) / 1e6,
"throttled_seconds": int(values["throttled_usec"]) / 1e6,
"throttled_periods": int(values["nr_throttled"]),
"memory_bytes": int(data[-1]),
"cpu_limit": info["HostConfig"]["NanoCpus"] / 1e9,
"memory_limit": info["HostConfig"]["Memory"],
}
return result
def counter_delta(before, after, seconds):
result = []
for container, current in after.items():
old = before.get(container, current)
row = {key: current[key] for key in ("service", "name", "cpu_limit", "memory_limit", "memory_bytes")}
row["used_cpu_cores"] = round((current["cpu_seconds"] - old["cpu_seconds"]) / seconds, 3)
row["throttled_seconds"] = round(current["throttled_seconds"] - old["throttled_seconds"], 3)
row["throttled_periods"] = current["throttled_periods"] - old["throttled_periods"]
result.append(row)
return result
def rolling_replace(base_url="http://127.0.0.1:18080", build=True):
originals = api_ids()
if len(originals) < 2:
raise RuntimeError("Rolling replacement requires at least two API replicas")
if build:
compose("build", "--build-arg", "BUILD_REVISION=rolling-" + str(time.time_ns()), "api", timeout=180)
records = []
for old in originals:
before = set(api_ids())
old_info = inspect(old)
old_alias = alias(old)
old_ip = next(iter(old_info["NetworkSettings"]["Networks"].values()))["IPAddress"]
compose("up", "-d", "--no-deps", "--no-recreate", "--scale", "api=" + str(len(originals) + 1), "api")
wait_api(base_url, len(originals) + 1)
added = (set(api_ids()) - before).pop()
slot = next(row["svname"] for row in servers() if row.get("addr", "").split(":")[0] == old_ip)
runtime("set server messenger/" + slot + " state drain")
deadline = time.monotonic() + 8
while time.monotonic() < deadline:
active = next(row for row in servers() if row["svname"] == slot)
if int(active["scur"]) == 0:
break
time.sleep(.1)
else:
raise RuntimeError("Backend did not drain")
docker("stop", "--time", "8", old)
docker("rm", old)
runtime("set server messenger/" + slot + " state ready")
wait_api(base_url, len(originals))
records.append({"old_container": old, "old_instance": old_alias,
"old_image": old_info["Image"], "new_container": added,
"new_instance": alias(added), "new_image": inspect(added)["Image"]})
return records
+20
View File
@@ -0,0 +1,20 @@
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
def compose(*args, timeout=90):
result = subprocess.run([str(ROOT / "scripts/compose.sh"), *args], cwd=ROOT,
text=True, capture_output=True, check=True, timeout=timeout)
return result.stdout.strip()
def sql(query):
return compose("exec", "-T", "postgres", "psql", "-X", "-U", "messenger", "-d", "messenger", "-Atc", query)
def redis(*args):
return compose("exec", "-T", "redis", "redis-cli", "--raw", *args)
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Additional black-box checks for the Lab2 authentication boundary."""
import argparse
import base64
import hashlib
import sys
import time
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, check, run # noqa: E402
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--check-expiry", action="store_true")
args = parser.parse_args()
client = Client(args.base_url)
username = "student_" + uuid.uuid4().hex[:12]
password = "Длинный пароль с двоеточием: " + uuid.uuid4().hex
registration = {"username": username, "display_name": "Проверка Lab2", "password": password}
user = client.call("POST", "/api/v1/users", 201, body=registration, schema="User")["json"]
check("password" not in user and "password_hash" not in user, "password leaked in User")
client.call("POST", "/api/v1/users", 409, body=registration)
client.call("POST", "/api/v1/users", 400, body={**registration, "unexpected": True})
client.call("POST", "/api/v1/users", 400, body={**registration, "username": username + "\n"})
client.call("POST", "/api/v1/users", 400, body={**registration, "password": "short"})
client.call("POST", "/api/v1/users", 400, raw=b'{"username":',
headers={"Content-Type": "application/json"})
client.call("POST", "/api/v1/users", 400, raw=b'{}',
headers={"Content-Type": "text/plain"})
def basic(secret):
encoded = base64.b64encode((username + ":" + secret).encode("utf-8")).decode("ascii")
return {"Authorization": "Basic " + encoded}
client.call("POST", "/api/v1/auth/sessions", 401, headers=basic("wrong password"))
client.call("POST", "/api/v1/auth/sessions", 400, headers=basic(password), body={})
session = client.call("POST", "/api/v1/auth/sessions", 201,
headers=basic(password), schema="Session")["json"]
token = session["token"]
check(token != password and username not in token, "token contains credentials")
client.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": user["id"]})
client.call("GET", "/api/v1/users/me", 401, headers=basic(password))
actor = {"id": user["id"], "token": token}
me = client.call("GET", "/api/v1/users/me", actor=actor, schema="User")["json"]
check(me == user, "Bearer session resolved to a different user")
client.call("POST", "/api/v1/chats", 400, actor=actor,
body={"title": "Bad members", "member_ids": [user["id"], str(uuid.uuid4())]})
if args.check_expiry:
from compose_helpers import redis
key = "messenger:session:" + hashlib.sha256(token.encode("ascii")).hexdigest()
check(0 < int(redis("PTTL", key)) <= 2000, "short-TTL session missing cache expiry")
time.sleep(3)
client.call("GET", "/api/v1/users/me", 401, actor=actor)
check(redis("EXISTS", key) == "0", "expired session remained in Redis")
print("PASS: TTL=2 expires in PostgreSQL authentication and Redis cache")
else:
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=actor)
client.call("GET", "/api/v1/users/me", 401, actor=actor)
print("PASS: Lab2 password, Basic, Bearer, input validation and session lifecycle")
if __name__ == "__main__":
run(main)
+100
View File
@@ -0,0 +1,100 @@
"""Cross-replica message retries, authorization, expiry and transaction rollback."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import json
import time
import uuid
from compose_helpers import ROOT, compose, sql
from client import Client, check, run
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://127.0.0.1:18080")
args = parser.parse_args()
c = Client(args.base_url)
alice, bob, eve, chat = c.bootstrap()
path = "/api/v1/chats/" + chat["id"] + "/messages"
key = uuid.uuid4().hex
checks = []
instances = {c.call("GET", "/api/v1/users/me", actor=alice, schema="User")["headers"]["X-Instance-Id"] for _ in range(30)}
containers = compose("ps", "-q", "api").splitlines()
check(len(instances) >= 2 and len(containers) >= 2, "two real API processes must be available")
checks.append("one session served by at least two API processes")
for invalid in ["", "bad key", "a" * 129, "a,b"]:
c.call("POST", path, 400, actor=alice, body={"text": "invalid"}, headers={"Idempotency-Key": invalid})
c.call("POST", path, 400, actor=alice, body={"text": "missing"})
c.call("POST", path, 401, body={"text": "anonymous"}, headers={"Idempotency-Key": key})
def submit(number):
local = Client(args.base_url)
body = {"text": "Одно сообщение 👋", "attachment_ids": []} if number % 2 else {"text": "Одно сообщение 👋"}
return local.call("POST", path, 201, actor=alice, body=body,
headers={"Idempotency-Key": key}, schema="Message")
with ThreadPoolExecutor(max_workers=16) as pool:
results = list(pool.map(submit, range(32)))
message = results[0]["json"]
check(all(result["json"] == message for result in results), "concurrent replay changed Message")
replay_instances = sorted({result["headers"]["X-Instance-Id"] for result in results})
check(len(replay_instances) >= 2, "replay did not pass through different API processes")
count = int(sql("SELECT count(*) FROM messages WHERE chat_id = '" + chat["id"] + "';"))
check(count == 1, "same key created duplicate message")
checks.append("32 concurrent requests across replicas create one message; absent attachments equals []")
c.call("POST", path, 409, actor=alice, body={"text": "Different"},
headers={"Idempotency-Key": key})
c.call("POST", path, 404, actor=eve, body={"text": message["text"]},
headers={"Idempotency-Key": key})
second = c.message(bob, chat, message["text"], key=key)["json"]
check(second["id"] != message["id"], "key incorrectly shared between users")
other_chat = c.call("POST", "/api/v1/chats", 201, actor=alice,
body={"title": "Scope", "member_ids": [alice["id"]]}, schema="Chat")["json"]
third = c.message(alice, other_chat, message["text"], key=key)["json"]
check(third["id"] != message["id"], "key incorrectly shared between chats")
checks.append("changed body conflicts; user/chat scopes are independent; access rechecked")
remaining = float(sql("SELECT extract(epoch FROM expires_at - clock_timestamp()) FROM message_requests WHERE message_id = '" + message["id"] + "';"))
check(86300 < remaining <= 86400, "request retention is not 24 hours")
sql("UPDATE message_requests SET expires_at = now() - interval '1 second' WHERE message_id = '" + message["id"] + "';")
renewed = c.message(alice, chat, "After expiry", key=key)["json"]
check(renewed["id"] != message["id"], "expired key cannot be reused")
checks.append("24-hour expiry stored in PostgreSQL; expired key can be reused")
name = "rollback_" + uuid.uuid4().hex
failed_key = uuid.uuid4().hex
sql(f"""
CREATE FUNCTION {name}() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NEW.request_key = '{failed_key}' THEN RAISE EXCEPTION 'injected request failure'; END IF;
RETURN NEW;
END $$;
CREATE TRIGGER {name} BEFORE INSERT ON message_requests FOR EACH ROW EXECUTE FUNCTION {name}();
""")
before = int(sql("SELECT count(*) FROM messages WHERE chat_id = '" + chat["id"] + "';"))
try:
c.call("POST", path, 503, actor=alice, body={"text": "Atomic retry"},
headers={"Idempotency-Key": failed_key})
after = int(sql("SELECT count(*) FROM messages WHERE chat_id = '" + chat["id"] + "';"))
check(before == after, "failed idempotency record left a message committed")
finally:
sql(f"DROP TRIGGER {name} ON message_requests; DROP FUNCTION {name}();")
c.message(alice, chat, "Atomic retry", key=failed_key)
checks.append("5xx rolls back message and key together; retry succeeds")
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
c.call("POST", path, 401, actor=alice, body={"text": "Atomic retry"},
headers={"Idempotency-Key": failed_key})
checks.append("revoked token cannot replay an existing result")
evidence = {"verified_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"instances": sorted(instances), "replay_instances": replay_instances,
"api_containers": containers, "checks": checks}
(ROOT / "evidence" / "idempotency.json").write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n")
print(json.dumps(evidence, ensure_ascii=False, indent=2))
if __name__ == "__main__":
run(main)
+42
View File
@@ -0,0 +1,42 @@
"""Run idempotency checks with and without SQL batching, then test short sessions."""
import argparse
import json
import os
import subprocess
import sys
from pathlib import Path
from cluster import recreate, wait_api
from compose_helpers import ROOT
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://127.0.0.1:18080")
parser.add_argument("--expiry", action="store_true")
args = parser.parse_args()
try:
if args.expiry:
environment = dict(os.environ, SESSION_TTL_SECONDS="2")
subprocess.run([str(ROOT / "scripts/compose.sh"), "up", "-d", "--no-deps", "--force-recreate", "api"],
env=environment, check=True, timeout=90)
wait_api(args.base_url, 2)
subprocess.run([sys.executable, str(ROOT / "student-tests/lab2_tests.py"),
"--base-url", args.base_url, "--check-expiry"], check=True)
else:
for batching in (False, True):
recreate(batching=batching)
wait_api(args.base_url, 2)
subprocess.run([sys.executable, str(ROOT / "student-tests/lab3_tests.py"), "--base-url", args.base_url], check=True)
report = (ROOT / "evidence/idempotency.json").read_text()
suffix = "batched" if batching else "separate"
(ROOT / ("evidence/idempotency-" + suffix + ".json")).write_text(report)
finally:
environment = dict(os.environ, SESSION_TTL_SECONDS="3600", MESSAGE_BATCHING="true")
subprocess.run([str(ROOT / "scripts/compose.sh"), "up", "-d", "--no-deps", "--force-recreate", "api"],
env=environment, check=True, timeout=90)
wait_api(args.base_url, 2)
if __name__ == "__main__":
main()
+51
View File
@@ -0,0 +1,51 @@
"""Restart storage and processes, then replay the original request with the original token."""
import argparse
import json
import subprocess
import time
from cluster import inspect
from compose_helpers import ROOT, compose, sql
from client import Client, check, run
import uuid
def state():
result = {}
for service in ("postgres", "redis", "api", "lb"):
result[service] = [{"container": row["Id"], "started_at": row["State"]["StartedAt"],
"volumes": [mount["Name"] for mount in row["Mounts"] if mount["Type"] == "volume"]}
for row in (inspect(container) for container in compose("ps", "-q", service).splitlines())]
return result
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://127.0.0.1:18080")
args = parser.parse_args()
c = Client(args.base_url)
alice, bob, eve, chat = c.bootstrap()
key = uuid.uuid4().hex
original = c.message(alice, chat, "Persistent request " + key, key=key)["json"]
before = state()
subprocess.run([str(ROOT / "scripts/restart.sh")], check=True, timeout=90, stdout=subprocess.DEVNULL)
after = state()
for service in before:
check({row["started_at"] for row in before[service]} != {row["started_at"] for row in after[service]},
service + " was not restarted")
check(before["postgres"][0]["volumes"] == after["postgres"][0]["volumes"], "database volume changed")
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
replay = c.message(alice, chat, original["text"], key=key)["json"]
check(replay == original, "original key/token did not replay after full restart")
check(sql("SELECT count(*) FROM messages WHERE chat_id = '" + chat["id"] + "';") == "1", "restart replay duplicated message")
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
c.call("GET", "/api/v1/users/me", 401, actor=alice)
report = {"verified_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"before": before, "after": after, "same_token": True, "same_message": True,
"replay_without_duplicates": True, "logout_status": 401}
(ROOT / "evidence/persistence.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
print("PASS: all services restarted, original token and key replayed, one message, logout 401")
if __name__ == "__main__":
run(main)
+336
View File
@@ -0,0 +1,336 @@
"""Track 1: fixed/growing API budgets, saturation curves and SQL batching."""
import argparse
import csv
import gzip
import hashlib
import json
import statistics
import time
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from cluster import api_ids, counters, counter_delta, docker, recreate, wait_api, inspect, servers
from compose_helpers import ROOT, compose, sql
from client import Client, check, run
from traffic import traffic, public_report
def median_row(rows):
return {
"rps": round(statistics.median(row["successful_rps"] for row in rows), 3),
"p95_ms": round(statistics.median(row["successful_latency_ms"]["p95"] for row in rows), 3),
"error_ratio": round(statistics.median(row["error_ratio"] for row in rows), 6),
"failed_requests_total": sum(row["failed_requests"] for row in rows),
"error_ratio_max": max(row["error_ratio"] for row in rows),
"rps_min": min(row["successful_rps"] for row in rows),
"rps_max": max(row["successful_rps"] for row in rows),
}
def summarize(evidence):
for configuration in evidence["configurations"]:
label = configuration["series"] + "-" + str(configuration["replicas"])
for concurrency in configuration["curves"]:
configuration["curves"][concurrency] = median_row([row for row in evidence["runs"] if row["label"] == label and row["concurrency"] == int(concurrency)])
evidence["batching_comparison"] = {label: median_row([row for row in evidence["runs"] if row["label"] == label]) for label in ("separate", "batched")}
evidence["database_capacity_comparison"] = {label: median_row([row for row in evidence["runs"] if row["label"] == "postgres-" + label]) for label in ("half_cpu", "one_cpu")}
def make_chart(evidence):
figure, axes = plt.subplots(1, 3, figsize=(15, 4.5))
for series, color in (("fixed", "#436b4f"), ("growing", "#b37b24")):
selected = [row for row in evidence["configurations"] if row["series"] == series]
for concurrency, style in ((4, ":"), (16, "--"), (64, "-")):
ys = [row["curves"][str(concurrency)]["rps"] for row in selected]
axes[0].plot([row["replicas"] for row in selected], ys, marker="o",
linestyle=style, color=color, label=f"{series}, C={concurrency}")
row = selected[-1]
xs = [int(value) for value in row["curves"]]
axes[1].plot(xs, [row["curves"][str(value)]["rps"] for value in xs],
marker="o", color=color, label=f"{series}, 4 replicas")
axes[2].plot(xs, [row["curves"][str(value)]["p95_ms"] for value in xs],
marker="o", color=color, label=f"{series}, 4 replicas")
axes[0].set(xlabel="API replicas", ylabel="Successful requests/s", title="Fixed vs growing API budget", xticks=[1, 2, 4])
axes[1].set(xlabel="Concurrent clients", ylabel="Successful requests/s", title="Throughput saturation")
axes[2].set(xlabel="Concurrent clients", ylabel="Successful latency p95, ms", title="Queueing cost")
for axis in axes:
axis.grid(alpha=.2)
axis.legend(fontsize=8)
figure.tight_layout()
figure.savefig(ROOT / "evidence/scaling.png", dpi=160)
figure.savefig(ROOT / "evidence/scaling.svg")
plt.close(figure)
def write_report(evidence):
table = []
for row in evidence["configurations"]:
for concurrency, measured in row["curves"].items():
table.append("| " + " | ".join(str(value) for value in
(row["series"], row["replicas"], row["total_api_cpus"], row["total_api_memory_mib"],
concurrency, measured["rps"], measured["p95_ms"], measured["error_ratio"], measured["failed_requests_total"])) + " |")
comparison = evidence["batching_comparison"]
before, after = comparison["separate"], comparison["batched"]
gain = (after["rps"] / before["rps"] - 1) * 100
recovery = evidence["database_capacity_comparison"]
db_gain = (recovery["one_cpu"]["rps"] / recovery["half_cpu"]["rps"] - 1) * 100
one = next(row for row in evidence["configurations"] if row["series"] == "growing" and row["replicas"] == 1)
low, high = one["curves"]["16"], one["curves"]["64"]
throughput_change = (high["rps"] / low["rps"] - 1) * 100
base_runs = [row for row in evidence["runs"] if row["label"] == "growing-1" and row["concurrency"] == 64]
cpu = {service: statistics.mean(sum(item["used_cpu_cores"] for item in row["resources"] if item["service"] == service) for row in base_runs) for service in ("api", "postgres", "lb")}
statuses = {}
for row in evidence["runs"]:
for status, count in row["status_counts"].items():
if status not in ("200", "201"):
statuses[status] = statuses.get(status, 0) + count
text = f"""# Масштабирование API
Проверено: {evidence['verified_at']}. Трек 1, Lab3.
## Гипотеза
Несколько API при одном суммарном бюджете CPU/RAM не обязаны быть быстрее одного.
При увеличении суммарного бюджета предел задаётся общей БД, балансировщиком, пулами
соединений или клиентом. Объединение последовательных SQL-команд уменьшает число
обменов API с PostgreSQL.
## Запуск
make up
make research-grade5
Исходные результаты: evidence/scaling.json.
Данные каждого HTTP-запроса: evidence/scaling-requests.csv.gz.
Графики: evidence/scaling.png и evidence/scaling.svg.
## Методика
Один Docker Desktop на macOS, {evidence['host']['cpus']} виртуальных CPU,
{round(evidence['host']['memory_bytes'] / 1024**3, 2)} GiB RAM.
Основные версии и ограничения контейнеров записаны в JSON.
Нагрузка: 50% чтений первой страницы из 50 сообщений, 50% отправок новых сообщений.
Одна действующая сессия, отдельный чат каждого замера, 250 начальных сообщений.
Регистрация, Argon2id и подготовка набора не входят в измерение.
Клиент использует постоянные HTTP/1.1-соединения, без повторов запросов.
Неподтверждённая запись могла попасть в БД, поэтому RPS означает успешные HTTP-ответы.
Латентность всех попыток и успешных ответов записана отдельно.
Полное время учитывает завершение начатых запросов и сбор наблюдений.
Медиана доли ошибок может быть нулевой при сбое в одном из трёх прогонов,
поэтому отдельно приведено суммарное число ошибок и диапазон RPS.
Серия fixed: всего 1 CPU и 768 MiB для API, делённые между 1/2/4 репликами.
Серия growing: каждой API даётся 1 CPU и 384 MiB.
БД: 0.5 CPU, 512 MiB; HAProxy: 0.5 CPU, 96 MiB; Redis: 0.25 CPU, 96 MiB.
Пул Npgsql: 20 соединений на реплику, суммарно 20/40/80.
Есть отдельная проверка увеличения CPU PostgreSQL до 1.
Перед конфигурацией прогрев 3 секунды, перед каждой concurrency ещё 2 секунды.
Concurrency: 4/16/64. Каждая точка: {evidence['repeats']} прогона по
{evidence['seconds_per_run']} секунд, приведены медианы.
Порядок concurrency чередуется между конфигурациями; варианты batching чередуются.
CPU и throttling измерены по cgroup cpu.stat до/после прогона. Это окно включает
накладные расходы сбора счётчиков. RAM отражает memory.current в конце окна,
а не исторический пик. Для каждого прогона есть успешные RPS, ошибки, p50/p95/p99,
распределение реплик и счётчики HAProxy/БД.
## Результаты
| Серия | Реплики | CPU API всего | MiB API всего | Клиенты | RPS | p95 ms | Медиана доли ошибок | Ошибок всего |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
{chr(10).join(table)}
![Масштабирование](../evidence/scaling.png)
## Проверенные изменения
SQL-команды не меняют транзакционную границу: блокировка, проверка ключа,
запись сообщения и результата остаются согласованными. MESSAGE_BATCHING=false
отправляет команды отдельно; true объединяет пары команд в один сетевой обмен.
Конкурентная проверка обоих режимов входит в собственные тесты.
| Вариант | Медиана RPS | Диапазон RPS | p95 ms | Ошибок всего |
| --- | ---: | --- | ---: | ---: |
| Отдельные SQL-команды | {before['rps']} | {before['rps_min']} - {before['rps_max']} | {before['p95_ms']} | {before['failed_requests_total']} |
| SQL batching | {after['rps']} | {after['rps_min']} - {after['rps_max']} | {after['p95_ms']} | {after['failed_requests_total']} |
Изменение медианных RPS: {gain:+.1f}%. Эти значения относятся только к этому
профилю и конфигурации из JSON; это не универсальная оценка скорости.
Увеличение PostgreSQL с 0.5 до 1 CPU при четырёх API: изменение медианных RPS
{db_gain:+.1f}%. В JSON сохранены оба набора CPU/throttling и латентностей,
поэтому причинное объяснение можно проверить по ресурсным ограничениям.
## Анализ насыщения
У одной API в growing увеличение concurrency с 16 до 64 изменило медиану
RPS с {low['rps']} до {high['rps']} ({throughput_change:+.1f}%), а p95 вырос
с {low['p95_ms']} до {high['p95_ms']} ms. В этом профиле плато начинается
около {round(high['rps'] / 50) * 50} успешных запросов/с.
На этой точке среднее потребление CPU по окну cgroup: API {cpu['api']:.3f}
из 1, PostgreSQL {cpu['postgres']:.3f} из 0.5, HAProxy {cpu['lb']:.3f} из 0.5.
База близка к своей квоте, тогда как у API и LB остаётся запас. Дополнительный
эксперимент с 1 CPU PostgreSQL дал {recovery['one_cpu']['rps']} против
{recovery['half_cpu']['rps']} RPS при прежних четырёх API. Это подтверждает
существенное влияние общей БД в выбранной конфигурации.
Коды неуспешных попыток за всю серию: {statuses}; 0 означает отсутствие
полного HTTP-ответа. Ошибки на перегрузке не исключались из исходных данных.
Число SQL-соединений растёт вместе с репликами, поэтому здесь исследуется
полный эффект конфигурации API, а не изолированное действие числа процессов.
Насыщение оценивается по кривым RPS и p95 при увеличении concurrency.
Рост задержки без сопоставимого роста RPS означает накопление очереди.
Распределение использованных CPU, throttling, очередей HAProxy и активных
соединений PostgreSQL сохранено по каждому прогону. Высокая утилизация БД
при свободном CPU API указывает на общий предел хранилища; загруженный API
при свободной БД указывает на ограничение API.
## Ограничения
Closed-loop генератор замедляет поступление запросов при росте задержки
и имеет coordinated omission. Клиент работает на том же физическом компьютере.
Не измерены производственные arrival rates, сетевые задержки между узлами
и предел отдельного выделенного генератора. Приведённые числа не являются
заявлением о максимальной производительности сервера.
Таблицы растут между прогонами, buffers прогреты; это влияет на сравнение.
Один LB, PostgreSQL и один Docker-host остаются точками отказа.
Redis является восстанавливаемым кэшем; сессии проверяются в PostgreSQL.
Добавление API не обеспечивает отказоустойчивость узла или базы.
## Источники
- https://www.haproxy.com/documentation/haproxy-configuration-tutorials/reliability/health-checks/
- https://www.haproxy.com/documentation/haproxy-configuration-tutorials/proxying-essentials/dns-resolution/
- https://www.npgsql.org/doc/performance.html
"""
(ROOT / "docs").mkdir(exist_ok=True)
(ROOT / "docs/SCALING.md").write_text(text)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://127.0.0.1:18080")
parser.add_argument("--seconds", type=int, default=8)
parser.add_argument("--repeats", type=int, default=3)
args = parser.parse_args()
check(args.seconds >= 5 and args.repeats >= 2, "use at least 5 seconds and two repeats")
wait_api(args.base_url, 2)
c = Client(args.base_url, timeout=20)
actor = c.user("scaling")
host = json.loads(docker("info", "--format", '{{json .}}'))
evidence = {"verified_at": "", "track": 1, "seconds_per_run": args.seconds, "repeats": args.repeats,
"host": {"cpus": host["NCPU"], "memory_bytes": host["MemTotal"],
"docker_version": host["ServerVersion"], "os": host["OperatingSystem"]},
"configurations": [], "runs": []}
evidence["source_sha256"] = hashlib.sha256(b"".join(path.read_bytes() for path in sorted((ROOT / "src").rglob("*.cs")) if "obj" not in path.parts)).hexdigest()
pg = compose("ps", "-q", "postgres")
run_number = 0
raw_path = ROOT / "evidence/scaling-requests.csv.gz"
def fixture():
chat = c.call("POST", "/api/v1/chats", 201, actor=actor,
body={"title": "Scaling " + str(time.time_ns()), "member_ids": [actor["id"]]}, schema="Chat")["json"]
sql("INSERT INTO messages(id, chat_id, sender_id, text, created_at) SELECT md5('" + chat["id"] + ":' || n::text)::uuid, '" + chat["id"] + "', '" + actor["id"] + "', 'fixture ' || n, now() + n * interval '1 microsecond' FROM generate_series(1,250) n;")
return chat
def measured(label, concurrency):
nonlocal run_number
run_number += 1
chat = fixture()
before = counters()
begin = time.monotonic()
def observe():
return {
"postgres_activity": json.loads(sql("SELECT coalesce(json_agg(t), '[]') FROM (SELECT state, wait_event_type, count(*) FROM pg_stat_activity WHERE application_name = 'messenger-api' GROUP BY state, wait_event_type) t;")),
"lb_queues": [{key: row[key] for key in ("svname", "status", "qcur", "scur", "qmax")} for row in servers() if row["addr"]]
}
result = traffic(args.base_url, actor, chat, args.seconds, concurrency, observer=observe)
check(bool(result["observations"]) and all("error" not in item for item in result["observations"]), "resource observer failed")
after = counters()
result["resources"] = counter_delta(before, after, time.monotonic() - begin)
result["run"] = run_number
result["label"] = label
result["postgres_activity"] = json.loads(sql("SELECT coalesce(json_agg(t), '[]') FROM (SELECT state, wait_event_type, count(*) FROM pg_stat_activity WHERE application_name = 'messenger-api' GROUP BY state, wait_event_type) t;"))
result["lb_queues"] = [] # Filled from the runtime API below without request bodies.
result["lb_queues"] = [{key: row[key] for key in ("svname", "status", "qcur", "qmax", "qtime_max")} for row in servers() if row["addr"]]
for sample in result["_samples"]:
raw.writerow((run_number, label, *sample))
report = public_report(result)
evidence["runs"].append(report)
print(f"{label}, C={concurrency}, trial={run_number}: {report['successful_rps']} RPS, p95={report['successful_latency_ms']['p95']} ms, errors={report['failed_requests']}", flush=True)
(ROOT / "evidence/scaling-progress.json").write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n")
check(result["successful_requests"] > 0, "no successful requests")
return report
def configure(replicas, cpus, memory, batching=True, database_cpus=.5):
docker("update", "--cpus", str(database_cpus), pg)
recreate(replicas, cpus, memory, batching=batching)
wait_api(args.base_url, replicas)
actual = [inspect(container)["HostConfig"] for container in api_ids()]
check(len(actual) == replicas, "replica count differs from requested configuration")
check(all(item["NanoCpus"] == int(cpus * 1e9) and item["Memory"] == int(memory[:-1]) * 1024**2 for item in actual), "CPU/RAM limits differ from requested budget")
traffic(args.base_url, actor, fixture(), duration=3, concurrency=4)
try:
with gzip.open(raw_path, "wt", newline="") as destination:
raw = csv.writer(destination)
raw.writerow(("run", "configuration", "offset_seconds", "operation", "http_status", "latency_ms", "instance_id"))
for series in ("fixed", "growing"):
for replicas in (1, 2, 4):
cpu = 1 / replicas if series == "fixed" else 1
memory = 768 // replicas if series == "fixed" else 384
print(f"Configuring {series}: {replicas} API, {cpu} CPU/{memory} MiB each", flush=True)
configure(replicas, cpu, str(memory) + "m")
row = {"series": series, "replicas": replicas, "per_api_cpus": cpu,
"per_api_memory_mib": memory, "total_api_cpus": cpu * replicas,
"total_api_memory_mib": memory * replicas, "curves": {}}
order = (4, 16, 64) if replicas != 2 else (64, 16, 4)
for concurrency in order:
traffic(args.base_url, actor, fixture(), duration=2, concurrency=concurrency)
trials = [measured(series + "-" + str(replicas), concurrency) for _ in range(args.repeats)]
row["curves"][str(concurrency)] = median_row(trials)
row["curves"] = dict(sorted(row["curves"].items(), key=lambda item: int(item[0])))
evidence["configurations"].append(row)
comparison = {"separate": [], "batched": []}
for trial in range(args.repeats):
for batching in ((False, True) if trial % 2 == 0 else (True, False)):
configure(2, 1, "384m", batching=batching)
label = "batched" if batching else "separate"
comparison[label].append(measured(label, 16))
evidence["batching_comparison"] = {key: median_row(rows) for key, rows in comparison.items()}
comparison = {"half_cpu": [], "one_cpu": []}
for trial in range(args.repeats):
for label, cpu in (("half_cpu", .5), ("one_cpu", 1)) if trial % 2 == 0 else (("one_cpu", 1), ("half_cpu", .5)):
configure(4, 1, "384m", database_cpus=cpu)
comparison[label].append(measured("postgres-" + label, 64))
evidence["database_capacity_comparison"] = {key: median_row(rows) for key, rows in comparison.items()}
finally:
docker("update", "--cpus", ".5", pg)
recreate()
wait_api(args.base_url, 2)
evidence["verified_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
evidence["confirmed_improvements"] = []
if evidence["batching_comparison"]["batched"]["rps"] >= 1.05 * evidence["batching_comparison"]["separate"]["rps"]:
evidence["confirmed_improvements"].append("SQL command batching increased median successful RPS")
if evidence["database_capacity_comparison"]["one_cpu"]["rps"] >= 1.05 * evidence["database_capacity_comparison"]["half_cpu"]["rps"]:
evidence["confirmed_improvements"].append("Additional PostgreSQL CPU increased median successful RPS")
check(evidence["confirmed_improvements"], "no throughput improvement confirmed; inspect measurements")
(ROOT / "evidence/scaling.json").write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n")
make_chart(evidence)
write_report(evidence)
print("PASS: scaling research saved to evidence/scaling.json and docs/SCALING.md")
if __name__ == "__main__":
run(main)
+59
View File
@@ -0,0 +1,59 @@
"""Reactions are durable, private and idempotent across the actual API replicas."""
import argparse
import json
import uuid
from compose_helpers import sql
from client import Client, check, run
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://127.0.0.1:18080")
args = parser.parse_args()
client = Client(args.base_url)
alice, bob, eve, chat = client.bootstrap()
message = client.call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, actor=alice,
body={"text": "Реакции через разные API"}, headers={"Idempotency-Key": str(uuid.uuid4())}, schema="Message")["json"]
route = f"/api/ui/chats/{chat['id']}/messages/{message['id']}/reactions/like"
summary = f"/api/ui/chats/{chat['id']}/reactions?message_ids={message['id']}"
def items(actor):
return json.loads(client.call("GET", summary, actor=actor)["bytes"])["items"]
client.call("PUT", route, 401)
client.call("GET", summary, 401)
client.call("PUT", route, 404, actor=eve)
client.call("GET", summary, 404, actor=eve)
instances = set()
for _ in range(8):
response = client.call("PUT", route, 204, actor=alice)
instances.add(response["headers"]["X-Instance-Id"])
check(len(instances) >= 2, "writes did not reach two API instances")
check(items(alice)[0]["count"] == 1 and items(alice)[0]["mine"], "repeated PUT counted twice")
check(not items(bob)[0]["mine"], "mine flag leaked between users")
client.call("PUT", route, 204, actor=bob)
check(items(alice)[0]["count"] == 2, "two users did not aggregate")
check(int(sql(f"SELECT count(*) FROM message_reactions WHERE message_id = '{message['id']}';")) == 2,
"reactions were not persisted")
client.call("DELETE", route, 204, actor=alice)
client.call("DELETE", route, 204, actor=alice)
check(items(alice)[0]["count"] == 1 and not items(alice)[0]["mine"], "DELETE affected another user's reaction")
client.call("PUT", route.rsplit('/', 1)[0] + "/invalid", 400, actor=alice)
missing = route.replace(message["id"], str(uuid.uuid4()))
client.call("PUT", missing, 404, actor=alice)
other = client.call("POST", "/api/v1/chats", 201, actor=alice,
body={"title": "Другая комната", "member_ids": [alice["id"]]}, schema="Chat")["json"]
client.call("PUT", route.replace(chat["id"], other["id"]), 404, actor=alice)
mixed = json.loads(client.call("GET", summary.replace(chat["id"], other["id"]), actor=alice)["bytes"])
check(mixed["items"] == [], "foreign message reaction escaped its chat")
client.call("GET", summary.rsplit('=',1)[0] + '=bad', 400, actor=alice)
client.call("GET", "/api/ui/cluster", 401)
cluster = json.loads(client.call("GET", "/api/ui/cluster", actor=alice)["bytes"])
check(cluster["redis_available"] and cluster["postgres_available"], "cluster dependency snapshot failed")
check(sum(node["ready"] for node in cluster["instances"]) >= 2, "missing actual cluster heartbeats")
print("PASS: two-replica reaction writes, idempotency, user isolation, chat privacy, PostgreSQL persistence, cluster heartbeat")
if __name__ == "__main__":
run(main)
+135
View File
@@ -0,0 +1,135 @@
"""Persistent HTTP/1.1 workers; closed-loop measurements include client overhead."""
from concurrent.futures import ThreadPoolExecutor
from collections import Counter
import http.client
import json
import math
import threading
import time
from urllib.parse import urlsplit
import uuid
def percentile(values, fraction):
return round(sorted(values)[max(0, math.ceil(len(values) * fraction) - 1)], 3) if values else None
def traffic(base_url, actor, chat, duration=10, concurrency=16, action=None, retry_uncertain=False, observer=None):
address = urlsplit(base_url)
barrier = threading.Barrier(concurrency + 1)
actions = []
action_error = []
observations = []
sample_stop = threading.Event()
started = 0
def worker(number):
connection = http.client.HTTPConnection(address.hostname, address.port, timeout=3)
records, confirmed = [], []
pending = None
index = number
barrier.wait()
deadline = started + duration
try:
while time.monotonic() < deadline:
operation = "write" if pending or index % 2 else "read"
headers = {"Authorization": "Bearer " + actor["token"], "Content-Type": "application/json"}
path = "/api/v1/chats/" + chat["id"] + "/messages"
payload = None
if operation == "write":
if pending is None:
pending = (uuid.uuid4().hex, uuid.uuid4().hex)
headers["Idempotency-Key"] = pending[0]
payload = json.dumps({"text": pending[1]}).encode()
else:
path += "?limit=50"
begin = time.monotonic()
status, instance, message_id = 0, "", None
try:
connection.request("POST" if operation == "write" else "GET", path, body=payload, headers=headers)
response = connection.getresponse()
status = response.status
instance = response.getheader("X-Instance-Id", "")
content = response.read()
if status == (201 if operation == "write" else 200):
if operation == "write":
message_id = json.loads(content)["id"]
confirmed.append((message_id, pending[1]))
pending = None
else:
connection.close()
except (OSError, http.client.HTTPException, ValueError):
connection.close()
status = 0
elapsed = (time.monotonic() - begin) * 1000
records.append((round(begin - started, 6), operation, status, round(elapsed, 4), instance))
if not retry_uncertain:
pending = None
index += 1
finally:
connection.close()
return records, confirmed
def run_action():
try:
time.sleep(2)
begin = time.monotonic()
result = action()
actions.append({"started_after_seconds": begin - started,
"finished_after_seconds": time.monotonic() - started, "result": result})
except Exception as error:
action_error.append(error)
def sample():
while not sample_stop.wait(2):
try:
observations.append({"offset_seconds": round(time.monotonic() - started, 3), "data": observer()})
except Exception as error:
observations.append({"error": type(error).__name__})
with ThreadPoolExecutor(max_workers=concurrency) as pool:
futures = [pool.submit(worker, n) for n in range(concurrency)]
started = time.monotonic()
barrier.wait()
sampler = threading.Thread(target=sample) if observer else None
if sampler:
sampler.start()
thread = threading.Thread(target=run_action) if action else None
if thread:
thread.start()
try:
outcomes = [future.result() for future in futures]
finally:
sample_stop.set()
if sampler:
sampler.join()
if thread:
thread.join()
ended = time.monotonic()
if action_error:
raise action_error[0]
samples = sorted([row for records, _ in outcomes for row in records])
successes = [row for row in samples if row[2] == (201 if row[1] == "write" else 200)]
failed = [row for row in samples if row[2] != (201 if row[1] == "write" else 200)]
latencies = [row[3] for row in successes]
report = {
"duration_seconds": round(ended - started, 4), "requested_seconds": duration,
"concurrency": concurrency, "successful_requests": len(successes), "failed_requests": len(failed),
"successful_rps": round(len(successes) / (ended - started), 3),
"error_ratio": round(len(failed) / len(samples), 6) if samples else None,
"successful_latency_ms": {name: percentile(latencies, fraction)
for name, fraction in (("p50", .5), ("p95", .95), ("p99", .99))},
"all_attempt_latency_ms": {name: percentile([row[3] for row in samples], fraction)
for name, fraction in (("p50", .5), ("p95", .95), ("p99", .99))},
"status_counts": dict(Counter(str(row[2]) for row in samples)),
"instance_counts": dict(Counter(row[4] for row in successes)),
"actions": actions,
"observations": observations,
"_samples": samples,
"_confirmed": [row for _, confirmations in outcomes for row in confirmations],
}
return report
def public_report(report):
return {key: value for key, value in report.items() if not key.startswith("_")}
+66
View File
@@ -0,0 +1,66 @@
"""UI history must page backwards while the required API keeps ascending semantics."""
import argparse
import json
import uuid
from compose_helpers import sql
from client import Client, check, run, shape
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
args = parser.parse_args()
client = Client(args.base_url)
alice, bob, eve, chat = client.bootstrap()
previews_path = "/api/ui/chats?limit=1"
client.call("GET", previews_path, 401)
empty_previews = json.loads(client.call("GET", previews_path, actor=eve)["bytes"])
check(not any(item["id"] == chat["id"] for item in empty_previews["items"]), "UI chat preview leaked a private chat")
initial = json.loads(client.call("GET", previews_path, actor=alice)["bytes"])
check(initial["items"][0]["last_message"] is None, "empty chat has a phantom preview")
path = "/api/ui/chats/" + chat["id"] + "/messages"
client.call("GET", path, 401)
client.call("GET", path, 404, actor=eve)
members_path = "/api/ui/chats/" + chat["id"] + "/members"
client.call("GET", members_path, 401)
client.call("GET", members_path, 404, actor=eve)
members = json.loads(client.call("GET", members_path, actor=bob)["bytes"])["items"]
check({user["id"] for user in members} == {alice["id"], bob["id"]}, "wrong UI member list")
for member in members:
shape(member, "User") # rejects any password/hash fields in this projection
prefix = uuid.uuid4().hex[:20]
# Equal timestamps exercise the UUID tie-breaker in both directions.
sql(f"""
INSERT INTO messages(id, chat_id, sender_id, text, created_at)
SELECT ('{prefix}' || lpad(n::text, 12, '0'))::uuid,
'{chat['id']}'::uuid, '{alice['id']}'::uuid, 'UI pagination ' || n,
'2026-02-01T00:00:00Z'::timestamptz
FROM generate_series(1, 75) fixture(n);
""")
check(int(sql(f"SELECT count(*) FROM messages WHERE chat_id = '{chat['id']}';")) == 75, "UI fixture mismatch")
ascending = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=50", actor=alice, schema="MessagePage")["json"]
recent = client.call("GET", path + "?limit=50", actor=bob, schema="MessagePage")["json"]
older = client.call("GET", path + "?limit=50&cursor=" + recent["next_cursor"], actor=bob, schema="MessagePage")["json"]
previews = json.loads(client.call("GET", previews_path, actor=alice)["bytes"])
check(previews["items"][0]["last_message"] == recent["items"][0], "preview did not use the latest UUID for equal-time messages")
second_chat = client.call("POST", "/api/v1/chats", 201, actor=alice,
body={"title": "Preview pagination", "member_ids": [alice["id"]]}, schema="Chat")["json"]
first = json.loads(client.call("GET", previews_path, actor=alice)["bytes"])
second = json.loads(client.call("GET", previews_path + "&cursor=" + first["next_cursor"], actor=alice)["bytes"])
check({first["items"][0]["id"], second["items"][0]["id"]} == {chat["id"], second_chat["id"]}
and second["next_cursor"] is None, "chat preview pagination lost or repeated chats")
client.call("GET", previews_path + "&cursor=" + first["next_cursor"], 400, actor=bob)
client.call("GET", "/api/v1/chats?cursor=" + first["next_cursor"], 400, actor=alice)
check([item["id"] for item in ascending["items"]] == sorted(item["id"] for item in ascending["items"]), "required history changed order")
check([item["id"] for item in recent["items"]] == sorted((item["id"] for item in recent["items"]), reverse=True), "UI history is not newest first")
all_items = recent["items"] + older["items"]
check(len(all_items) == 75 and len({item["id"] for item in all_items}) == 75 and older["next_cursor"] is None,
"UI pagination lost or repeated equal-time messages")
client.call("GET", path + "?cursor=" + ascending["next_cursor"], 400, actor=alice)
client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?cursor=" + recent["next_cursor"], 400, actor=alice)
print("PASS: UI authentication, privacy, newest page, backwards pagination, cursor isolation; required API stays ascending")
if __name__ == "__main__":
run(main)
+296
View File
@@ -0,0 +1,296 @@
// Optional browser regression test. The application itself has no npm dependencies.
const { chromium, request } = require('playwright');
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const path = require('node:path');
const { randomUUID } = require('node:crypto');
const baseURL = process.env.MESSENGER_TEST_URL || 'http://localhost:18080';
const evidence = path.resolve(__dirname, '../evidence');
const results = { verified_at: new Date().toISOString(), checks: [] };
let browser, api;
const sessions = [];
async function call(method, route, body, actor) {
const response = await api.fetch(route, {
method, data: body,
headers: { ...(actor ? { Authorization: 'Bearer ' + actor.token } : {}), ...(method === 'POST' && route.endsWith('/messages') ? { 'Idempotency-Key': randomUUID() } : {}) }
});
assert(response.ok(), `${method} ${route}: HTTP ${response.status()}`);
return response.status() === 204 ? null : response.json();
}
async function account(suffix, name) {
const username = 'ui_' + suffix + '_' + randomUUID().slice(0, 8);
const password = randomUUID();
await call('POST', '/api/v1/users', { username, display_name: name, password });
const response = await api.post('/api/v1/auth/sessions', {
headers: { Authorization: 'Basic ' + Buffer.from(username + ':' + password).toString('base64') }
});
assert.equal(response.status(), 201);
const actor = await response.json();
sessions.push(actor);
return { ...actor, username, password };
}
async function login(page, actor) {
await page.goto(baseURL);
await page.locator('#login-username').fill(actor.username);
await page.locator('#login-password').fill(actor.password);
await page.locator('#login-form button[type=submit]').click();
await page.locator('#app-screen').waitFor({ state: 'visible' });
}
async function decodeVisibleImage(page, selector) {
await page.waitForFunction(selector => {
const img = document.querySelector(selector);
return img?.complete && img.naturalWidth > 0;
}, selector);
await page.locator(selector).evaluate(img => img.decode());
}
async function openHistory(page, chat) {
await page.getByRole('button', { name: new RegExp(chat.title) }).click();
await page.waitForFunction(() => document.querySelectorAll('article.message').length === 50);
await page.waitForFunction(() => [...document.querySelectorAll('.message-author')].some(e => e.textContent === 'Собеседник'));
await page.locator('#older-messages').click();
await page.waitForFunction(() => document.querySelectorAll('article.message').length === 75);
}
async function pollOnce(page, chat) {
await page.waitForResponse(r => r.url().includes(`/api/ui/chats/${chat.id}/messages?limit=50`) && r.status() === 200);
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
}
async function observeList(page) {
await page.evaluate(() => {
const list = document.querySelector('#message-list');
const first = list.querySelector('article');
const text = first.querySelector('.message-text').firstChild;
const selection = getSelection();
const range = document.createRange();
range.setStart(text, 0); range.setEnd(text, Math.min(10, text.length));
selection.removeAllRanges(); selection.addRange(range);
window.uiAudit = { first, selection: selection.toString(), added: 0, removed: 0, records: 0 };
window.uiAudit.observer = new MutationObserver(records => {
window.uiAudit.records += records.length;
for (const record of records) {
window.uiAudit.added += record.addedNodes.length;
window.uiAudit.removed += record.removedNodes.length;
}
});
window.uiAudit.observer.observe(list, { childList: true, subtree: true, characterData: true });
});
}
async function audit(page) {
return page.evaluate(() => ({
added: window.uiAudit.added, removed: window.uiAudit.removed, records: window.uiAudit.records,
sameNode: window.uiAudit.first === document.querySelector('#message-list article'),
selectionPreserved: getSelection().toString() === window.uiAudit.selection
}));
}
(async () => {
await fs.mkdir(evidence, { recursive: true });
api = await request.newContext({ baseURL, timeout: 15000 });
browser = await chromium.launch({
executablePath: process.env.MESSENGER_BROWSER_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
headless: true
});
const page = await browser.newPage({ viewport: { width: 1280, height: 850 }, deviceScaleFactor: 1 });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.goto(baseURL);
await page.locator('.spirit-svg').waitFor();
await page.screenshot({ path: path.join(evidence, 'ui-kolovertysh-login.png') });
await page.locator('#login-username').fill('mascot_preview');
await page.waitForFunction(() => document.querySelector('#mascot-stage').dataset.mood === 'looking');
await page.mouse.move(850, 400);
await page.waitForFunction(() => document.querySelector('#mascot-stage').style.getPropertyValue('--gaze-x') !== '');
await page.route('**/api/v1/auth/sessions', route => route.fulfill({ status: 401, contentType: 'application/json', body: JSON.stringify({error:{message:'Invalid credentials'}}) }));
await page.locator('#login-password').fill('invalid_preview');
await page.locator('#login-form button[type=submit]').click();
await page.locator('#auth-error-art').waitFor({ state: 'visible' });
assert.equal(await page.locator('#mascot-stage').getAttribute('data-mood'), 'error');
await page.unroute('**/api/v1/auth/sessions');
results.checks.push('mascot: input reaction, event-driven gaze, authentication-error illustration');
const mobile = await browser.newPage({ viewport: { width: 320, height: 844 }, deviceScaleFactor: 1 });
mobile.on('pageerror', error => errors.push(error.message));
await mobile.goto(baseURL);
await mobile.locator('#login-password').fill('preview_password');
await mobile.waitForFunction(() => document.querySelector('#mascot-stage').dataset.mood === 'private');
await mobile.waitForFunction(() => {
const m = getComputedStyle(document.querySelector('.spirit-hand-left')).transform;
return m !== 'none' && Number(m.match(/matrix\((.*)\)/)?.[1].split(',')[4]) > 20;
});
assert(await mobile.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth));
await mobile.screenshot({ path: path.join(evidence, 'ui-kolovertysh-mobile.png'), fullPage: true });
await mobile.locator('[data-password-toggle=login-password]').click();
assert.equal(await mobile.locator('#login-password').getAttribute('type'), 'text');
await mobile.emulateMedia({ reducedMotion: 'reduce' });
assert.equal(await mobile.locator('.spirit-motion').evaluate(e => getComputedStyle(e).animationName), 'none');
results.checks.push('mobile 320px: no horizontal overflow, private/revealed password, reduced motion');
await mobile.locator('#tab-register').click();
await mobile.locator('#register-password').fill('short');
await mobile.waitForFunction(() => document.querySelector('#mascot-stage').dataset.mood === 'short');
await mobile.locator('#register-password').fill('long_preview_password');
await mobile.waitForFunction(() => document.querySelector('#mascot-stage').dataset.mood === 'private');
await mobile.setViewportSize({ width: 390, height: 844 });
assert(await mobile.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth));
results.checks.push('registration: short-password/private states, 390px without overflow');
await mobile.close();
const alice = await account('alice', 'Проверка интерфейса');
const bob = await account('bob', 'Собеседник');
const chat = await call('POST', '/api/v1/chats', {
title: 'Проверка интерфейса ' + randomUUID().slice(0, 4), member_ids: [alice.user.id, bob.user.id]
}, alice);
const seeded = [];
const phrases = ['Привет! Проверяю обновлённый чат.', 'Теперь сообщения собраны аккуратнее.', 'Старую историю можно читать без скачков.', 'Да, и выделенный текст сохраняется.', 'Новые сообщения появляются внизу.', 'К ним можно перейти отдельной кнопкой.'];
for (let n = 0; n < 75; n++) {
seeded.push(await call('POST', `/api/v1/chats/${chat.id}/messages`, {
text: phrases[n % phrases.length] + (n % 10 === 0 ? ' Проверка длинного сообщения: строка должна переноситься внутри пузырька и оставаться читаемой на телефоне.' : '')
}, Math.floor(n / 3) % 2 ? bob : alice));
}
if (process.env.MESSENGER_BASELINE_APP) {
const baseline = await browser.newPage({ viewport: { width: 1280, height: 850 } });
await baseline.route('**/app.js', route => route.fulfill({ contentType: 'text/javascript', path: process.env.MESSENGER_BASELINE_APP }));
await login(baseline, alice); await openHistory(baseline, chat);
await observeList(baseline); await pollOnce(baseline, chat);
results.before = await audit(baseline);
assert(results.before.removed > 0 && !results.before.sameNode);
await baseline.locator("#logout").click();
await baseline.locator("#auth-screen").waitFor({ state: "visible" });
await baseline.close();
}
await page.route('**/api/ui/chats?limit=100', route => route.fulfill({ status: 503, contentType: 'application/json', body: JSON.stringify({error:{message:'Сервис временно недоступен'}}) }));
await login(page, alice);
await page.locator('#workspace-error').waitFor({state:'visible'});
await decodeVisibleImage(page, '#workspace-error img');
await page.screenshot({path:path.join(evidence,'ui-kolovertysh-error.png')});
await page.unroute('**/api/ui/chats?limit=100');
await page.locator('#retry-chats').click();
await page.locator('#welcome').waitFor({state:'visible'});
const chatRow = page.locator(`[data-chat-id="${chat.id}"]`);
await chatRow.waitFor();
assert.equal(await chatRow.locator('.chat-preview').textContent(), 'Вы: ' + seeded.at(-1).text);
assert.equal(await chatRow.locator('time').getAttribute('datetime'), seeded.at(-1).created_at);
const avatar = await chatRow.locator('.avatar svg').evaluate(e => e.outerHTML);
await page.locator('#refresh-chats').click();
await page.waitForFunction(() => !document.querySelector('#refresh-chats').classList.contains('is-loading'));
assert.equal(await chatRow.locator('.avatar svg').evaluate(e => e.outerHTML), avatar);
assert.equal(await chatRow.locator('.avatar svg').evaluate(e => getComputedStyle(e).stroke), 'none');
results.checks.push('chat previews: latest text and timestamp, deterministic SVG avatar survives refresh without inherited icon stroke');
assert(await page.locator('#workspace-error').isHidden());
assert.equal(await page.locator('#mascot-stage').evaluate(e => e.classList.contains('is-visible')), false);
results.checks.push('initial chat-list failure: illustrated retry state, successful recovery, hidden mascot paused');
const emptyChat = await call('POST', '/api/v1/chats', {title:'Пустой разговор ' + randomUUID().slice(0,4), member_ids:[alice.user.id]}, alice);
await page.locator('#refresh-chats').click();
await page.getByRole('button', {name:new RegExp(emptyChat.title)}).waitFor();
const messageRoute = `**/api/ui/chats/${emptyChat.id}/messages?limit=50`;
await page.route(messageRoute, route => route.fulfill({status:503,contentType:'application/json',body:JSON.stringify({error:{message:'Сервис временно недоступен'}})}));
await page.getByRole('button', {name:new RegExp(emptyChat.title)}).click();
await page.locator('#conversation-error').waitFor({state:'visible'});
assert(await page.locator('#empty-conversation').isHidden());
await page.unroute(messageRoute);
await page.locator('#retry-messages').click();
await page.locator('#empty-conversation').waitFor({state:'visible'});
assert(await page.locator('#conversation-error').isHidden());
await decodeVisibleImage(page, '#empty-conversation img');
await page.screenshot({path:path.join(evidence,'ui-kolovertysh-empty.png')});
results.checks.push('message-load failure does not look empty; retry recovers to illustrated empty conversation');
await page.reload();
await page.locator('#welcome').waitFor({state:'visible'});
await decodeVisibleImage(page, '.welcome-illustration');
await page.screenshot({ path: path.join(evidence, 'ui-illustration-welcome.png') });
await openHistory(page, chat);
const expected = [...seeded].sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id)).map(m => m.id);
assert.deepEqual(await page.locator('article.message').evaluateAll(nodes => nodes.map(n => n.dataset.messageId)), expected);
assert(await page.locator('article.message.grouped').count() > 0);
await observeList(page); await pollOnce(page, chat);
results.after = await audit(page);
assert.equal(results.after.records, 0, 'unchanged poll mutated message list');
assert(results.after.sameNode && results.after.selectionPreserved);
results.checks.push('75 messages across two pages: order, unique IDs, grouping');
results.checks.push('unchanged poll: zero message-list mutations, original node and selection preserved');
await page.locator('#message-scroll').evaluate(e => { e.scrollTop = 0; });
const beforeScroll = await page.locator('#message-scroll').evaluate(e => e.scrollTop);
const arrival = await call('POST', `/api/v1/chats/${chat.id}/messages`, { text: 'Новое сообщение пришло, пока вы читали историю.' }, bob);
await page.locator(`article[data-message-id="${arrival.id}"]`).waitFor();
assert.equal(await page.locator('#message-scroll').evaluate(e => e.scrollTop), beforeScroll);
await page.waitForFunction(() => document.querySelector('#jump-latest').textContent.includes('Новые сообщения: 1'));
assert((await audit(page)).sameNode && (await audit(page)).selectionPreserved);
await page.locator('#jump-latest').click();
await page.waitForFunction(() => document.querySelector('#jump-latest').hidden);
results.checks.push('incoming message: original nodes/selection/scroll preserved, new-message button returns to bottom');
await page.locator('#message-input').fill('Сообщение отправлено из браузера.');
await page.locator('#send-message').click();
await page.waitForFunction(() => document.querySelectorAll('article.message').length === 77);
assert.equal(await chatRow.locator('.chat-preview').textContent(), 'Вы: Сообщение отправлено из браузера.');
const ids = await page.locator('article.message').evaluateAll(nodes => nodes.map(n => n.dataset.messageId));
assert.equal(new Set(ids).size, ids.length);
await pollOnce(page, chat);
assert.equal(await page.locator('article.message').count(), 77);
results.checks.push('own send followed by poll: no duplicate messages');
const retryKeys = [];
const retryRoute = `**/api/v1/chats/${chat.id}/messages`;
await page.route(retryRoute, async route => {
retryKeys.push(route.request().headers()['idempotency-key']);
if (retryKeys.length === 1) {
const committed = await route.fetch();
assert.equal(committed.status(), 201);
await route.abort('failed');
} else await route.continue();
});
await page.locator('#message-input').fill('Повтор после потерянного ответа.');
await page.locator('#send-message').click();
await page.getByText('Ответ не получен. Повторите отправку: сообщение не продублируется.', {exact:true}).waitFor();
await page.locator('#send-message').click();
await page.waitForFunction(() => document.querySelector('#message-input').value === '');
await pollOnce(page, chat);
assert.equal(retryKeys.length, 2);
assert(retryKeys[0] && retryKeys[0] === retryKeys[1]);
assert.equal(await page.locator('article.message').count(), 78);
await page.unroute(retryRoute);
results.checks.push('lost response after COMMIT: manual retry preserves key and creates one message');
await page.locator('#toast').waitFor({ state: 'hidden' });
await page.locator('#message-scroll').evaluate(e => { e.scrollTop = e.scrollHeight; });
await page.locator('#conversation').evaluate(e => Promise.all(e.getAnimations({ subtree: true }).map(a => a.finished)));
await page.screenshot({ path: path.join(evidence, 'ui-optimized-chat.png') });
await page.setViewportSize({ width: 390, height: 844 });
await page.waitForFunction(() => document.documentElement.clientWidth === 390);
await page.locator('#message-scroll').evaluate(e => { e.scrollTop = e.scrollHeight; });
assert(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth));
await page.screenshot({ path: path.join(evidence, 'ui-optimized-chat-mobile.png') });
await page.locator('#show-members').click();
assert.equal(await page.locator('#members-list .avatar svg').count(), 2);
assert(await page.locator('#members-dialog').evaluate(e => e.scrollWidth <= e.clientWidth));
await page.locator('#members-dialog [data-close-dialog]').click();
results.checks.push('mobile conversation 390px: no horizontal overflow');
await page.locator('#back-to-chats').click();
await page.locator('#logout').click();
await page.locator('#auth-screen').waitFor({ state: 'visible' });
results.checks.push('welcome, empty-conversation and error illustrations decoded when shown');
assert.deepEqual(errors, []);
results.checks.push('no uncaught browser errors');
results.fixture = { chat_id: chat.id, messages: 78 };
await fs.writeFile(path.join(evidence, 'ui-optimization.json'), JSON.stringify(results, null, 2) + '\n');
console.log(JSON.stringify(results, null, 2));
})().catch(error => {
console.error(error.stack || error.message);
process.exitCode = 1;
}).finally(async () => {
for (const actor of sessions) {
try { await call('DELETE', '/api/v1/auth/sessions/current', undefined, actor); } catch {}
}
await browser?.close(); await api?.dispose();
});
+111
View File
@@ -0,0 +1,111 @@
// Integration test against the real cluster; includes a real, automatically restored container stop.
const { chromium, request } = require('playwright');
const assert = require('node:assert/strict');
const { randomUUID } = require('node:crypto');
const { spawn } = require('node:child_process');
const fs = require('node:fs/promises');
const path = require('node:path');
const baseURL = process.env.MESSENGER_TEST_URL || 'http://127.0.0.1:18080';
const evidence = path.resolve(__dirname, '../evidence');
const actors = [], errors = [], checks = [];
let api, browser, demo;
async function call(method, route, actor, data) {
const response = await api.fetch(route, {method, data,
headers:{...(actor ? {Authorization:'Bearer '+actor.token} : {}), ...(method==='POST' && route.endsWith('/messages') ? {'Idempotency-Key':randomUUID()} : {})}});
assert(response.ok(), `${method} ${route.split('?')[0]}: ${response.status()}`);
return response.status()===204 ? null : response.json();
}
async function actor(name) {
const username = 'show_' + randomUUID().replaceAll('-','').slice(0,16), password = randomUUID();
await call('POST','/api/v1/users',null,{username,password,display_name:name});
const response = await api.post('/api/v1/auth/sessions',{headers:{Authorization:'Basic '+Buffer.from(username+':'+password).toString('base64')}});
assert.equal(response.status(),201); const value=await response.json(); actors.push(value); return value;
}
async function pageFor(actor, chat) {
const page=await browser.newPage({viewport:{width:1440,height:1000}});
page.on('pageerror',error=>errors.push(error.message));
await page.addInitScript(session=>sessionStorage.setItem('n1k0der.session',JSON.stringify(session)),actor);
await page.goto(baseURL); await page.locator(`[data-chat-id="${chat.id}"]`).click();
await page.locator('article.message').first().waitFor(); return page;
}
const row=(page,id)=>page.locator(`article[data-message-id="${id}"]`);
(async()=>{
await fs.mkdir(evidence,{recursive:true});
api=await request.newContext({baseURL,timeout:15000});
browser=await chromium.launch({executablePath:process.env.MESSENGER_BROWSER_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',headless:true});
const alice=await actor('Никита'), bob=await actor('Собеседник');
const chat=await call('POST','/api/v1/chats',alice,{title:'Защита · живой мессенджер',member_ids:[alice.user.id,bob.user.id]});
const message=await call('POST',`/api/v1/chats/${chat.id}/messages`,bob,{text:'Привет! Проверим реакции и работу двух API 🍄'});
await call('POST',`/api/v1/chats/${chat.id}/messages`,alice,{text:'Да! Сейчас отключим один экземпляр. Переписка продолжит работать.'});
const a=await pageFor(alice,chat), b=await pageFor(bob,chat);
await row(a,message.id).locator('.reaction-picker').click();
await row(a,message.id).getByRole('button',{name:'Гриб',exact:true}).click();
await a.waitForFunction(id=>document.querySelector(`article[data-message-id="${id}"] [data-reaction=mushroom]`)?.getAttribute('aria-pressed')==='true',message.id);
await b.waitForFunction(id=>document.querySelector(`article[data-message-id="${id}"] [data-reaction=mushroom]`)?.textContent==='🍄 1',message.id);
assert.equal(await row(b,message.id).locator('[data-reaction=mushroom]').getAttribute('aria-pressed'),'false');
await row(b,message.id).locator('[data-reaction=mushroom]').click();
await a.waitForFunction(id=>document.querySelector(`article[data-message-id="${id}"] [data-reaction=mushroom]`)?.textContent==='🍄 2',message.id);
checks.push('real two-window reactions: shared count, per-user mine state');
await a.locator('.sidebar-diagnostics').click();
await a.waitForFunction(()=>document.querySelectorAll('.cluster-api[data-state=up]').length>=2);
await a.locator('#cluster-probe').click();
await a.waitForFunction(()=>document.querySelector('#cluster-detail').textContent.includes('200'));
const liveResponse=await api.get('/health/ready');
assert.equal(liveResponse.status(),200);
const target=liveResponse.headers()['x-instance-id'];
await a.locator(`.cluster-api[data-instance-id="${target}"][data-state=up]`).waitFor();
assert.match(target,/^[a-f0-9]{32}$/);
checks.push('live diagram: actual Redis heartbeats, real X-Instance-Id response and counters');
await a.locator('.cluster-demo summary').click();
await a.screenshot({path:path.join(evidence,'ui-showcase-live.png')});
let output='';
demo=spawn('python3',['scripts/demo-failover.py','--instance',target,'--seconds','22','--base-url',baseURL],{cwd:path.resolve(__dirname,'..'),stdio:['ignore','pipe','pipe']});
demo.stdout.on('data',chunk=>{output+=chunk.toString()}); demo.stderr.on('data',chunk=>{output+=chunk.toString()});
const completion=new Promise((resolve,reject)=>{demo.on('error',reject); demo.on('close',code=>code===0 ? resolve() : reject(new Error('Failover demo failed: '+output)));});
// Attach a handler immediately so an early script failure is not an unhandled rejection.
completion.catch(()=>{});
await a.waitForFunction(id=>document.querySelector(`[data-instance-id="${id}"]`)?.dataset.state==='down',target,{timeout:25000});
await a.locator('#message-input').fill('Один API отключён, а сообщение всё равно доставлено ✓');
await a.locator('#send-message').click();
await b.locator('#message-list').getByText('Один API отключён, а сообщение всё равно доставлено ✓',{exact:true}).waitFor();
const during=await call('GET','/api/ui/cluster',alice);
assert.equal(during.instances.filter(node=>node.ready).length,1);
await row(b,message.id).locator('.reaction-picker').click();
await row(b,message.id).getByRole('button',{name:'Сердце',exact:true}).click();
await a.waitForFunction(id=>document.querySelector(`article[data-message-id="${id}"] [data-reaction=love]`)?.textContent==='❤️ 1',message.id);
assert.equal((await call('GET','/api/ui/cluster',alice)).instances.filter(node=>node.ready).length,1);
await a.screenshot({path:path.join(evidence,'ui-showcase-failover.png')});
await completion; demo=null;
await a.waitForFunction(()=>document.querySelectorAll('.cluster-api[data-state=up]').length>=2,{},{timeout:20000});
assert(output.includes('Восстанавливаем') && output.includes('Готово.'));
checks.push('real Docker stop: heartbeat disappears, browser sends message and reaction via surviving API, script restores replicas');
const cluster=await call('GET','/api/ui/cluster',alice);
assert(cluster.instances.some(node=>node.id===target && !node.ready));
assert(cluster.instances.filter(node=>node.ready).length>=2);
checks.push('restart is shown with new process ID; old missing heartbeat is not mislabelled as recovery');
await a.route('**/api/ui/cluster',route=>route.fulfill({status:200,contentType:'application/json',body:JSON.stringify({redis_available:false,postgres_available:true,checked_at:Date.now(),instances:[]})}));
await a.locator('#cluster-probe').click();
await a.waitForFunction(()=>document.querySelector('#cluster-status').textContent.includes('неизвестно'));
assert.equal(await a.locator('.cluster-api[data-state=down]').count(),0);
assert(await a.locator('#cluster-copy').isDisabled());
await a.unroute('**/api/ui/cluster');
await a.locator('#cluster-probe').click();
await a.waitForFunction(()=>document.querySelectorAll('.cluster-api[data-state=up]').length>=2);
checks.push('missing Redis telemetry is shown as unknown, rather than a false API outage');
await a.setViewportSize({width:390,height:844});
assert(await a.evaluate(()=>document.documentElement.scrollWidth<=document.documentElement.clientWidth));
assert(await a.locator('#diagnostics-panel').evaluate(e=>e.scrollWidth<=e.clientWidth));
await a.screenshot({path:path.join(evidence,'ui-showcase-mobile.png')});
await a.emulateMedia({reducedMotion:'reduce'});
assert.equal(await a.locator('.cluster-api').first().evaluate(e=>getComputedStyle(e).transitionDuration),'0s');
checks.push('390px diagram: no horizontal overflow; reduced motion supported');
assert.deepEqual(errors,[]);
await fs.writeFile(path.join(evidence,'ui-showcase.json'),JSON.stringify({checks,errors,failover:output},null,2)+'\n');
console.log(JSON.stringify({checks,errors},null,2));
})().catch(error=>{console.error(error.stack);process.exitCode=1;}).finally(async()=>{
if(demo && demo.exitCode===null && demo.signalCode===null){demo.kill('SIGTERM');await new Promise(resolve=>demo.once('close',resolve));}
for(const value of actors){try{await call('DELETE','/api/v1/auth/sessions/current',value)}catch{}}
await browser?.close();await api?.dispose();
});