"""Проверки общего результата повтора через LB и несколько API.""" from concurrent.futures import ThreadPoolExecutor import json from pathlib import Path import sys import uuid sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) from client import Client, arguments, check, run def main(): args = arguments('Shared idempotency through LB') c = Client(args.base_url, args.ca_file) alice, bob, eve, chat = c.bootstrap() key = uuid.uuid4().hex text = 'Один результат для конкурентных повторов' def send(_): return Client(args.base_url, args.ca_file).message(alice, chat, text, key=key) with ThreadPoolExecutor(max_workers=16) as pool: responses = list(pool.map(send, range(32))) first = responses[0]['json'] check(all(r['json'] == first and r['status'] == 201 for r in responses), 'replay differs') instances = {r['headers']['X-Instance-Id'] for r in responses} check(len(instances) >= 2, 'race did not cross API replicas') path = '/api/v1/chats/' + chat['id'] + '/messages' history = c.call('GET', path, actor=bob, schema='MessagePage')['json']['items'] check(len(history) == 1 and history[0] == first, 'concurrent replay created duplicates') c.call('POST', path, 409, body={'text': 'Другой текст'}, actor=alice, headers={'Idempotency-Key': key}) for invalid in ['', 'bad key', 'a' * 129]: c.call('POST', path, 400, body={'text': text}, actor=alice, headers={'Idempotency-Key': invalid}) c.call('POST', path, 400, body={'text': text}, actor=alice) # Тот же ключ независим для другого пользователя и другого чата. other = c.message(bob, chat, text, key=key)['json'] check(other['id'] != first['id'], 'key scope must include user') chat2 = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Second', 'member_ids': [alice['id']]}, schema='Chat')['json'] check(c.message(alice, chat2, text, key=key)['json']['id'] != first['id'], 'key scope must include chat') # Пробелы JSON не изменяют смысл текста и не должны менять результат. replay = c.call('POST', path, 201, actor=alice, raw=json.dumps({'text': text}, indent=2).encode(), headers={'Content-Type': 'application/json', 'Idempotency-Key': key}, schema='Message') check(replay['json'] == first, 'JSON formatting changed idempotency') c.call('POST', path, 404, actor=eve, body={'text': text}, headers={'Idempotency-Key': key}) c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice) c.call('POST', path, 401, actor=alice, body={'text': text}, headers={'Idempotency-Key': key}) result = dict(status='PASS', concurrent_requests=32, observed_instances=len(instances), messages_after_race=len(history), conflict=409, invalid_key=400, logout=401) Path('evidence').mkdir(exist_ok=True) Path('evidence/idempotency.json').write_text(json.dumps(result, indent=2)) print('PASS: shared idempotency, scope, conflict and auth on replay') if __name__ == '__main__': run(main)