#!/usr/bin/env python3 from concurrent.futures import ThreadPoolExecutor import threading import uuid from client import Client, Failure, arguments, check, run def main(): args = arguments('Concurrent Idempotency-Key check through the load balancer') c = Client(args.base_url, args.ca_file) alice, bob, eve, chat = c.bootstrap() path = '/api/v1/chats/' + chat['id'] + '/messages' parallel = 32 key = 'idem-' + uuid.uuid4().hex barrier = threading.Barrier(parallel) def send(_): local = Client(args.base_url, args.ca_file) barrier.wait() return local.call('POST', path, 201, actor=alice, body={'text': 'same'}, headers={'Idempotency-Key': key}, schema='Message') with ThreadPoolExecutor(max_workers=parallel) as pool: results = list(pool.map(send, range(parallel))) ids = {r['json']['id'] for r in results} instances = {r['headers']['X-Instance-Id'] for r in results} check(len(ids) == 1, 'parallel requests produced %d messages' % len(ids)) check(len(instances) >= 2, 'requests were served by one instance only') check(len({r['json']['created_at'] for r in results}) == 1, 'created_at differs between replays') listing = c.call('GET', path, actor=alice, schema='MessagePage')['json']['items'] check(sum(1 for m in listing if m['text'] == 'same') == 1, 'duplicate message in history') c.call('POST', path, 409, actor=alice, body={'text': 'other'}, headers={'Idempotency-Key': key}) 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!'}) other = c.call('POST', path, 201, actor=bob, body={'text': 'same'}, headers={'Idempotency-Key': key}, schema='Message')['json'] check(other['id'] not in ids, 'key must be scoped per user') print('PASS: %d parallel requests, 1 message, %d instances' % (parallel, len(instances))) if __name__ == '__main__': run(main)