#!/usr/bin/env python3 """Sends one message with the SAME Idempotency-Key many times in parallel through the balancer. Expects every response to be 201 with the same message, at least two replicas answering (X-Instance-Id) and exactly one message in the chat history. Synthetic users only; the token stays in memory. """ import argparse import base64 import json import threading import urllib.error import urllib.request import uuid from collections import Counter parser = argparse.ArgumentParser() parser.add_argument('--base-url', default='http://localhost:8080') parser.add_argument('--parallel', type=int, default=32) parser.add_argument('--rounds', type=int, default=20) args = parser.parse_args() def call(method, path, body=None, headers=None): data = json.dumps(body).encode() if body is not None else None request = urllib.request.Request(args.base_url + path, data=data, method=method, headers={ 'Content-Type': 'application/json', **(headers or {})}) try: with urllib.request.urlopen(request, timeout=10) as response: return response.status, response.headers, json.loads(response.read() or b'null') except urllib.error.HTTPError as error: return error.code, error.headers, json.loads(error.read() or b'null') username = 'race_' + uuid.uuid4().hex[:12] password = 'race-password-' + uuid.uuid4().hex status, _, user = call('POST', '/api/v1/users', {'username': username, 'display_name': 'race', 'password': password}) assert status == 201, status basic = base64.b64encode(f'{username}:{password}'.encode()).decode() status, _, session = call('POST', '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + basic}) assert status == 201, status auth = {'Authorization': 'Bearer ' + session['token']} status, _, chat = call('POST', '/api/v1/chats', {'title': 'race', 'member_ids': [user['id']]}, auth) assert status == 201, status path = f"/api/v1/chats/{chat['id']}/messages" statuses, instances, violations = Counter(), Counter(), 0 for round_number in range(args.rounds): key = uuid.uuid4().hex results = [] barrier = threading.Barrier(args.parallel) def send(): barrier.wait() results.append(call('POST', path, {'text': f'race {round_number}'}, {**auth, 'Idempotency-Key': key})) threads = [threading.Thread(target=send) for _ in range(args.parallel)] for thread in threads: thread.start() for thread in threads: thread.join() ids = {body['id'] for status, _, body in results if status == 201} for status, headers, _ in results: statuses[status] += 1 instances[headers.get('X-Instance-Id', '-')] += 1 if len(ids) != 1: violations += 1 status, _, page = call('GET', path + '?limit=100', headers=auth) texts = [m['text'] for m in page['items']] print(json.dumps({ 'rounds': args.rounds, 'parallel_requests_per_round': args.parallel, 'statuses': dict(statuses), 'requests_per_instance': dict(instances), 'rounds_with_more_than_one_message_id': violations, 'messages_in_history': len(texts), 'distinct_texts_in_history': len(set(texts)), }, indent=2)) ok = violations == 0 and len(texts) == args.rounds == len(set(texts)) and len(instances) >= 2 and set(statuses) == {201} print('PASS' if ok else 'FAIL') raise SystemExit(0 if ok else 1)