feat: полная реализация

This commit is contained in:
2026-11-10 15:27:10 +03:00
parent 7734b222f8
commit 5cf99b5384
18 changed files with 935 additions and 211 deletions
+88 -27
View File
@@ -1,36 +1,97 @@
#!/usr/bin/env python3
import sys
import uuid
import requests
import time
BASE = "http://localhost:8080"
LOGIN = "test"
PASSWORD = "test123"
TIMEOUT = 5
failures = []
def check(condition, message):
if condition:
print("PASS:", message)
return True
failures.append(message)
print("FAIL:", message)
return False
def login():
response = requests.post("http://localhost:8080/api/auth/login", json={"login": "user", "password": "password"})
return response.json()["token"]
response = requests.post(
BASE + "/api/auth/login",
json={"login": LOGIN, "password": PASSWORD},
timeout=TIMEOUT,
)
if not check(response.status_code == 200, "login returns 200 (got %d)" % response.status_code):
print(response.text)
return None
token = response.json().get("token")
check(bool(token), "login returns a token")
return token
def get_messages(token):
headers = {"Authorization": f"Bearer {token}"}
response = requests.get("http://localhost:8080/api/messages", headers=headers)
return response.json()
def post_message(token, message):
headers = {"Authorization": f"Bearer {token}", "Idempotency-Key": str(uuid.uuid4())}
response = requests.post("http://localhost:8080/api/messages", headers=headers, json={"recipient": "user", "body": message})
return response.json()
def test_idempotency(token):
message = "Hello, World!"
response1 = post_message(token, message)
response2 = post_message(token, message)
return response1 == response2
def test_health():
response = requests.get("http://localhost:8080/health")
return response.json() == {"status": "ok", "instance": "api1"}
def main():
token = login()
messages = get_messages(token)
print(messages)
assert test_idempotency(token)
assert test_health()
if token is None:
return 1
auth = {"Authorization": "Bearer " + token}
response = requests.get(BASE + "/api/messages", headers=auth, timeout=TIMEOUT)
check(response.status_code == 200, "GET /api/messages returns 200")
instance = response.headers.get("X-Instance-Id")
check(bool(instance), "response carries X-Instance-Id (%s)" % instance)
check(isinstance(response.json(), list), "GET /api/messages returns a JSON array")
key = "key-" + uuid.uuid4().hex[:12]
body = {"recipient": LOGIN, "body": "hello " + uuid.uuid4().hex[:8]}
first = requests.post(
BASE + "/api/messages",
headers=dict(auth, **{"Idempotency-Key": key}),
json=body,
timeout=TIMEOUT,
)
check(first.status_code == 201, "first POST returns 201 (got %d)" % first.status_code)
second = requests.post(
BASE + "/api/messages",
headers=dict(auth, **{"Idempotency-Key": key}),
json=body,
timeout=TIMEOUT,
)
check(second.status_code in (200, 201), "replayed POST returns 2xx (got %d)" % second.status_code)
first_id = first.json().get("id")
second_id = second.json().get("id")
check(first_id is not None, "first POST returns message id")
check(first_id == second_id, "replay returns the same id (%s vs %s)" % (first_id, second_id))
missing_key = requests.post(BASE + "/api/messages", headers=auth, json=body, timeout=TIMEOUT)
check(missing_key.status_code == 400, "POST without Idempotency-Key returns 400 (got %d)" % missing_key.status_code)
unauthorized = requests.get(BASE + "/api/messages", timeout=TIMEOUT)
check(unauthorized.status_code == 401, "GET without token returns 401 (got %d)" % unauthorized.status_code)
messages = requests.get(BASE + "/api/messages", headers=auth, timeout=TIMEOUT).json()
matching = [m for m in messages if m.get("body") == body["body"]]
check(len(matching) == 1, "history contains exactly one copy of the message (got %d)" % len(matching))
if failures:
print("\n%d check(s) failed" % len(failures))
return 1
print("\nAll API checks passed")
return 0
if __name__ == "__main__":
main()
try:
sys.exit(main())
except requests.RequestException as exc:
print("request failed:", exc)
sys.exit(1)
+152 -21
View File
@@ -1,33 +1,164 @@
import requests
import time
#!/usr/bin/env python3
import subprocess
import sys
import threading
import time
from pathlib import Path
import requests
BASE = "http://localhost:8080"
LOGIN = "test"
PASSWORD = "test123"
TIMEOUT = 5
REPO_ROOT = Path(__file__).resolve().parents[1]
RECOVERY_BUDGET = 10.0
failures = []
def check(condition, message):
if condition:
print("PASS:", message)
return True
failures.append(message)
print("FAIL:", message)
return False
def worker(worker_id):
token = login()
for _ in range(10):
post_message(token, f"Message from worker {worker_id}")
def login():
response = requests.post("http://localhost:8080/api/auth/login", json={"login": "user", "password": "password"})
response = requests.post(
BASE + "/api/auth/login",
json={"login": LOGIN, "password": PASSWORD},
timeout=TIMEOUT,
)
response.raise_for_status()
return response.json()["token"]
def post_message(token, message):
headers = {"Authorization": f"Bearer {token}", "Idempotency-Key": str(uuid.uuid4())}
response = requests.post("http://localhost:8080/api/messages", headers=headers, json={"recipient": "user", "body": message})
return response.json()
def test_load():
threads = []
for i in range(10):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
def fetch(token):
response = requests.get(
BASE + "/api/messages",
headers={"Authorization": "Bearer " + token},
timeout=TIMEOUT,
)
response.raise_for_status()
return response.headers.get("X-Instance-Id", "")
def round_robin(token, count):
instances = []
lock = threading.Lock()
def worker():
try:
instance = fetch(token)
except requests.RequestException:
return
with lock:
instances.append(instance)
threads = [threading.Thread(target=worker) for _ in range(count)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return instances
def compose(*args):
return subprocess.run(
["docker", "compose", *args],
cwd=REPO_ROOT,
capture_output=True,
text=True,
check=False,
)
for t in threads:
t.join()
def main():
test_load()
token = login()
auth = {"Authorization": "Bearer " + token}
probe = requests.post(
BASE + "/api/messages",
headers=dict(auth, **{"Idempotency-Key": "load-" + str(time.time_ns())}),
json={"recipient": LOGIN, "body": "before failover"},
timeout=TIMEOUT,
)
check(probe.status_code == 201, "message written before failover (got %d)" % probe.status_code)
probe_id = probe.json().get("id")
instances = round_robin(token, 20)
check(len(set(instances)) >= 2, "requests reached at least two replicas: %s" % sorted(set(instances)))
print("\n=== Stopping api1 ===")
stop = compose("stop", "api1")
check(stop.returncode == 0, "docker compose stop api1 succeeded")
started = time.monotonic()
recovered_at = None
served_after = []
transient_errors = 0
while time.monotonic() - started < RECOVERY_BUDGET + 5:
try:
instance = fetch(token)
except requests.RequestException:
transient_errors += 1
time.sleep(0.2)
continue
if recovered_at is None:
recovered_at = time.monotonic() - started
served_after.append(instance)
if len(served_after) >= 5:
break
time.sleep(0.1)
check(
recovered_at is not None and recovered_at <= RECOVERY_BUDGET,
"reads recovered within %.0fs (%.2fs, %d transient errors)"
% (RECOVERY_BUDGET, recovered_at if recovered_at is not None else -1, transient_errors),
)
check(bool(served_after), "requests still served while api1 is down")
check(all(x == "api2" for x in served_after), "api1 left rotation, served by: %s" % sorted(set(served_after)))
write = requests.post(
BASE + "/api/messages",
headers=dict(auth, **{"Idempotency-Key": "load-fail-" + str(time.time_ns())}),
json={"recipient": LOGIN, "body": "written during failover"},
timeout=TIMEOUT,
)
check(write.status_code == 201, "write works while api1 is down (got %d)" % write.status_code)
print("\n=== Starting api1 back ===")
start = compose("start", "api1")
check(start.returncode == 0, "docker compose start api1 succeeded")
deadline = time.monotonic() + 30
back = set()
while time.monotonic() < deadline:
back = set(round_robin(token, 10))
if "api1" in back:
break
time.sleep(1)
check("api1" in back, "api1 is back in rotation: %s" % sorted(back))
history = requests.get(BASE + "/api/messages", headers=auth, timeout=TIMEOUT)
check(history.status_code == 200, "history readable after failover (got %d)" % history.status_code)
ids = [m.get("id") for m in history.json()]
check(probe_id in ids, "message written before failover survived")
check(len(ids) == len(set(ids)), "no duplicate messages in history")
if failures:
print("\n%d check(s) failed" % len(failures))
return 1
print("\nFailover scenario passed")
return 0
if __name__ == "__main__":
main()
try:
sys.exit(main())
except requests.RequestException as exc:
print("request failed:", exc)
sys.exit(1)