#!/usr/bin/env python3 """Конкурентный повтор POST сообщения с одним Idempotency-Key через LB (lab3). Каждый раунд: N потоков (каждый со своим соединением) по барьеру одновременно отправляют одинаковый body с одинаковым ключом. Ожидаем: все ответы 201 с одним и тем же Message, запросы обслужены ≥2 репликами, в истории ровно одно сообщение. Затем тот же ключ с другим body — 409; тот же ключ в другом чате — новое сообщение. """ from concurrent.futures import ThreadPoolExecutor import json import threading import uuid import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) # публичный client.py from client import Client, Failure, arguments, check, run from resilience import history def main(): def configure(p): p.add_argument('--rounds', type=int, default=10) p.add_argument('--parallel', type=int, default=16) p.add_argument('--output', default=None) args = arguments('Concurrent Idempotency-Key replay across replicas', configure) c = Client(args.base_url, args.ca_file) alice, bob, eve, chat = c.bootstrap() other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Второй чат', 'member_ids': [alice['id'], bob['id']]}, schema='Chat')['json'] rounds = [] all_instances = set() for r in range(args.rounds): key = 'conc-' + uuid.uuid4().hex text = 'Конкурентный повтор %d %s' % (r, key) barrier = threading.Barrier(args.parallel) def worker(_): local = Client(args.base_url, args.ca_file, timeout=10) barrier.wait() try: resp = local.message(alice, chat, text, key=key) return resp['status'], resp['json'], resp['headers'].get('X-Instance-Id') except Failure as exc: return 'fail', str(exc), None with ThreadPoolExecutor(max_workers=args.parallel) as pool: results = list(pool.map(worker, range(args.parallel))) statuses = [s for s, _, _ in results] check(all(s == 201 for s in statuses), 'round %d: not all 201: %s' % (r, statuses)) bodies = {json.dumps(b, sort_keys=True) for _, b, _ in results} check(len(bodies) == 1, 'round %d: replays returned different messages' % r) instances = {i for _, _, i in results} all_instances |= instances stored = [m for m in history(c, bob, chat) if m['text'] == text] check(len(stored) == 1, 'round %d: %d messages stored for one key' % (r, len(stored))) # Другой body с тем же ключом — 409, не новое сообщение. c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice, body={'text': text + ' (изменён)'}, headers={'Idempotency-Key': key}) rounds.append({'round': r, 'requests': args.parallel, 'status_201': statuses.count(201), 'distinct_messages': len(bodies), 'stored': len(stored), 'instances': len(instances)}) # Ключ уникален в пределах чата: тот же ключ в другом чате создаёт своё сообщение. key = 'scope-' + uuid.uuid4().hex a = c.message(alice, chat, 'scope', key=key)['json'] b = c.message(alice, other, 'scope', key=key)['json'] check(a['id'] != b['id'], 'key leaked across chats') # Другой пользователь с тем же ключом — тоже независим. d = c.message(bob, chat, 'scope', key=key)['json'] check(d['id'] != a['id'], 'key leaked across users') # Без ключа и с неверным ключом — 400. path = '/api/v1/chats/' + chat['id'] + '/messages' c.call('POST', path, 400, actor=alice, body={'text': 'x'}) c.call('POST', path, 400, actor=alice, body={'text': 'x'}, headers={'Idempotency-Key': 'bad key!'}) c.call('POST', path, 400, actor=alice, body={'text': 'x'}, headers={'Idempotency-Key': 'k' * 129}) # Повтор проверяет доступ: посторонний с тем же ключом получает 404. c.call('POST', path, 404, actor=eve, body={'text': 'scope'}, headers={'Idempotency-Key': key}) check(len(all_instances) >= 2, 'concurrent requests were served by fewer than 2 replicas') summary = {'rounds': args.rounds, 'parallel_per_round': args.parallel, 'distinct_instances_seen': len(all_instances), 'duplicates_found': sum(x['stored'] - 1 for x in rounds), 'per_round': rounds} text = json.dumps(summary, ensure_ascii=False, indent=2) if args.output: with open(args.output, 'w', encoding='utf-8') as f: f.write(text + '\n') print(text) print('PASS: concurrent Idempotency-Key replay produced exactly one message per key.') if __name__ == '__main__': run(main)