forked from mtusi2026/mtusi2026lab2
165 lines
7.3 KiB
Python
165 lines
7.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Concurrency evidence for level 4: N clients write M messages in parallel.
|
|
|
|
Command (see REPORT.md and `make concurrency`):
|
|
python3 student-tests/concurrency.py --clients 10 --messages-per-client 10 \
|
|
--output evidence/concurrency.json
|
|
|
|
Expectation: every acknowledged message is stored exactly once, the full history
|
|
contains exactly clients*messages_per_client unique messages and the order over
|
|
pages is strictly increasing by (created_at, id). No retries are hidden: any
|
|
failed write is reported and fails the run.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import json
|
|
from pathlib import Path
|
|
import sys
|
|
import threading
|
|
import time
|
|
import uuid
|
|
from urllib.parse import quote
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
|
|
from client import Client, Failure, LAB, arguments, check, timestamp # noqa: E402
|
|
|
|
MESSAGES_PATH = '/api/v1/chats/%s/messages'
|
|
|
|
|
|
def build_fixture(base_url, ca_file, clients):
|
|
"""One user per client plus a single chat everybody belongs to."""
|
|
master = Client(base_url, ca_file, timeout=15)
|
|
master.call('GET', '/health/ready', schema='Health')
|
|
actors = [master.user('conc%d' % index) for index in range(clients)]
|
|
chat = master.call('POST', '/api/v1/chats', 201, actor=actors[0],
|
|
body={'title': 'Конкурентная запись',
|
|
'member_ids': [actor['id'] for actor in actors]},
|
|
schema='Chat')['json']
|
|
check(set(chat['member_ids']) == {actor['id'] for actor in actors},
|
|
'chat membership mismatch')
|
|
return master, actors, chat
|
|
|
|
|
|
def write_phase(base_url, ca_file, actors, chat, messages_per_client, prefix):
|
|
"""Each client writes its own slice of messages, all starting at once."""
|
|
barrier = threading.Barrier(len(actors))
|
|
|
|
def worker(index):
|
|
client = Client(base_url, ca_file, timeout=15)
|
|
actor = actors[index]
|
|
barrier.wait()
|
|
acknowledged, errors = [], []
|
|
started = time.monotonic()
|
|
for message_index in range(messages_per_client):
|
|
text = '%s-%03d-%03d' % (prefix, index, message_index)
|
|
try:
|
|
message = client.message(actor, chat, text)['json']
|
|
acknowledged.append((text, message['id']))
|
|
except Failure as exc:
|
|
errors.append('%s: %s' % (text, exc))
|
|
return {'client_index': index, 'acknowledged': acknowledged, 'errors': errors,
|
|
'duration_seconds': round(time.monotonic() - started, 3)}
|
|
|
|
started = time.monotonic()
|
|
with ThreadPoolExecutor(max_workers=len(actors)) as pool:
|
|
results = list(pool.map(worker, range(len(actors))))
|
|
return results, round(time.monotonic() - started, 3)
|
|
|
|
|
|
def read_whole_history(client, actor, chat):
|
|
items, cursor, pages = [], None, 0
|
|
while True:
|
|
query = '?limit=100' + ('' if cursor is None else '&cursor=' + quote(cursor, safe=''))
|
|
page = client.call('GET', MESSAGES_PATH % chat['id'] + query, actor=actor,
|
|
schema='MessagePage')['json']
|
|
items.extend(page['items'])
|
|
pages += 1
|
|
cursor = page['next_cursor']
|
|
check(pages < 100, 'pagination did not terminate')
|
|
if cursor is None:
|
|
return items, pages
|
|
|
|
|
|
def main():
|
|
def configure(parser):
|
|
parser.add_argument('--clients', type=int, default=10)
|
|
parser.add_argument('--messages-per-client', type=int, default=10)
|
|
parser.add_argument('--output', default=None,
|
|
help='Optional JSON report path, no session data inside')
|
|
|
|
args = arguments('Concurrent writes from independent HTTP clients', configure)
|
|
check(1 <= args.clients <= 64, 'clients must be 1..64')
|
|
check(1 <= args.messages_per_client <= 200, 'messages-per-client must be 1..200')
|
|
expected = args.clients * args.messages_per_client
|
|
prefix = 'conc-' + uuid.uuid4().hex[:8]
|
|
|
|
master, actors, chat = build_fixture(args.base_url, args.ca_file, args.clients)
|
|
results, elapsed = write_phase(args.base_url, args.ca_file, actors, chat,
|
|
args.messages_per_client, prefix)
|
|
acknowledged = [pair for result in results for pair in result['acknowledged']]
|
|
errors = [error for result in results for error in result['errors']]
|
|
history, pages = read_whole_history(master, actors[0], chat)
|
|
|
|
stored_texts = [message['text'] for message in history]
|
|
stored_ids = [message['id'] for message in history]
|
|
expected_texts = {'%s-%03d-%03d' % (prefix, client, index)
|
|
for client in range(args.clients)
|
|
for index in range(args.messages_per_client)}
|
|
missing = sorted(expected_texts.difference(stored_texts))
|
|
keys = [(timestamp(message['created_at']), uuid.UUID(message['id']).int)
|
|
for message in history]
|
|
ordered_correctly = all(keys[index] < keys[index + 1] for index in range(len(keys) - 1))
|
|
|
|
report = {
|
|
'lab': LAB,
|
|
'workload': 'closed-loop parallel POST messages from independent clients',
|
|
'clients': args.clients,
|
|
'messages_per_client': args.messages_per_client,
|
|
'expected_messages': expected,
|
|
'acknowledged_201': len(acknowledged),
|
|
'stored_in_history': len(history),
|
|
'unique_stored_ids': len(set(stored_ids)),
|
|
'unique_stored_texts': len(set(stored_texts)),
|
|
'duplicates': len(stored_ids) - len(set(stored_ids)),
|
|
'missing_texts': missing,
|
|
'failed_writes': len(errors),
|
|
'write_errors': errors[:10],
|
|
'history_pages': pages,
|
|
'history_order_strictly_increasing': ordered_correctly,
|
|
'writers_elapsed_seconds': elapsed,
|
|
'successful_rps': round(len(acknowledged) / elapsed, 3) if elapsed else None,
|
|
'per_client': [{'client_index': result['client_index'],
|
|
'acknowledged': len(result['acknowledged']),
|
|
'errors': len(result['errors']),
|
|
'duration_seconds': result['duration_seconds']}
|
|
for result in sorted(results, key=lambda item: item['client_index'])],
|
|
'note': ('Client-observed timings: closed-loop, single Docker host, no retries. '
|
|
'Latency percentiles are intentionally absent here (see make load).'),
|
|
}
|
|
text = json.dumps(report, ensure_ascii=False, indent=2)
|
|
if args.output:
|
|
destination = Path(args.output)
|
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
destination.write_text(text + '\n')
|
|
print(text)
|
|
check(not errors, 'some parallel writes failed')
|
|
check(len(acknowledged) == expected, 'not every write was acknowledged')
|
|
check(len(history) == expected, 'history holds %d messages instead of %d'
|
|
% (len(history), expected))
|
|
check(not missing, 'messages missing from the history')
|
|
check(len(set(stored_ids)) == expected, 'duplicate message ids in the history')
|
|
check(ordered_correctly, 'history is not strictly ordered by (created_at, id)')
|
|
print('PASS: %d parallel messages from %d clients stored exactly once' %
|
|
(expected, args.clients))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
main()
|
|
except (Failure, ValueError, OSError) as exc:
|
|
print('FAIL:', exc)
|
|
raise SystemExit(1)
|