forked from mtusi2026/mtusi2026lab3
43 lines
2.4 KiB
Python
43 lines
2.4 KiB
Python
from concurrent.futures import ThreadPoolExecutor
|
|
import json
|
|
from pathlib import Path
|
|
import sys
|
|
import uuid
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
|
from client import Client, check
|
|
|
|
c = Client()
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
path = '/api/v1/chats/' + chat['id']
|
|
key = uuid.uuid4().hex
|
|
|
|
|
|
def send(_):
|
|
result = Client().message(alice, chat, 'Concurrent shared key', key=key)
|
|
return result['json'], result['headers']['X-Instance-Id']
|
|
|
|
|
|
with ThreadPoolExecutor(max_workers=16) as pool:
|
|
replies = list(pool.map(send, range(32)))
|
|
check(len({item['id'] for item, _ in replies}) == 1, 'duplicate concurrent write')
|
|
instances = sorted({instance for _, instance in replies})
|
|
check(len(instances) >= 2, 'concurrent requests did not cross replicas')
|
|
history = c.call('GET', path + '/messages', actor=bob, schema='MessagePage')['json']
|
|
check(len(history['items']) == 1, 'concurrent replay duplicated history')
|
|
replay = c.message(alice, chat, 'Concurrent shared key', key=key, attachments=[])['json']
|
|
check(replay == replies[0][0], 'empty optional attachments changed idempotency semantics')
|
|
c.call('POST', path + '/messages', 409, actor=alice, body={'text': 'changed'}, headers={'Idempotency-Key': key})
|
|
c.call('POST', path + '/messages', 400, actor=alice, body={'text': 'valid', 'sender_id': eve['id']}, headers={'Idempotency-Key': key})
|
|
c.call('POST', path + '/messages', 400, actor=alice, body={'text': ' '}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
|
c.call('POST', '/api/v1/chats', 400, actor=alice, body={'title': 'bad', 'member_ids': [alice['id'], alice['id']]})
|
|
c.call('GET', '/api/v1/chats/not-a-uuid/messages', 400, actor=alice)
|
|
c.call('GET', path + '/messages?cursor=broken', 400, actor=alice)
|
|
c.call('POST', path + '/messages', 400, actor=alice, raw=b'{', headers={'Content-Type': 'application/json', 'Idempotency-Key': key})
|
|
c.message(alice, chat, 'second')
|
|
page = c.call('GET', path + '/messages?limit=1', actor=alice, schema='MessagePage')['json']
|
|
other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'other', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
|
from urllib.parse import quote
|
|
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + quote(page['next_cursor']), 400, actor=alice)
|
|
print(json.dumps({'result': 'PASS', 'parallel_requests': 32, 'instances': instances, 'created_messages_for_shared_key': 1}))
|