Реализована лабораторная работа 4 на оценку 4

This commit is contained in:
MacBook
2026-10-20 21:16:52 +03:00
parent ec540a1a72
commit 6913a7ca1f
42 changed files with 3419 additions and 37 deletions
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Stop Redis and PostgreSQL separately and check bounded API failures."""
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check # noqa: E402
def compose(*args):
subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT,
check=True, stdout=subprocess.DEVNULL)
def wait_ready(client, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
time.sleep(0.5)
raise Failure("stack did not recover")
def main():
client = Client(timeout=5)
actor = client.user("dependency")
try:
compose("stop", "redis")
client.call("GET", "/health/ready", 503)
client.call("GET", "/api/v1/users/me", 503, actor=actor)
client.call("GET", "/api/v1/users/me", 401)
finally:
compose("start", "redis")
wait_ready(client)
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
try:
compose("stop", "postgres")
client.call("GET", "/health/ready", 503)
client.call("GET", "/api/v1/users/me", 503, actor=actor)
finally:
compose("start", "postgres")
wait_ready(client)
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
print("PASS: Redis/PostgreSQL failures returned 503; anonymous access stayed 401; state recovered")
if __name__ == "__main__":
try:
main()
except (Failure, OSError, subprocess.CalledProcessError) as exc:
print("FAIL:", exc)
raise SystemExit(1)
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""Recreate the API with a two-second session TTL and prove expiry."""
import os
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check # noqa: E402
def compose(env, *args):
subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT,
env=env, check=True, stdout=subprocess.DEVNULL)
def wait_ready(timeout=60):
client = Client(timeout=2)
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
time.sleep(0.5)
raise Failure("API did not become ready")
def main():
normal_env = dict(os.environ)
normal_env.pop("SESSION_TTL_SECONDS", None)
short_env = dict(normal_env)
short_env["SESSION_TTL_SECONDS"] = "2"
try:
compose(short_env, "up", "-d", "--force-recreate", "--no-deps", "--wait", "api1", "api2")
compose(short_env, "exec", "-T", "nginx", "nginx", "-s", "reload")
wait_ready()
client = Client()
actor = client.user("expiry")
time.sleep(3)
client.call("GET", "/api/v1/users/me", 401, actor=actor)
print("PASS: two-second Redis session expired and was rejected")
finally:
compose(normal_env, "up", "-d", "--force-recreate", "--no-deps", "--wait", "api1", "api2")
compose(normal_env, "exec", "-T", "nginx", "nginx", "-s", "reload")
wait_ready()
if __name__ == "__main__":
try:
main()
except (Failure, OSError, subprocess.CalledProcessError) as exc:
print("FAIL:", exc)
raise SystemExit(1)
@@ -0,0 +1,55 @@
"""Prove that one idempotency key creates one message across both replicas."""
import concurrent.futures
import json
import sys
import threading
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, check, run # noqa: E402
def main():
args = arguments("Concurrent cross-replica idempotency check")
base = Client(args.base_url, args.ca_file)
alice, _, _, chat = base.bootstrap()
path = "/api/v1/chats/" + chat["id"] + "/messages"
key = "parallel-" + uuid.uuid4().hex
body = {"text": "one logical concurrent message"}
workers = 12
barrier = threading.Barrier(workers)
def send(_):
client = Client(args.base_url, args.ca_file)
barrier.wait()
result = client.call("POST", path, 201, actor=alice, body=body,
headers={"Idempotency-Key": key}, schema="Message")
return result["json"], result["headers"]["X-Instance-Id"]
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
responses = list(pool.map(send, range(workers)))
messages = [item[0] for item in responses]
instances = sorted(set(item[1] for item in responses))
ids = sorted(set(item["id"] for item in messages))
check(len(ids) == 1, "one key created more than one message")
check(all(item == messages[0] for item in messages),
"idempotent responses differ")
check(len(instances) >= 2, "requests did not cross two API replicas")
base.call("POST", path, 409, actor=alice, body={"text": "different body"},
headers={"Idempotency-Key": key})
page = base.call("GET", path + "?limit=100", actor=alice,
schema="MessagePage")["json"]
check(sum(item["id"] == ids[0] for item in page["items"]) == 1,
"history contains a duplicate message")
result = {"parallel_requests": workers, "instances": instances,
"unique_message_ids": len(ids), "conflicting_reuse_status": 409}
print("PASS:", json.dumps(result, ensure_ascii=False))
if __name__ == "__main__":
run(main)
@@ -0,0 +1,71 @@
"""Check LB failover when api1 still runs but cannot reach its stores."""
import json
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run # noqa: E402
def docker(*args):
return subprocess.run(["docker", *args], cwd=ROOT, check=True,
capture_output=True, text=True).stdout.strip()
def compose(*args):
return docker("compose", "--env-file", ".env", *args)
def details(container):
return json.loads(docker("inspect", container))[0]
def wait_health(container, expected, timeout=90):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if details(container)["State"]["Health"]["Status"] == expected:
return
time.sleep(1)
raise Failure("api1 did not become " + expected)
def main():
client = Client(timeout=8)
seen = set()
for _ in range(20):
seen.add(client.call("GET", "/health/ready", schema="Health")
["headers"]["X-Instance-Id"])
check(seen == {"api-1", "api-2"}, "both instances must be ready initially")
actor, _, _, chat = client.bootstrap()
container = compose("ps", "-q", "api1")
check(bool(container), "api1 container is missing")
network = next((name for name in details(container)["NetworkSettings"]["Networks"]
if name.endswith("_backend")), None)
check(network is not None, "api1 backend network is missing")
disconnected = False
try:
docker("network", "disconnect", network, container)
disconnected = True
wait_health(container, "unhealthy")
for _ in range(20):
for path, schema in (("/api/v1/users/me", "User"),
("/health/ready", "Health")):
response = client.call("GET", path, actor=actor, schema=schema)
check(response["headers"]["X-Instance-Id"] == "api-2",
path + " was not served by healthy api2")
for number in range(10):
response = client.message(actor, chat, "unready check " + str(number))
check(response["headers"]["X-Instance-Id"] == "api-2",
"message was not accepted by healthy api2")
print("PASS: api1 unhealthy with frontend connection; 40 GETs and 10 POSTs served by api2")
finally:
if disconnected:
docker("network", "connect", "--alias", "api1", network, container)
wait_health(container, "healthy")
if __name__ == "__main__":
run(main)