Implement lab3 grade 4: balanced API replicas, shared idempotency and failure tests

This commit is contained in:
2026-11-02 20:54:35 +03:00
parent 0ab3a341aa
commit 5332cda400
55 changed files with 102293 additions and 19 deletions
+55
View File
@@ -0,0 +1,55 @@
"""Run inside API network: same session and simultaneous requests at distinct processes."""
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import socket
import sys
import threading
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, check
def main():
clients = [Client('http://' + ip + ':8080') for ip in sorted(set(socket.gethostbyname_ex('api')[2]))]
check(len(clients) == 2, 'Expected two API addresses in Docker DNS')
c = clients[0]
alice, bob, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/messages'
key = uuid.uuid4().hex
barrier = threading.Barrier(16)
def send(n):
barrier.wait(timeout=10)
return clients[n % 2].call('POST', path, 201, actor=alice,
body={'attachment_ids': [], 'text': 'Параллельный повтор'} if n % 2 else
{'text': 'Параллельный повтор'},
headers={'Idempotency-Key': key}, schema='Message')
with ThreadPoolExecutor(max_workers=16) as pool:
responses = list(pool.map(send, range(16)))
messages = [x['json'] for x in responses]
instances = sorted({x['headers']['X-Instance-Id'] for x in responses})
check(len(instances) == 2, 'Requests did not reach distinct API processes')
check(all(x == messages[0] for x in messages), 'Concurrent responses differ')
history = clients[1].call('GET', path, actor=bob, schema='MessagePage')['json']['items']
check(history == [messages[0]], 'Concurrent requests created duplicates')
clients[1].call('POST', path, 409, actor=alice, body={'text': 'Другой body'}, headers={'Idempotency-Key': key})
# Scope is user + chat; an independent user and another chat may reuse the key.
other = clients[1].message(bob, chat, 'Другой пользователь', key=key)['json']
chat2 = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Другой чат', 'member_ids': [alice['id']]}, schema='Chat')['json']
third = clients[1].message(alice, chat2, 'Другой чат', key=key)['json']
check(len({messages[0]['id'], other['id'], third['id']}) == 3, 'Incorrect idempotency scope')
for invalid in ('', 'contains space', 'x' * 129):
c.call('POST', path, 400, actor=alice, body={'text': 'Invalid key'}, headers={'Idempotency-Key': invalid})
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
clients[1].call('POST', path, 401, actor=alice, body={'text': 'Параллельный повтор'},
headers={'Idempotency-Key': key})
print(json.dumps(dict(result='PASS', parallel_requests=16, api_instances=instances,
unique_messages=1, scope_conflict_logout='PASS'), ensure_ascii=False))
if __name__ == '__main__':
main()
+173
View File
@@ -0,0 +1,173 @@
#!/usr/bin/env python3
"""Grade 4 only: each process failure and sequential replacement under one fixed load."""
import argparse
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import sys
import threading
import time
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path[:0] = [str(ROOT / 'tests'), str(ROOT / 'scripts')]
from client import Client, Failure, check
from resilience import history
from labctl import command, compose, containers, replace_one, save, wait_api
# IPv4-only published LB: avoid slow localhost IPv6 fallback on Windows.
os.environ.setdefault('BASE_URL', 'http://127.0.0.1:8080')
def quantile(values, q):
ordered = sorted(values)
return round(ordered[min(len(ordered) - 1, int((len(ordered) - 1) * q))] * 1000, 3) if values else None
def scenario(mode, target=None, seconds=32):
c = Client(timeout=2)
alice, bob, eve, chat = c.bootstrap()
original_key = uuid.uuid4().hex
original = c.message(alice, chat, 'Подтверждено до воздействия', key=original_key)['json']
instances_before = {c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id']
for _ in range(20)}
check(len(instances_before) == 2, 'Need two distinct processes before experiment')
samples, confirmations, resources, action = [], [], [], {}
stop = threading.Event()
start = time.monotonic()
def worker(n):
client = Client(timeout=2)
key = uuid.uuid4().hex
text = 'load-' + key
while not stop.is_set():
for operation in ('write', 'read'):
at = time.monotonic()
try:
if operation == 'write':
result = client.message(alice, chat, text, key=key)
confirmations.append(result['json'])
key = uuid.uuid4().hex
text = 'load-' + key
else:
result = client.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100',
actor=bob, schema='MessagePage')
check(original in result['json']['items'], 'Confirmed data missing during action')
samples.append(dict(at=round(at - start, 5), end=round(time.monotonic() - start, 5),
elapsed=time.monotonic() - at, operation=operation,
ok=True, status=result['status'], instance=result['headers']['X-Instance-Id']))
except Failure as exc:
# Failure only contains sanitized method/path/status or transport type.
samples.append(dict(at=round(at - start, 5), end=round(time.monotonic() - start, 5),
elapsed=time.monotonic() - at, operation=operation,
ok=False, error=str(exc)))
stop.wait(.03)
def affect():
stop.wait(5)
action['start'] = time.monotonic() - start
try:
if mode == 'stop':
before = containers('api')
command('docker', 'stop', '--time', '8', target['id'])
action['stop_completed'] = time.monotonic() - start
after = containers('api', all_states=True)
check(next(x for x in after if x['id'] == target['id'])['status'] == 'exited', 'Target still running')
action.update(before=before, after_stop=after)
stop.wait(10)
compose('up', '-d', '--no-deps', '--no-recreate', 'api')
wait_api()
else:
initial = containers('api')
changes = []
for item in initial:
changes.append(replace_one(item['id']))
action['replacements'] = changes
save('rolling-processes.json', dict(before=initial, replacements=changes, after=containers('api')))
action['end'] = time.monotonic() - start
except Exception as exc:
action['error'] = type(exc).__name__
stop.set()
def monitor():
while not stop.is_set():
ids = [x['id'] for x in containers()]
rows = command('docker', 'stats', '--no-stream', '--format', '{{json .}}', *ids)
resources.append(dict(at=round(time.monotonic() - start, 3),
containers=[json.loads(x) for x in rows.splitlines()]))
stop.wait(5)
with ThreadPoolExecutor(max_workers=6) as pool:
workers = [pool.submit(worker, n) for n in range(4)]
impact = pool.submit(affect)
monitor_job = pool.submit(monitor)
stop.wait(seconds)
stop.set()
impact.result()
monitor_job.result()
for job in workers:
job.result()
check('error' not in action, 'Action failed: ' + action.get('error', ''))
wait_api()
all_messages = history(c, bob, chat)
by_id = {x['id']: x for x in all_messages}
check(len(by_id) == len(all_messages), 'Duplicate IDs')
check(len({x['text'] for x in all_messages}) == len(all_messages), 'Uncertain retry duplicated a message')
check(all(by_id.get(x['id']) == x for x in [original, *confirmations]), 'Confirmed data lost')
check(c.message(alice, chat, original['text'], key=original_key)['json'] == original,
'Pre-action idempotency result changed after replacement')
elapsed = max(x['end'] for x in samples)
errors = [x for x in samples if not x['ok']]
successful = [x for x in samples if x['ok']]
latencies = [x['elapsed'] for x in successful]
result = dict(mode=mode, target=target['name'] if target else None,
at_utc=datetime.now(timezone.utc).isoformat(), duration_seconds=round(elapsed, 3),
warmup_seconds=5, concurrency=4, profile='each worker: POST + GET, then 30ms pause; closed loop',
initial_messages=1, final_messages=len(all_messages), confirmations=len(confirmations),
operations=len(samples), successful_operations=len(successful), errors=len(errors),
error_percent=round(100 * len(errors) / len(samples), 3),
successful_rps=round(len(successful) / elapsed, 3),
latency_success_ms=dict(p50=quantile(latencies, .5), p95=quantile(latencies, .95), p99=quantile(latencies, .99)),
instances_before=sorted(instances_before), action=action, resources=resources,
confirmed_data_lost=0, duplicate_messages=0)
if mode == 'stop':
done = action['stop_completed']
post = [x for x in samples if done <= x['at'] < done + 8]
recovery = {}
for op in ('read', 'write'):
valid = [x for x in post if x['ok'] and x['operation'] == op]
check(bool(valid), op + ' did not continue after stop')
recovery[op] = round(min(x['end'] for x in valid) - action['start'], 3)
check(recovery[op] <= 10, 'Recovery exceeded 10 seconds')
relevant_errors = [x for x in errors if action['start'] <= x['at'] < done + 8]
result['first_success_after_stop_seconds_from_action_start'] = recovery
result['last_error_seconds_from_action_start'] = round(
max((x['end'] - action['start'] for x in relevant_errors), default=0), 3)
result['successful_rps_8s_after_stop'] = round(sum(x['ok'] for x in post) / 8, 3)
else:
check(len(action['replacements']) == 2, 'Both containers must be replaced')
check(len(errors) / len(samples) < .2, 'Too many errors during sequential replacement')
filename = 'load-' + (target['name'] if target else 'rolling') + '.json'
result['samples'] = samples
save(filename, result)
print(json.dumps({k: v for k, v in result.items() if k not in ('samples', 'resources', 'action')}, ensure_ascii=False))
print('Evidence:', 'evidence/' + filename, flush=True)
def main():
p = argparse.ArgumentParser()
p.add_argument('--mode', choices=['failures', 'rolling', 'all'], default='all')
args = p.parse_args()
wait_api()
if args.mode in ('failures', 'all'):
for target in containers('api'):
scenario('stop', target)
if args.mode in ('rolling', 'all'):
scenario('rolling')
print('PASS: grade 4 load scenarios; no scale or multi-node research track.')
if __name__ == '__main__':
main()