#!/usr/bin/env python3 import argparse import json import sys import threading import uuid from concurrent.futures import ThreadPoolExecutor from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'tests')) from client import Client def main(): p = argparse.ArgumentParser() p.add_argument('--base-url', default='http://localhost:8080') p.add_argument('--parallel', type=int, default=20) a = p.parse_args() c = Client(a.base_url) alice, bob, _eve, chat = c.bootstrap() path = '/api/v1/chats/' + chat['id'] + '/messages' r = c.call('POST', path, 400, actor=alice, body={'text': 'без ключа'}) print('1) POST без Idempotency-Key ->', r['status'], r['json']['error']['code']) key = 'demo-' + uuid.uuid4().hex[:8] r1 = c.message(alice, chat, 'Привет', key=key) r2 = c.message(alice, chat, 'Привет', key=key) print('2) ключ %s: первый ответ %s id=%s (реплика %s)' % (key, r1['status'], r1['json']['id'], r1['headers']['X-Instance-Id'])) print(' повтор того же: %s id=%s (реплика %s) -> %s' % ( r2['status'], r2['json']['id'], r2['headers']['X-Instance-Id'], 'ТО ЖЕ сообщение' if r1['json'] == r2['json'] else 'ОШИБКА: другое')) r = c.call('POST', path, 409, actor=alice, body={'text': 'Другой текст'}, headers={'Idempotency-Key': key}) print('3) тот же ключ, другое тело ->', r['status'], r['json']['error']['code']) key = 'race-' + uuid.uuid4().hex[:8] barrier = threading.Barrier(a.parallel) def send(_): local = Client(a.base_url) barrier.wait() x = local.message(alice, chat, 'Гонка', key=key) return x['json']['id'], x['headers']['X-Instance-Id'] with ThreadPoolExecutor(a.parallel) as pool: res = list(pool.map(send, range(a.parallel))) ids = {i for i, _ in res} inst = {s for _, s in res} history = c.call('GET', path + '?limit=100', actor=bob, schema='MessagePage')['json']['items'] stored = [m for m in history if m['text'] == 'Гонка'] print('4) %d параллельных POST с ключом %s через реплики %s' % (a.parallel, key, sorted(inst))) print(' разных id в ответах: %d; сообщений в истории: %d -> %s' % ( len(ids), len(stored), 'дублей нет' if len(ids) == 1 and len(stored) == 1 else 'ДУБЛЬ!')) print('История чата:', json.dumps([m['text'] for m in history], ensure_ascii=False)) if __name__ == '__main__': main()