solution
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
# Собственные проверки лабораторной 3
|
||||
|
||||
```sh
|
||||
make student-test BASE_URL=http://127.0.0.1:8080
|
||||
python3 student-tests/idempotency_probe.py
|
||||
```
|
||||
|
||||
| Файл | Что проверяет |
|
||||
| --- | --- |
|
||||
| `harness.py` | клиент публичного `tests/client.py`, сбор `X-Instance-Id`, история, ожидание готовности |
|
||||
| `test_lab3.py` | ≥2 реплики на одном токене; 24 параллельных POST с одним ключом через LB; 409 на другое тело; область ключа; валидация ключа; безопасный повтор |
|
||||
| `idempotency_probe.py` | 32 параллельных POST с одним ключом, печатает обезличенную JSON-сводку |
|
||||
| `run_all.py` | запуск unittest-модулей |
|
||||
|
||||
Все проверки идут через `BASE_URL` (по умолчанию `http://127.0.0.1:8080`),
|
||||
не печатают токены и не управляют Docker — это делает action-скрипт публичного
|
||||
`tests/resilience.py`.
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Общая обвязка собственных проверок лабораторной 3.
|
||||
|
||||
Публичный клиент из tests/ переиспользуется, а не копируется: он уже проверяет
|
||||
схему ответа, X-Request-Id, X-Instance-Id, конверт ошибки и challenge. Здесь
|
||||
живут только помощники, специфичные для балансировки и идемпотентности.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TESTS = ROOT / "tests"
|
||||
HERE = Path(__file__).resolve().parent
|
||||
for candidate in (str(TESTS), str(HERE)):
|
||||
if candidate not in sys.path:
|
||||
sys.path.insert(0, candidate)
|
||||
|
||||
from client import Client, Failure # noqa: E402
|
||||
|
||||
DEFAULT_BASE_URL = "http://127.0.0.1:8080"
|
||||
DEFAULT_TIMEOUT = 10.0
|
||||
|
||||
|
||||
def client(timeout: float = DEFAULT_TIMEOUT) -> Client:
|
||||
return Client(os.environ.get("BASE_URL", DEFAULT_BASE_URL), None, timeout)
|
||||
|
||||
|
||||
def instance_ids(api: Client, actor: dict, count: int = 40) -> set[str]:
|
||||
"""Собирает X-Instance-Id разных ответов через LB, не доверяя одному запросу."""
|
||||
seen: set[str] = set()
|
||||
for _ in range(count):
|
||||
seen.add(
|
||||
api.call("GET", "/api/v1/users/me", actor=actor, schema="User")["headers"][
|
||||
"X-Instance-Id"
|
||||
]
|
||||
)
|
||||
return seen
|
||||
|
||||
|
||||
def wait_ready(timeout: float = 120.0) -> None:
|
||||
api = client(timeout=5)
|
||||
deadline = time.monotonic() + timeout
|
||||
last = "no attempts"
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
api.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except (Failure, OSError) as exc:
|
||||
last = str(exc)
|
||||
time.sleep(0.5)
|
||||
raise Failure("stand did not become ready within %.0fs: %s" % (timeout, last))
|
||||
|
||||
|
||||
def history(api: Client, actor: dict, chat_id: str) -> list[dict]:
|
||||
items: list[dict] = []
|
||||
cursor = None
|
||||
for _ in range(1000):
|
||||
path = "/api/v1/chats/%s/messages?limit=100" % chat_id
|
||||
if cursor is not None:
|
||||
path += "&cursor=" + cursor
|
||||
page = api.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
items.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return items
|
||||
raise Failure("history pagination exceeded safety bound")
|
||||
|
||||
|
||||
def unique_key() -> str:
|
||||
return uuid.uuid4().hex
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Печатает обезличенную сводку конкурентного повтора одного Idempotency-Key."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from uuid import uuid4
|
||||
|
||||
import harness
|
||||
|
||||
|
||||
def main() -> int:
|
||||
api = harness.client()
|
||||
alice, bob, _, chat = api.bootstrap()
|
||||
key = uuid4().hex
|
||||
text = "probe-" + uuid4().hex
|
||||
workers = 32
|
||||
barrier = threading.Barrier(workers)
|
||||
|
||||
def worker(_: int) -> dict:
|
||||
local = harness.client(10)
|
||||
barrier.wait()
|
||||
return local.message(alice, chat, text, key=key)
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
responses = list(pool.map(worker, range(workers)))
|
||||
elapsed = time.monotonic() - started
|
||||
bodies = [r["json"] for r in responses]
|
||||
instances = sorted({r["headers"]["X-Instance-Id"] for r in responses})
|
||||
messages = [m for m in harness.history(api, bob, chat["id"]) if m["text"] == text]
|
||||
summary = {
|
||||
"concurrent_requests": workers,
|
||||
"elapsed_seconds": round(elapsed, 3),
|
||||
"statuses": sorted({r["status"] for r in responses}),
|
||||
"distinct_instances": instances,
|
||||
"distinct_message_ids": len({b["id"] for b in bodies}),
|
||||
"history_matches": len(messages),
|
||||
"all_responses_identical": all(b == bodies[0] for b in bodies),
|
||||
}
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
return 0 if (
|
||||
summary["statuses"] == [201]
|
||||
and summary["distinct_message_ids"] == 1
|
||||
and summary["history_matches"] == 1
|
||||
and len(instances) >= 2
|
||||
) else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Собственные проверки лабораторной 3: реплики, LB и общая идемпотентность."""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import unittest
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from uuid import uuid4
|
||||
|
||||
import harness
|
||||
from client import Client
|
||||
|
||||
|
||||
class Lab3Tests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
harness.wait_ready()
|
||||
cls.api = harness.client()
|
||||
cls.alice, cls.bob, cls.eve, cls.chat = cls.api.bootstrap()
|
||||
|
||||
def test_01_at_least_two_instances_and_stable_header(self) -> None:
|
||||
"""LB действительно распределяет один и тот же токен между разными процессами."""
|
||||
observed = harness.instance_ids(self.api, self.alice, 40)
|
||||
self.assertGreaterEqual(len(observed), 2, "less than two X-Instance-Id values through LB")
|
||||
for _ in range(10):
|
||||
me = self.api.call("GET", "/api/v1/users/me", actor=self.alice, schema="User")["json"]
|
||||
self.assertEqual(me["id"], self.alice["id"])
|
||||
|
||||
def test_02_concurrent_same_key_through_lb_creates_one_message(self) -> None:
|
||||
"""Один ключ + одно тело одновременно через разные реплики = одно сообщение."""
|
||||
key = uuid4().hex
|
||||
text = "concurrent-idempotency-" + uuid4().hex
|
||||
workers = 24
|
||||
barrier = threading.Barrier(workers)
|
||||
|
||||
def worker(_: int) -> dict:
|
||||
local = harness.client(10)
|
||||
barrier.wait()
|
||||
return local.message(self.alice, self.chat, text, key=key)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
responses = list(pool.map(worker, range(workers)))
|
||||
|
||||
bodies = [response["json"] for response in responses]
|
||||
instances = {response["headers"]["X-Instance-Id"] for response in responses}
|
||||
self.assertGreaterEqual(len(instances), 2, "concurrent requests did not reach both replicas")
|
||||
self.assertEqual(bodies, [bodies[0]] * workers, "replay returned a different Message")
|
||||
messages = [m for m in harness.history(self.api, self.bob, self.chat["id"]) if m["text"] == text]
|
||||
self.assertEqual(len(messages), 1, "idempotency key created %d messages" % len(messages))
|
||||
self.assertEqual(messages[0], bodies[0])
|
||||
|
||||
def test_03_same_key_other_body_conflicts(self) -> None:
|
||||
key = uuid4().hex
|
||||
first = self.api.message(self.alice, self.chat, "first-" + uuid4().hex, key=key)["json"]
|
||||
replay = self.api.message(self.alice, self.chat, first["text"], key=key)["json"]
|
||||
self.assertEqual(replay, first)
|
||||
self.api.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + self.chat["id"] + "/messages",
|
||||
409,
|
||||
actor=self.alice,
|
||||
body={"text": "different body"},
|
||||
headers={"Idempotency-Key": key},
|
||||
)
|
||||
|
||||
def test_04_key_scope_user_and_chat(self) -> None:
|
||||
key = uuid4().hex
|
||||
text_alice = "scope-a-" + uuid4().hex
|
||||
text_bob = "scope-b-" + uuid4().hex
|
||||
alice_message = self.api.message(self.alice, self.chat, text_alice, key=key)["json"]
|
||||
bob_message = self.api.message(self.bob, self.chat, text_bob, key=key)["json"]
|
||||
self.assertNotEqual(alice_message["id"], bob_message["id"])
|
||||
other_chat = self.api.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=self.alice,
|
||||
body={"title": "Другой чат", "member_ids": [self.alice["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
other = self.api.message(self.alice, other_chat, text_alice, key=key)["json"]
|
||||
self.assertNotEqual(other["id"], alice_message["id"])
|
||||
|
||||
def test_05_key_validation(self) -> None:
|
||||
path = "/api/v1/chats/" + self.chat["id"] + "/messages"
|
||||
for bad in ("", "has space", "bad/slash", "x" * 129):
|
||||
self.api.call(
|
||||
"POST",
|
||||
path,
|
||||
400,
|
||||
actor=self.alice,
|
||||
body={"text": "bad-key"},
|
||||
headers={"Idempotency-Key": bad},
|
||||
)
|
||||
self.api.call("POST", path, 400, actor=self.alice, body={"text": "no key"})
|
||||
for good in ("a", "z" * 128):
|
||||
self.api.message(self.alice, self.chat, "boundary-" + uuid4().hex, key=good)
|
||||
|
||||
def test_06_uncertain_retry_is_safe(self) -> None:
|
||||
"""Повтор с тем же ключом после потери ответа не создаёт второй объект."""
|
||||
key = uuid4().hex
|
||||
text = "retry-after-conflict-" + uuid4().hex
|
||||
first = self.api.message(self.alice, self.chat, text, key=key)["json"]
|
||||
again = self.api.message(self.alice, self.chat, text, key=key)["json"]
|
||||
self.assertEqual(first, again)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
Reference in New Issue
Block a user