Completed for a grade of three

This commit is contained in:
2026-10-23 14:11:11 +03:00
parent a3dbcd6ba4
commit 92c2fdc254
54 changed files with 1221 additions and 92 deletions
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""Sends one message with the SAME Idempotency-Key many times in parallel through the balancer.
Expects every response to be 201 with the same message, at least two replicas answering (X-Instance-Id)
and exactly one message in the chat history. Synthetic users only; the token stays in memory.
"""
import argparse
import base64
import json
import threading
import urllib.error
import urllib.request
import uuid
from collections import Counter
parser = argparse.ArgumentParser()
parser.add_argument('--base-url', default='http://localhost:8080')
parser.add_argument('--parallel', type=int, default=32)
parser.add_argument('--rounds', type=int, default=20)
args = parser.parse_args()
def call(method, path, body=None, headers=None):
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(args.base_url + path, data=data, method=method, headers={
'Content-Type': 'application/json', **(headers or {})})
try:
with urllib.request.urlopen(request, timeout=10) as response:
return response.status, response.headers, json.loads(response.read() or b'null')
except urllib.error.HTTPError as error:
return error.code, error.headers, json.loads(error.read() or b'null')
username = 'race_' + uuid.uuid4().hex[:12]
password = 'race-password-' + uuid.uuid4().hex
status, _, user = call('POST', '/api/v1/users', {'username': username, 'display_name': 'race', 'password': password})
assert status == 201, status
basic = base64.b64encode(f'{username}:{password}'.encode()).decode()
status, _, session = call('POST', '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + basic})
assert status == 201, status
auth = {'Authorization': 'Bearer ' + session['token']}
status, _, chat = call('POST', '/api/v1/chats', {'title': 'race', 'member_ids': [user['id']]}, auth)
assert status == 201, status
path = f"/api/v1/chats/{chat['id']}/messages"
statuses, instances, violations = Counter(), Counter(), 0
for round_number in range(args.rounds):
key = uuid.uuid4().hex
results = []
barrier = threading.Barrier(args.parallel)
def send():
barrier.wait()
results.append(call('POST', path, {'text': f'race {round_number}'}, {**auth, 'Idempotency-Key': key}))
threads = [threading.Thread(target=send) for _ in range(args.parallel)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
ids = {body['id'] for status, _, body in results if status == 201}
for status, headers, _ in results:
statuses[status] += 1
instances[headers.get('X-Instance-Id', '-')] += 1
if len(ids) != 1:
violations += 1
status, _, page = call('GET', path + '?limit=100', headers=auth)
texts = [m['text'] for m in page['items']]
print(json.dumps({
'rounds': args.rounds,
'parallel_requests_per_round': args.parallel,
'statuses': dict(statuses),
'requests_per_instance': dict(instances),
'rounds_with_more_than_one_message_id': violations,
'messages_in_history': len(texts),
'distinct_texts_in_history': len(set(texts)),
}, indent=2))
ok = violations == 0 and len(texts) == args.rounds == len(set(texts)) and len(instances) >= 2 and set(statuses) == {201}
print('PASS' if ok else 'FAIL')
raise SystemExit(0 if ok else 1)
+3 -3
View File
@@ -1,7 +1,7 @@
#!/bin/sh
# Restarts the API, PostgreSQL and Redis, keeping the named volume (no `down -v`, no re-seed).
# Restarts the balancer, every API replica, PostgreSQL and Redis, keeping the named volume (no `down -v`, no re-seed).
set -eu
cd "$(dirname "$0")/.."
docker compose stop api redis postgres
docker compose up -d --wait postgres redis api
docker compose stop lb api redis postgres
docker compose up -d --wait
+22
View File
@@ -0,0 +1,22 @@
#!/bin/sh
# Stops the ONE API replica named by TARGET_INSTANCE_ID and leaves it stopped (no DB/LB/volume changes).
# The replica's X-Instance-Id is its container hostname, i.e. the short container id.
# Restore afterwards with: docker compose start api
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
case "$TARGET_INSTANCE_ID" in
*[!0-9a-f]* | "") echo "unexpected instance id" >&2; exit 2 ;;
esac
# Only containers of the api service are candidates, so a wrong id can never stop the database or the balancer.
container=$(docker compose ps -q api | grep "^$TARGET_INSTANCE_ID" || true)
if [ -z "$container" ] || [ "$(printf '%s\n' "$container" | wc -l)" -ne 1 ]; then
echo "no single api replica matches $TARGET_INSTANCE_ID" >&2
exit 1
fi
docker stop --time 8 "$container" >/dev/null