215 lines
8.6 KiB
Python
215 lines
8.6 KiB
Python
"""Гонки (уровень 4): одновременные запросы по отдельным соединениям.
|
||
|
||
- 100 сообщений от 10 клиентов → ровно 100 уникальных в истории
|
||
(лаба 1, сохраняется);
|
||
- 10 одновременных регистраций одного username → одна 201, девять 409:
|
||
уникальность держит индекс PostgreSQL, а не проверка «сначала SELECT»;
|
||
- 10 одновременных отправок одного тела с одним `Idempotency-Key` →
|
||
десять 201 с одним `id`, в истории одно сообщение (лаба 3). Через LB
|
||
ещё нужна пара пересекающихся по времени ответов разных реплик: иначе
|
||
«одновременно через разные реплики» не доказано.
|
||
|
||
Параллельность настоящая: 10 потоков стартуют одновременно за
|
||
`threading.Barrier`, у каждого свой клиент и своё соединение, открытое
|
||
до барьера. Тест требует, чтобы хотя бы 2 запроса были в полёте
|
||
одновременно, иначе гонка не доказана.
|
||
"""
|
||
|
||
import threading
|
||
import time
|
||
from collections import Counter
|
||
from collections.abc import Callable
|
||
from concurrent.futures import ThreadPoolExecutor
|
||
|
||
import httpx
|
||
|
||
from helpers import (
|
||
USERS,
|
||
ClientFactory,
|
||
assert_error,
|
||
create_chat,
|
||
instance_id,
|
||
new_key,
|
||
read_history,
|
||
register,
|
||
send,
|
||
unique_password,
|
||
unique_username,
|
||
)
|
||
|
||
CLIENTS = 10
|
||
MESSAGES_PER_CLIENT = 10
|
||
# попыток собрать пересечение ответов разных реплик в одной гонке ключа
|
||
SAME_KEY_ATTEMPTS = 5
|
||
|
||
|
||
class InFlight:
|
||
"""Сколько запросов одновременно в полёте — максимум за прогон."""
|
||
|
||
def __init__(self) -> None:
|
||
self._lock = threading.Lock()
|
||
self.current = 0
|
||
self.peak = 0
|
||
|
||
def __enter__(self) -> None:
|
||
with self._lock:
|
||
self.current += 1
|
||
self.peak = max(self.peak, self.current)
|
||
|
||
def __exit__(self, *_exc: object) -> None:
|
||
with self._lock:
|
||
self.current -= 1
|
||
|
||
|
||
def run_together[T](
|
||
clients: list[httpx.Client],
|
||
work: Callable[[int, httpx.Client], T],
|
||
) -> list[T]:
|
||
"""Каждый клиент в своём потоке; старт — одновременно, за барьером."""
|
||
barrier = threading.Barrier(len(clients))
|
||
|
||
def worker(index: int) -> T:
|
||
own = clients[index]
|
||
# соединение открыто до барьера: после него сразу запросы
|
||
own.get("/health/live")
|
||
barrier.wait()
|
||
return work(index, own)
|
||
|
||
with ThreadPoolExecutor(max_workers=len(clients)) as pool:
|
||
return list(pool.map(worker, range(len(clients))))
|
||
|
||
|
||
def test_100_messages_from_10_clients(
|
||
client: httpx.Client,
|
||
new_client: ClientFactory,
|
||
) -> None:
|
||
users = [register(client, f"racer{index}") for index in range(CLIENTS)]
|
||
chat = create_chat(client, *users, title="Гонка")
|
||
in_flight = InFlight()
|
||
|
||
def send_all(index: int, own: httpx.Client) -> list[tuple[int, str, str]]:
|
||
results = []
|
||
for number in range(MESSAGES_PER_CLIENT):
|
||
text = f"client {index} message {number}"
|
||
with in_flight:
|
||
response = send(own, users[index], chat, text)
|
||
message_id = response.json().get("id", "") if response.is_success else ""
|
||
results.append((response.status_code, text, message_id))
|
||
return results
|
||
|
||
rows = run_together([new_client() for _ in range(CLIENTS)], send_all)
|
||
results = [row for group in rows for row in group]
|
||
|
||
statuses = Counter(status for status, _, _ in results)
|
||
items, sizes = read_history(client, users[0], chat, limit=30)
|
||
ids = [item["id"] for item in items]
|
||
keys = [(item["created_at"], item["id"]) for item in items]
|
||
|
||
print(
|
||
f"statuses={dict(statuses)} peak_in_flight={in_flight.peak} "
|
||
f"history={len(items)} unique_ids={len(set(ids))} pages={sizes}",
|
||
)
|
||
assert statuses == {201: CLIENTS * MESSAGES_PER_CLIENT}
|
||
assert in_flight.peak >= 2, "requests never overlapped: race is not proven"
|
||
assert len(items) == CLIENTS * MESSAGES_PER_CLIENT
|
||
assert len(set(ids)) == len(ids)
|
||
assert keys == sorted(keys)
|
||
# в истории ровно то, что подтвердил сервер, и тексты не перепутаны
|
||
assert {(item["id"], item["text"]) for item in items} == {
|
||
(message_id, text) for _, text, message_id in results
|
||
}
|
||
assert {item["sender_id"] for item in items} == {user["id"] for user in users}
|
||
|
||
|
||
def test_parallel_registration_of_one_username(new_client: ClientFactory) -> None:
|
||
username = unique_username("same")
|
||
in_flight = InFlight()
|
||
|
||
def register_same(_index: int, own: httpx.Client) -> httpx.Response:
|
||
body = {
|
||
"username": username,
|
||
"display_name": "Двойник",
|
||
"password": unique_password(),
|
||
}
|
||
with in_flight:
|
||
return own.post(USERS, json=body)
|
||
|
||
responses = run_together([new_client() for _ in range(CLIENTS)], register_same)
|
||
statuses = Counter(response.status_code for response in responses)
|
||
|
||
print(f"statuses={dict(statuses)} peak_in_flight={in_flight.peak}")
|
||
assert in_flight.peak >= 2, "requests never overlapped: race is not proven"
|
||
assert statuses == {201: 1, 409: CLIENTS - 1}
|
||
for response in responses:
|
||
if response.status_code == 409:
|
||
assert_error(response, 409, "conflict")
|
||
else:
|
||
assert response.json()["username"] == username
|
||
|
||
|
||
def race_one_key(
|
||
client: httpx.Client,
|
||
new_client: ClientFactory,
|
||
) -> tuple[list[tuple[float, float, httpx.Response]], int, list]:
|
||
"""10 потоков шлют одно тело с одним ключом; (начало, конец, ответ)."""
|
||
alice, bob = register(client, "alice"), register(client, "bob")
|
||
chat = create_chat(client, alice, bob, title="Гонка ключа")
|
||
key = new_key()
|
||
in_flight = InFlight()
|
||
|
||
def send_same(
|
||
_index: int, own: httpx.Client
|
||
) -> tuple[float, float, httpx.Response]:
|
||
with in_flight:
|
||
started = time.monotonic()
|
||
response = send(own, alice, chat, "одно сообщение на всех", key=key)
|
||
return started, time.monotonic(), response
|
||
|
||
rows = run_together([new_client() for _ in range(CLIENTS)], send_same)
|
||
items, _ = read_history(client, bob, chat, limit=100)
|
||
return rows, in_flight.peak, items
|
||
|
||
|
||
def check_one_message(rows: list, peak: int, items: list) -> None:
|
||
statuses = Counter(response.status_code for _, _, response in rows)
|
||
ids = {response.json()["id"] for _, _, response in rows if response.is_success}
|
||
print(
|
||
f"statuses={dict(statuses)} peak_in_flight={peak} ids={len(ids)} "
|
||
f"history={len(items)}",
|
||
)
|
||
assert peak >= 2, "requests never overlapped: race is not proven"
|
||
assert statuses == {201: CLIENTS}
|
||
assert len(ids) == 1
|
||
assert [item["id"] for item in items] == list(ids)
|
||
|
||
|
||
def test_same_key_at_once(client: httpx.Client, new_client: ClientFactory) -> None:
|
||
rows, peak, items = race_one_key(client, new_client)
|
||
check_one_message(rows, peak, items)
|
||
|
||
|
||
def test_same_key_through_replicas(
|
||
client: httpx.Client,
|
||
new_client: ClientFactory,
|
||
replicas: int,
|
||
) -> None:
|
||
"""Пара пересекающихся по времени запросов с разными X-Instance-Id: то
|
||
же одно сообщение, хотя ключ проверяли разные процессы."""
|
||
for attempt in range(1, SAME_KEY_ATTEMPTS + 1):
|
||
rows, peak, items = race_one_key(client, new_client)
|
||
check_one_message(rows, peak, items)
|
||
crossed = {
|
||
(instance_id(a), instance_id(b))
|
||
for a_start, a_end, a in rows
|
||
for b_start, b_end, b in rows
|
||
if instance_id(a) < instance_id(b) and a_start < b_end and b_start < a_end
|
||
}
|
||
served = Counter(instance_id(response) for _, _, response in rows)
|
||
print(f"attempt {attempt}: served={dict(served)} overlapping pairs={crossed}")
|
||
if crossed:
|
||
return
|
||
raise AssertionError(
|
||
f"no overlapping requests on different replicas in {SAME_KEY_ATTEMPTS} "
|
||
f"attempts ({replicas} replicas expected)",
|
||
)
|