ЛР 3: балансировка, идемпотентность и проверки на 4

This commit is contained in:
2026-11-01 17:02:42 +03:00
parent 0ab3a341aa
commit 412b1bb09d
64 changed files with 3904 additions and 53 deletions
+222
View File
@@ -0,0 +1,222 @@
"""Integration tests against real HTTP, PostgreSQL and Redis on the local stack."""
from concurrent.futures import ThreadPoolExecutor
import base64
import hashlib
import json
from pathlib import Path
import subprocess
import sys
import time
import unittest
from urllib.parse import quote
from uuid import uuid4
import psycopg
import redis
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
sys.path.insert(0, str(ROOT / "scripts"))
from client import Client
from ops import containers
from app.config import secret
class APITests(unittest.TestCase):
def setUp(self):
self.c = Client(timeout=8)
self.alice = self.c.user("student")
self.bob = self.c.user("member")
self.chat = self.c.call("POST", "/api/v1/chats", 201, actor=self.alice,
body={"title": "Учебный чат", "member_ids": [self.alice["id"], self.bob["id"]]},
schema="Chat")["json"]
self.path = "/api/v1/chats/" + self.chat["id"]
def scalar(self, query, params=()):
with psycopg.connect(secret("DATABASE_URL"), connect_timeout=2) as conn:
return conn.execute(query, params).fetchone()[0]
def history(self, limit=17):
result, cursor = [], None
for _ in range(100):
path = self.path + "/messages?limit=" + str(limit)
if cursor:
path += "&cursor=" + quote(cursor, safe="")
page = self.c.call("GET", path, actor=self.alice, schema="MessagePage")["json"]
result.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
return result
self.fail("Pagination did not terminate")
def test_registration_race(self):
registration = {"username": "race_" + uuid4().hex[:16], "display_name": "Гонка",
"password": "Synthetic-password-12345"}
def register(_):
return self.c.call("POST", "/api/v1/users", [201, 409], body=registration,
schema="User")["status"]
with ThreadPoolExecutor(max_workers=10) as pool:
statuses = list(pool.map(register, range(10)))
self.assertEqual(statuses.count(201), 1)
self.assertEqual(statuses.count(409), 9)
self.assertEqual(self.scalar("SELECT count(*) FROM users WHERE username=%s",
(registration["username"],)), 1)
print("RACE: 10 requests, 1 created, 9 conflicts, 1 database row", flush=True)
def test_composite_chat_rollback(self):
before = self.scalar("SELECT count(*) FROM chats")
memberships = self.scalar("SELECT count(*) FROM chat_members")
self.c.call("POST", "/api/v1/chats", 400, actor=self.alice,
body={"title": "Rollback", "member_ids": [self.alice["id"], str(uuid4())]})
self.assertEqual(self.scalar("SELECT count(*) FROM chats"), before)
self.assertEqual(self.scalar("SELECT count(*) FROM chat_members"), memberships)
self.assertEqual(self.scalar("SELECT count(*) FROM chats c WHERE NOT EXISTS "
"(SELECT 1 FROM chat_members m WHERE m.chat_id=c.id)"), 0)
print("ROLLBACK: invalid second member left no chat or membership rows", flush=True)
def test_concurrent_messages(self):
def send(index):
return self.c.message(self.alice, self.chat, "parallel-" + str(index))["json"]["id"]
with ThreadPoolExecutor(max_workers=10) as pool:
ids = list(pool.map(send, range(100)))
messages = self.history()
self.assertEqual(len(messages), 100)
self.assertEqual(len(set(ids)), 100)
self.assertEqual({row["id"] for row in messages}, set(ids))
self.assertEqual({row["text"] for row in messages}, {"parallel-" + str(i) for i in range(100)})
self.assertEqual(messages, sorted(messages, key=lambda row: (row["created_at"], row["id"])))
print("CONCURRENCY: 10 clients, 100 confirmations, 100 unique messages", flush=True)
def test_validation_and_access(self):
for payload in [b"{", b"null", b"[]", b"\xff", b'{"text":NaN}']:
self.c.call("POST", self.path + "/messages", 400, actor=self.alice, raw=payload,
headers={"Content-Type": "application/json", "Idempotency-Key": uuid4().hex})
for body in [{"text": ""}, {"text": " \n\t"}, {"text": 123}, {"text": "x" * 4001},
{"text": "hello", "sender_id": self.bob["id"]}]:
self.c.call("POST", self.path + "/messages", 400, actor=self.alice, body=body,
headers={"Idempotency-Key": uuid4().hex})
outsider = self.c.user("outsider")
for suffix in ("", "/messages"):
self.c.call("GET", self.path + suffix, 404, actor=outsider)
self.c.call("POST", self.path + "/messages", 404, actor=outsider, body={"text": "hidden"})
for members in [[self.bob["id"]], [self.alice["id"], self.alice["id"]], ["bad"], []]:
self.c.call("POST", "/api/v1/chats", 400, actor=self.alice,
body={"title": "Invalid", "member_ids": members})
self.c.call("GET", "/api/v1/chats/not-uuid", 400, actor=self.alice)
for limit in ("0", "101", "1.1", "-1", "", "true"):
self.c.call("GET", self.path + "/messages?limit=" + limit, 400, actor=self.alice)
self.c.call("POST", "/api/v1/users", 409, body=self.alice["registration"])
for raw in (b"{}", b'{"username":123}', b'{"username":"ab","display_name":"x","password":"123456789012"}'):
self.c.call("POST", "/api/v1/users", 400, raw=raw, headers={"Content-Type": "application/json"})
def test_passwords_and_authentication(self):
registration = {"username": "unicode_" + uuid4().hex[:12], "display_name": "Имя 🧪",
"password": "я:🧪" + "密" * 125}
user = self.c.call("POST", "/api/v1/users", 201, body=registration, schema="User")["json"]
credential = base64.b64encode((registration["username"] + ":" + registration["password"]).encode()).decode()
session = self.c.call("POST", "/api/v1/auth/sessions", 201,
headers={"Authorization": "Basic " + credential}, schema="Session")["json"]
self.assertEqual(session["user"]["id"], user["id"])
encoded = self.scalar("SELECT password_hash FROM users WHERE id=%s", (user["id"],))
algorithm, n, r, p, salt, digest = encoded.split("$")
self.assertEqual(algorithm, "scrypt")
actual = hashlib.scrypt(registration["password"].encode(), salt=bytes.fromhex(salt),
n=int(n), r=int(r), p=int(p), dklen=32, maxmem=64 * 1024 * 1024).hex()
self.assertTrue(actual == digest)
self.assertNotIn("password", user)
for username in (registration["username"], "missing_" + uuid4().hex[:12]):
bad = base64.b64encode((username + ":wrong-password-123").encode()).decode()
response = self.c.call("POST", "/api/v1/auth/sessions", 401,
headers={"Authorization": "Basic " + bad})
self.assertEqual(response["headers"]["WWW-Authenticate"], 'Basic realm="messenger", charset="UTF-8"')
self.assertEqual(response["json"]["error"]["message"], "Valid credentials required")
self.c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Basic " + credential})
self.c.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": user["id"]})
self.c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Bearer " + "x" * 43})
actor = {"id": user["id"], "token": session["token"]}
self.c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=actor)
self.c.call("GET", "/api/v1/users/me", 401, actor=actor)
self.c.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=actor)
def test_cursor_binding_and_chat_pages(self):
sent = [self.c.message(self.alice, self.chat, "page-" + str(i))["json"] for i in range(7)]
self.assertEqual(self.history(limit=2), sent)
page = self.c.call("GET", self.path + "/messages?limit=2", actor=self.alice, schema="MessagePage")["json"]
cursor = page["next_cursor"]
other = self.c.call("POST", "/api/v1/chats", 201, actor=self.alice,
body={"title": "Other", "member_ids": [self.alice["id"]]}, schema="Chat")["json"]
self.c.call("GET", "/api/v1/chats/" + other["id"] + "/messages?cursor=" + quote(cursor), 400, actor=self.alice)
for token in ("bad", "", cursor[:-3] + "xxx"):
self.c.call("GET", self.path + "/messages?cursor=" + quote(token), 400, actor=self.alice)
later = self.c.message(self.alice, self.chat, "later")["json"]
continued = self.c.call("GET", self.path + "/messages?limit=100&cursor=" + quote(cursor),
actor=self.alice, schema="MessagePage")["json"]
self.assertEqual(continued["items"], sent[2:] + [later])
first = self.c.call("GET", "/api/v1/chats?limit=1", actor=self.alice, schema="ChatPage")["json"]
second = self.c.call("GET", "/api/v1/chats?limit=100&cursor=" + quote(first["next_cursor"]),
actor=self.alice, schema="ChatPage")["json"]
self.assertEqual([row["id"] for row in first["items"] + second["items"]],
[self.chat["id"], other["id"]])
def compose(self, *args):
result = subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT,
capture_output=True, text=True, timeout=45)
if result.returncode:
self.fail("Compose action failed: " + " ".join(args[:2]))
def wait_ready(self):
deadline = time.monotonic() + 40
while time.monotonic() < deadline:
try:
self.c.call("GET", "/health/ready", schema="Health")
return
except AssertionError:
time.sleep(0.25)
self.fail("Stack did not recover")
def test_dependency_failures(self):
# With all backends unready, LB may generate its own 503. Diagnose
# the application error contract on an internal replica explicitly.
row = containers()[0]
self.c = Client("http://" + row["Name"].lstrip("/") + ":8080", timeout=8)
report = {}
for service in ("redis", "postgres"):
self.compose("stop", "--timeout", "2", service)
try:
self.c.call("GET", "/health/live", schema="Health")
ready = self.c.call("GET", "/health/ready", 503)
started = time.monotonic()
response = self.c.call("GET", "/api/v1/users/me", 503, actor=self.alice)
elapsed = time.monotonic() - started
self.assertEqual(response["json"]["error"]["code"], "unavailable")
self.assertLess(elapsed, 6)
self.c.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": self.alice["id"]})
report[service] = {"ready_status": ready["status"], "protected_status": response["status"],
"elapsed_seconds": round(elapsed, 3), "anonymous_status": 401}
finally:
self.compose("start", service)
self.wait_ready()
self.c.call("GET", "/api/v1/users/me", actor=self.alice, schema="User")
self.c.message(self.alice, self.chat, "after-" + service)
(ROOT / "evidence" / "failures.json").write_text(json.dumps(report, indent=2) + "\n")
print("FAILURES: Redis/PostgreSQL -> bounded 503, live 200, anonymous 401, recovery with old session", flush=True)
def test_redis_crash_durability(self):
client = redis.Redis.from_url(secret("CACHE_URL"), decode_responses=True)
try:
self.assertEqual(client.config_get("appendonly")["appendonly"], "yes")
self.assertEqual(client.config_get("appendfsync")["appendfsync"], "always")
key = "session:" + hashlib.sha256(self.alice["token"].encode()).hexdigest()
deadline_before = client.pexpiretime(key)
self.compose("kill", "--signal", "SIGKILL", "redis")
self.compose("start", "redis")
self.wait_ready()
self.c.call("GET", "/api/v1/users/me", actor=self.alice, schema="User")
self.assertEqual(client.pexpiretime(key), deadline_before)
finally:
client.close()
print("REDIS CRASH: old session survived SIGKILL/AOF replay, expiry deadline unchanged", flush=True)
if __name__ == "__main__":
unittest.main()
+110
View File
@@ -0,0 +1,110 @@
"""Cross-process idempotency, access and transaction boundaries."""
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import sys
import threading
import unittest
from uuid import uuid4
import psycopg
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
sys.path.insert(0, str(ROOT / "scripts"))
from client import Client
from ops import containers
from app.config import secret
class ReplicationTests(unittest.TestCase):
def setUp(self):
self.c = Client()
self.alice, self.bob, self.eve, self.chat = self.c.bootstrap()
self.path = "/api/v1/chats/" + self.chat["id"] + "/messages"
def sql(self, query, values=()):
with psycopg.connect(secret("DATABASE_URL"), connect_timeout=2) as conn:
cur = conn.execute(query, values)
return cur.fetchall() if cur.description else None
def test_parallel_replay_across_real_replicas(self):
replicas = containers()
self.assertGreaterEqual(len(replicas), 2)
clients = [Client("http://" + row["Name"].lstrip("/") + ":8080") for row in replicas]
barrier = threading.Barrier(10)
key = uuid4().hex
def send(index):
if index < 10:
barrier.wait()
return clients[index % len(clients)].message(self.alice, self.chat, "Один результат 🧪", key=key)
with ThreadPoolExecutor(max_workers=10) as pool:
responses = list(pool.map(send, range(100)))
self.assertEqual(len({r["json"]["id"] for r in responses}), 1)
self.assertGreaterEqual(len({r["headers"]["X-Instance-Id"] for r in responses}), 2)
self.assertTrue(all(r["json"] == responses[0]["json"] for r in responses))
self.assertEqual(self.sql("SELECT count(*) FROM messages WHERE chat_id=%s", (self.chat["id"],))[0][0], 1)
self.assertEqual(self.sql("SELECT count(*) FROM message_requests WHERE chat_id=%s", (self.chat["id"],))[0][0], 1)
for _ in range(12):
self.assertEqual(self.c.message(self.alice, self.chat, "Один результат 🧪", key=key)["json"], responses[0]["json"])
report = {"requests": 100, "clients": 10, "real_containers": len(replicas),
"observed_instances": len({r["headers"]["X-Instance-Id"] for r in responses}),
"messages": 1, "replay_records": 1, "lb_replays": 12}
(ROOT / "evidence" / "idempotency.json").write_text(json.dumps(report, indent=2) + "\n")
def test_key_validation_scope_conflict_and_logout(self):
for key in (None, "", "bad key", "bad/key", "a" * 129):
headers = {} if key is None else {"Idempotency-Key": key}
self.c.call("POST", self.path, 400, actor=self.alice, body={"text": "test"}, headers=headers)
key = uuid4().hex
first = self.c.message(self.alice, self.chat, "first", key=key)["json"]
replay = self.c.call("POST", self.path, 201, actor=self.alice,
raw=b'{\n "text" : "first"\n}', headers={"Content-Type": "application/json", "Idempotency-Key": key},
schema="Message")["json"]
self.assertEqual(first, replay)
self.c.call("POST", self.path, 409, actor=self.alice, body={"text": "changed"}, headers={"Idempotency-Key": key})
second = self.c.message(self.bob, self.chat, "first", key=key)["json"]
self.assertNotEqual(first["id"], second["id"])
other = self.c.call("POST", "/api/v1/chats", 201, actor=self.alice,
body={"title": "scope", "member_ids": [self.alice["id"]]}, schema="Chat")["json"]
self.assertNotEqual(self.c.message(self.alice, other, "first", key=key)["json"]["id"], first["id"])
self.c.call("POST", self.path, 404, actor=self.eve, body={"text": "first"}, headers={"Idempotency-Key": key})
self.c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.alice)
self.c.call("POST", self.path, 401, actor=self.alice, body={"text": "first"}, headers={"Idempotency-Key": key})
def test_failed_transaction_does_not_save_message_or_replay(self):
key = uuid4().hex
# Fail after INSERT messages, at INSERT replay, to check the whole
# transaction rather than merely validation before the first write.
self.sql("""CREATE FUNCTION lab3_test_reject() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'synthetic transaction failure'; END $$""")
self.sql("CREATE TRIGGER lab3_test_reject BEFORE INSERT ON message_requests "
"FOR EACH ROW EXECUTE FUNCTION lab3_test_reject()")
try:
self.c.call("POST", self.path, 503, actor=self.alice, body={"text": "atomic"}, headers={"Idempotency-Key": key})
self.assertEqual(self.sql("SELECT count(*) FROM messages WHERE chat_id=%s", (self.chat["id"],))[0][0], 0)
self.assertEqual(self.sql("SELECT count(*) FROM message_requests WHERE chat_id=%s", (self.chat["id"],))[0][0], 0)
finally:
self.sql("DROP TRIGGER lab3_test_reject ON message_requests")
self.sql("DROP FUNCTION lab3_test_reject()")
first = self.c.message(self.alice, self.chat, "atomic", key=key)["json"]
self.assertEqual(self.c.message(self.alice, self.chat, "atomic", key=key)["json"], first)
def test_expired_key_and_same_session_on_all_instances(self):
observed = set()
for _ in range(30):
response = self.c.call("GET", "/api/v1/users/me", actor=self.alice, schema="User")
self.assertEqual(response["json"]["id"], self.alice["id"])
observed.add(response["headers"]["X-Instance-Id"])
self.assertGreaterEqual(len(observed), 2)
key = uuid4().hex
original = self.c.message(self.alice, self.chat, "before expiry", key=key)["json"]
self.sql("UPDATE message_requests SET expires_at=clock_timestamp()-interval '1 second' "
"WHERE user_id=%s AND chat_id=%s AND request_key=%s", (self.alice["id"], self.chat["id"], key))
fresh = self.c.message(self.alice, self.chat, "after expiry", key=key)["json"]
self.assertNotEqual(original["id"], fresh["id"])
self.assertEqual(self.c.message(self.alice, self.chat, "after expiry", key=key)["json"], fresh)
if __name__ == "__main__":
unittest.main()