"""Конкурентные и отрицательные проверки общей идемпотентности через LB.""" from concurrent.futures import ThreadPoolExecutor from pathlib import Path import sys import uuid sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) from client import Client, check c = Client() alice, bob, eve, chat = c.bootstrap() path = '/api/v1/chats/' + chat['id'] + '/messages' key = uuid.uuid4().hex def send(i): return Client().call('POST', path, 201, actor=alice, body={'text': 'Общий конкурентный ключ', **({'attachment_ids': []} if i % 2 else {})}, headers={'Idempotency-Key': key}, schema='Message') with ThreadPoolExecutor(max_workers=16) as pool: results = list(pool.map(send, range(32))) check(len({r['json']['id'] for r in results}) == 1, 'повтор создал дубли') instances = {r['headers']['X-Instance-Id'] for r in results} check(len(instances) >= 2, 'не наблюдаются разные процессы') c.call('POST', path, 409, actor=alice, body={'text': 'Другой текст'}, headers={'Idempotency-Key': key}) for invalid in ('', 'bad key', 'x' * 129, 'bad/key'): c.call('POST', path, 400, actor=alice, body={'text': 'Проверка'}, headers={'Idempotency-Key': invalid}) c.call('POST', path, 404, actor=eve, body={'text': 'Проверка'}, headers={'Idempotency-Key': key}) other = c.message(bob, chat, 'Независимый пользователь', key=key)['json'] check(other['id'] != results[0]['json']['id'], 'ключ не изолирован по пользователю') second = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Другой чат', 'member_ids': [alice['id']]}, schema='Chat')['json'] c.message(alice, second, 'Независимый чат', key=key) race_key = uuid.uuid4().hex def conflict_race(i): return Client().call('POST', path, [201,409], actor=alice, body={'text': 'Тело ' + str(i%2)}, headers={'Idempotency-Key': race_key}, schema='Message') with ThreadPoolExecutor(max_workers=16) as pool: race = list(pool.map(conflict_race, range(16))) check(sum(r['status']==201 for r in race)==8, 'неверная сериализация разных тел') check(sum(r['status']==409 for r in race)==8, 'не обнаружен конфликт параллельных тел') check(len({r['json']['id'] for r in race if r['status']==201})==1, 'гонка разных тел создала дубли') c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice) c.call('POST', path, 401, actor=alice, body={'text': 'Общий конкурентный ключ'}, headers={'Idempotency-Key': key}) print('PASS: 32 одинаковых и 16 конфликтующих параллельных запросов,', len(instances), 'реплики; один результат, конфликт, валидация, ACL, области ключа и отзыв сессии.')