#!/usr/bin/env python3 """Один Idempotency-Key, N параллельных запросов через LB (то есть через разные реплики). Половина запросов с телом A, половина с телом B: должно появиться ровно одно сообщение, каждый 201 возвращает его, другое тело получает 409. Запуск: python3 student-tests/idempotency_race.py --base-url http://localhost:8080""" from concurrent.futures import ThreadPoolExecutor import json from pathlib import Path import sys import threading import uuid sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) from client import Client, arguments, check, run # noqa: E402 def main(): args = arguments('Parallel same-key POST race', lambda p: p.add_argument('--parallel', type=int, default=32)) c = Client(args.base_url, args.ca_file) alice, bob, _, chat = c.bootstrap() path = '/api/v1/chats/' + chat['id'] + '/messages' key = 'race-' + uuid.uuid4().hex texts = ['гонка A ' + key, 'гонка B ' + key] barrier = threading.Barrier(args.parallel) def send(i): local = Client(args.base_url, args.ca_file) barrier.wait() r = local.call('POST', path, [201, 409], actor=alice, body={'text': texts[i % 2]}, headers={'Idempotency-Key': key}, schema='Message') return r['status'], r['json'], r['headers']['X-Instance-Id'] with ThreadPoolExecutor(args.parallel) as pool: results = list(pool.map(send, range(args.parallel))) created = [body for status, body, _ in results if status == 201] check(created, 'no request succeeded') winner = created[0] check(all(body == winner for body in created), 'replicas returned different messages for one key') check(all(body['error']['code'] == 'conflict' for status, body, _ in results if status == 409), '409 without conflict code') statuses = {texts[i % 2]: set() for i in range(2)} for i, (status, _, _) in enumerate(results): statuses[texts[i % 2]].add(status) check(statuses[winner['text']] == {201}, 'winning body must always get 201') check(statuses[next(t for t in texts if t != winner['text'])] == {409}, 'other body must always get 409') instances = {inst for _, _, inst in results} check(len(instances) >= 2, 'race did not reach two replicas') history = c.call('GET', path + '?limit=100', actor=bob, schema='MessagePage')['json']['items'] stored = [m for m in history if key in m['text']] check(stored == [winner], 'expected exactly one stored message equal to the replayed one') # Тот же ключ у другого пользователя независим. other = c.message(bob, chat, texts[0], key=key)['json'] check(other['id'] != winner['id'] and other['sender_id'] == bob['id'], 'key scope leaked across users') print(json.dumps({'parallel': args.parallel, 'replicas_hit': len(instances), 'created_201': len(created), 'conflict_409': args.parallel - len(created), 'stored_messages': len(stored)}, ensure_ascii=False)) print('PASS: concurrent same-key POSTs through different replicas created exactly one message') if __name__ == '__main__': run(main)