#!/usr/bin/env python3 """Контракт lab3 без остановки стенда: сессия, UUID, идемпотентность, две реплики.""" import json import uuid from concurrent.futures import ThreadPoolExecutor from pathlib import Path from httpapi import basic, bearer, call from sql import compose, psql ROOT = Path(__file__).resolve().parents[1] EVIDENCE = ROOT / "evidence" / "student_checks.txt" LINES = [] def log(text): print(text) LINES.append(text) def check(cond, message): if not cond: log("FAIL: " + message) raise SystemExit(1) def register(username, display_name, password): status, _, payload = call( "POST", "/api/v1/users", {"username": username, "display_name": display_name, "password": password}, ) check(status == 201, "register {} -> {}".format(username, status)) check("password" not in payload and "password_hash" not in payload, "password leaked") return payload def login(username, password): status, headers, payload = call("POST", "/api/v1/auth/sessions", headers=basic(username, password)) check(status == 201, "login -> {}".format(status)) check(headers.get("X-Instance-Id"), "login without instance") check(payload["token_type"] == "Bearer", "token type") check(len(payload["token"]) >= 43, "token length") check(username not in payload["token"], "token contains username") return payload def main(): suffix = uuid.uuid4().hex[:10] alice = register("a_" + suffix, "Алиса", "long-enough-pw-1") bob = register("b_" + suffix, "Боб", "long-enough-pw-2") session = login("a_" + suffix, "long-enough-pw-1") token = session["token"] auth = bearer(token) status, _, _ = call("GET", "/api/v1/users/me") check(status == 401, "anon me {}".format(status)) status, headers, me = call("GET", "/api/v1/users/me", headers={**auth, "X-User-Id": bob["id"]}) check(status == 200 and me["id"] == alice["id"], "X-User-Id overrode session") check(headers.get("X-Instance-Id"), "me without instance") before = int(psql("SELECT count(*) FROM chats;")) status, _, body = call( "POST", "/api/v1/chats", {"title": "Дубликат UUID", "member_ids": [alice["id"], alice["id"].upper()]}, headers=auth, ) after = int(psql("SELECT count(*) FROM chats;")) check(status == 400 and before == after, "case-duplicate members {} chats {}->{}".format(status, before, after)) check(body.get("error", {}).get("code") == "invalid_request", "case-duplicate code") status, _, chat = call( "POST", "/api/v1/chats", {"title": "Лаба 3", "member_ids": [alice["id"], bob["id"]]}, headers=auth, ) check(status == 201, "create chat {}".format(status)) path = "/api/v1/chats/" + chat["id"] + "/messages" upper_path = "/api/v1/chats/" + chat["id"].upper() + "/messages" seen = set() for _ in range(30): status, headers, _ = call("GET", "/api/v1/users/me", headers=auth) check(status == 200, "spread {}".format(status)) seen.add(headers["X-Instance-Id"]) check(len(seen) >= 2, "observed instances {}".format(len(seen))) log("instances {}".format(len(seen))) key = "idem-" + uuid.uuid4().hex raw_a = json.dumps({"text": "Одинаково"}, ensure_ascii=False).encode("utf-8") raw_b = json.dumps({"attachment_ids": [], "text": "Одинаково"}, ensure_ascii=False).encode("utf-8") status, _, first = call( "POST", path, headers={**auth, "Content-Type": "application/json", "Idempotency-Key": key}, raw=raw_a, ) check(status == 201, "first message {}".format(status)) status, _, replay = call( "POST", upper_path, headers={**auth, "Content-Type": "application/json", "Idempotency-Key": key}, raw=raw_b, ) check(status == 201 and replay == first, "replay differs") status, _, conflict = call( "POST", path, {"text": "другое тело"}, headers={**auth, "Idempotency-Key": key}, ) check(status == 409 and conflict["error"]["code"] == "conflict", "different body {}".format(status)) rows = int(psql("SELECT count(*) FROM messages WHERE id = '{}';".format(first["id"]))) check(rows == 1, "message rows {}".format(rows)) status, _, _ = call("POST", path, {"text": "без ключа"}, headers=auth) check(status == 400, "missing key {}".format(status)) status, _, _ = call( "POST", path, {"text": "плохой ключ"}, headers={**auth, "Idempotency-Key": "bad key"}, ) check(status == 400, "bad key {}".format(status)) status, _, _ = call( "POST", path, {"text": " "}, headers={**auth, "Idempotency-Key": "blank-" + suffix}, ) check(status == 400, "blank text {}".format(status)) parallel_key = "par-" + uuid.uuid4().hex text = "Параллельно " + parallel_key def once(_n): return call( "POST", path, {"text": text}, headers={**auth, "Idempotency-Key": parallel_key}, timeout=20, ) with ThreadPoolExecutor(max_workers=8) as pool: results = list(pool.map(once, range(8))) codes = sorted(item[0] for item in results) bodies = [item[2] for item in results if item[0] == 201] check(codes == [201] * 8, "parallel codes {}".format(codes)) check(all(item == bodies[0] for item in bodies), "parallel bodies differ") count = int( psql( "SELECT count(*) FROM messages WHERE chat_id = '{}' AND body = '{}';".format(chat["id"], text) ) ) check(count == 1, "parallel rows {}".format(count)) log("parallel same key: 8x201, 1 row") psql( "UPDATE idempotency_keys SET created_at = now() - interval '25 hours' WHERE idem_key = '{}';".format(key) ) status, _, renewed = call( "POST", path, {"text": "Одинаково"}, headers={**auth, "Idempotency-Key": key}, ) check(status == 201 and renewed["id"] != first["id"], "expired key did not create a new message") log("expired key created a new message") versions = psql("SELECT version FROM schema_migrations ORDER BY 1;") check(versions == "001_init\n002_idempotency", "migrations [{}]".format(versions)) log("migrations " + versions.replace("\n", ",")) inspected = compose("ps", "-q", "api") api_ids = [line.strip() for line in inspected.stdout.decode().splitlines() if line.strip()] check(len(api_ids) >= 2, "running api replicas {}".format(len(api_ids))) for api_id in api_ids: info = __import__("subprocess").run( ["docker", "inspect", api_id], stdout=__import__("subprocess").PIPE, check=True, ) data = json.loads(info.stdout.decode())[0] ports = data["HostConfig"].get("PortBindings") or {} check(not ports, "api publishes ports") check(data["HostConfig"]["NanoCpus"] > 0, "api cpu limit missing") check(data["HostConfig"]["Memory"] > 0, "api memory limit missing") log("api replicas {} have cpu/memory limits and no published ports".format(len(api_ids))) EVIDENCE.parent.mkdir(exist_ok=True) EVIDENCE.write_text("\n".join(LINES) + "\n", encoding="utf-8") log("PASS student checks") EVIDENCE.write_text("\n".join(LINES) + "\n", encoding="utf-8") if __name__ == "__main__": main()