50 lines
1.9 KiB
Python
50 lines
1.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Verify concurrent same-key writes are shared across real API instances."""
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import uuid
|
|
from urllib.parse import quote
|
|
|
|
from client import Client, arguments, check, run
|
|
|
|
|
|
def main():
|
|
args = arguments('Concurrent message idempotency across API replicas')
|
|
client = Client(args.base_url, args.ca_file, timeout=10)
|
|
alice, _bob, _eve, chat = client.bootstrap()
|
|
text = 'Concurrent idempotency ' + uuid.uuid4().hex
|
|
key = 'race-' + uuid.uuid4().hex
|
|
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
|
|
|
def post_once(_):
|
|
return client.call('POST', path, 201, actor=alice,
|
|
body={'text': text},
|
|
headers={'Idempotency-Key': key}, schema='Message')
|
|
|
|
with ThreadPoolExecutor(max_workers=16) as pool:
|
|
responses = list(pool.map(post_once, range(32)))
|
|
|
|
messages = [response['json'] for response in responses]
|
|
check(all(message == messages[0] for message in messages),
|
|
'concurrent same-key requests returned different messages')
|
|
instances = {response['headers']['X-Instance-Id'] for response in responses}
|
|
check(len(instances) >= 2,
|
|
'concurrent requests did not reach at least two API replicas')
|
|
|
|
history = []
|
|
cursor = None
|
|
while True:
|
|
query = '?limit=100' + ('&cursor=' + quote(cursor, safe='') if cursor else '')
|
|
page = client.call('GET', path + query, actor=alice, schema='MessagePage')['json']
|
|
history.extend(page['items'])
|
|
cursor = page['next_cursor']
|
|
if cursor is None:
|
|
break
|
|
check(sum(message['text'] == text for message in history) == 1,
|
|
'same-key concurrent write created more than one history item')
|
|
print('PASS: 32 concurrent same-key POSTs returned one message across '
|
|
+ str(len(instances)) + ' API instances; history contains one record.')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
run(main)
|