forked from mtusi2026/mtusi2026lab3
97 lines
4.3 KiB
Python
97 lines
4.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Параллельные POST с одним Idempotency-Key через балансировщик (разные реплики).
|
|
|
|
Проверяет: в каждом раунде создаётся ровно одно сообщение, все ответы 201 и совпадают побайтно,
|
|
запросы реально обслужили ≥2 реплики. Отдельный раунд: один ключ с РАЗНЫМИ телами → один победитель, остальные 409.
|
|
|
|
Запуск: python3 tools/lab3/idempotency_race.py --base-url http://localhost:8080 --rounds 20 --parallel 40
|
|
"""
|
|
import argparse
|
|
import json
|
|
import os
|
|
import sys
|
|
import threading
|
|
import uuid
|
|
from collections import Counter
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
from common import Api, create_chat, read_history, register_user # noqa: E402
|
|
|
|
|
|
def fire(api, user, chat_id, key, bodies):
|
|
"""Одновременно отправляет len(bodies) запросов (старт по барьеру). Возвращает [(status, instance, json)]."""
|
|
barrier = threading.Barrier(len(bodies))
|
|
results = [None] * len(bodies)
|
|
|
|
def worker(i):
|
|
local = Api(api.base_url, timeout=15) # своё соединение на поток: настоящий параллелизм
|
|
barrier.wait()
|
|
status, headers, payload = local.request(
|
|
'POST', '/api/v1/chats/%s/messages' % chat_id, {'text': bodies[i]}, token=user['token'],
|
|
headers={'Idempotency-Key': key})
|
|
results[i] = (status, headers.get('x-instance-id'), payload)
|
|
|
|
threads = [threading.Thread(target=worker, args=(i,)) for i in range(len(bodies))]
|
|
for t in threads:
|
|
t.start()
|
|
for t in threads:
|
|
t.join()
|
|
return results
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('--base-url', default='http://localhost:8080')
|
|
parser.add_argument('--rounds', type=int, default=20)
|
|
parser.add_argument('--parallel', type=int, default=40)
|
|
parser.add_argument('--output', default=None)
|
|
args = parser.parse_args()
|
|
|
|
api = Api(args.base_url)
|
|
user = register_user(api, 'idem')
|
|
chat_id = create_chat(api, user)
|
|
|
|
instances = Counter()
|
|
failures = []
|
|
for round_no in range(args.rounds):
|
|
key = 'race-%d-%s' % (round_no, uuid.uuid4().hex[:12])
|
|
results = fire(api, user, chat_id, key, ['гонка %d' % round_no] * args.parallel)
|
|
statuses = Counter(r[0] for r in results)
|
|
bodies = {json.dumps(r[2], sort_keys=True) for r in results}
|
|
instances.update(r[1] for r in results)
|
|
if statuses != Counter({201: args.parallel}) or len(bodies) != 1:
|
|
failures.append('round %d: statuses=%s distinct_bodies=%d' % (round_no, dict(statuses), len(bodies)))
|
|
|
|
# Один ключ, разные тела: ровно один 201, остальные 409.
|
|
key = 'race-diff-' + uuid.uuid4().hex[:12]
|
|
results = fire(api, user, chat_id, key, ['вариант %d' % i for i in range(args.parallel)])
|
|
statuses = Counter(r[0] for r in results)
|
|
if statuses != Counter({201: 1, 409: args.parallel - 1}):
|
|
failures.append('different bodies: statuses=%s' % dict(statuses))
|
|
|
|
history = read_history(api, user, chat_id)
|
|
expected = args.rounds + 1
|
|
if len(history) != expected:
|
|
failures.append('history has %d messages, expected %d' % (len(history), expected))
|
|
if len({m['id'] for m in history}) != len(history):
|
|
failures.append('duplicate message ids in history')
|
|
if len(instances) < 2:
|
|
failures.append('only %d replica(s) served the race: %s' % (len(instances), dict(instances)))
|
|
|
|
summary = {
|
|
'rounds': args.rounds, 'parallel_requests_per_round': args.parallel,
|
|
'requests_total': args.rounds * args.parallel + args.parallel,
|
|
'messages_in_history': len(history), 'messages_expected': expected,
|
|
'replicas_that_served_requests': len(instances), 'requests_per_replica': dict(instances),
|
|
'result': 'FAIL' if failures else 'PASS', 'failures': failures,
|
|
}
|
|
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
|
if args.output:
|
|
with open(args.output, 'w', encoding='utf-8') as f:
|
|
json.dump(summary, f, ensure_ascii=False, indent=2)
|
|
return 1 if failures else 0
|
|
|
|
|
|
if __name__ == '__main__':
|
|
raise SystemExit(main())
|