forked from mtusi2026/mtusi2026lab3
48 lines
2.4 KiB
Python
48 lines
2.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Focused Lab 3 level-4 checks; run only against the local synthetic Compose stack."""
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import json, time, uuid
|
|
from client import Client, Failure, arguments, check, run
|
|
|
|
def main():
|
|
args = arguments("Concurrent idempotency and replica diversity checks")
|
|
c = Client(args.base_url, args.ca_file, timeout=5)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
instances = set()
|
|
for _ in range(40):
|
|
instances.add(c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers'].get('X-Instance-Id',''))
|
|
instances.discard('')
|
|
check(len(instances) >= 2, 'load balancer did not expose at least two distinct API instances')
|
|
|
|
key = 'parallel-' + uuid.uuid4().hex
|
|
body = {'text':'Одна запись при конкурентном повторе'}
|
|
def send(_):
|
|
return c.call(
|
|
'POST',
|
|
'/api/v1/chats/' + chat['id'] + '/messages',
|
|
expected=201,
|
|
actor=alice,
|
|
body=body,
|
|
headers={'Idempotency-Key': key},
|
|
schema='Message'
|
|
)
|
|
with ThreadPoolExecutor(max_workers=12) as pool:
|
|
responses = list(pool.map(send, range(12)))
|
|
ids = {r['json']['id'] for r in responses}
|
|
check(len(ids) == 1, 'concurrent identical keys produced different message IDs')
|
|
check(all(r['status'] == 201 for r in responses), 'identical retry must return HTTP 201')
|
|
|
|
changed = c.call('POST', '/api/v1/chats/'+chat['id']+'/messages', expected=409, actor=alice,
|
|
body={'text':'Другой текст'}, headers={'Idempotency-Key':key})
|
|
missing = c.call('POST', '/api/v1/chats/'+chat['id']+'/messages', expected=400, actor=alice,
|
|
body={'text':'Без ключа'}, headers={})
|
|
invalid = c.call('POST', '/api/v1/chats/'+chat['id']+'/messages', expected=400, actor=alice,
|
|
body={'text':'Неверный ключ'}, headers={'Idempotency-Key':'bad key'})
|
|
print(json.dumps({'distinct_instances':sorted(instances), 'parallel_requests':len(responses),
|
|
'distinct_message_ids':len(ids), 'changed_body_status':changed['status'],
|
|
'missing_key_status':missing['status'], 'invalid_key_status':invalid['status']}, ensure_ascii=False))
|
|
print('PASS: concurrent cross-replica idempotency, key validation, and instance visibility')
|
|
|
|
if __name__ == '__main__':
|
|
run(main)
|