before level 3 initial commit

This commit is contained in:
2026-11-05 17:03:42 +03:00
parent 0ab3a341aa
commit 8cd25e448f
32 changed files with 1616 additions and 4 deletions
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
"""Same Idempotency-Key sent concurrently through the LB must hit several replicas and create one message."""
import argparse
import json
import sys
import threading
import uuid
from collections import Counter
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, Failure, check, run # noqa: E402
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--base-url', default=None)
p.add_argument('--parallel', type=int, default=20)
p.add_argument('--rounds', type=int, default=5)
args = p.parse_args()
c = Client(args.base_url)
alice, bob, _, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/messages'
instances = Counter()
for round_no in range(args.rounds):
key = 'race-' + uuid.uuid4().hex
text = 'Конкурентный повтор %d %s' % (round_no, key)
barrier = threading.Barrier(args.parallel)
results, errors = [], []
def send():
barrier.wait()
try:
r = c.call('POST', path, 201, actor=alice, body={'text': text}, headers={'Idempotency-Key': key}, schema='Message')
results.append((r['headers']['X-Instance-Id'], r['json']))
except Failure as exc:
errors.append(str(exc))
threads = [threading.Thread(target=send) for _ in range(args.parallel)]
for t in threads:
t.start()
for t in threads:
t.join()
check(not errors, 'concurrent POST failed: ' + '; '.join(errors[:3]))
bodies = {json.dumps(body, sort_keys=True) for _, body in results}
check(len(bodies) == 1, 'replicas returned different messages for one key')
served = Counter(instance for instance, _ in results)
instances.update(served)
print('round %d: %d responses, 1 message, replicas %s' % (round_no, len(results), dict(served)))
c.call('POST', path, 409, actor=alice, body={'text': text + ' другой'}, headers={'Idempotency-Key': key})
page = c.call('GET', path + '?limit=100', actor=bob, schema='MessagePage')['json']
texts = [m['text'] for m in page['items']]
check(len(texts) == args.rounds and len(set(texts)) == args.rounds, 'expected exactly one message per key')
check(len(instances) >= 2, 'all requests hit one replica; LB does not balance')
print('PASS: %d keys x %d parallel requests -> %d messages via %d replicas %s'
% (args.rounds, args.parallel, len(texts), len(instances), dict(instances)))
if __name__ == '__main__':
run(main)
+3
View File
@@ -0,0 +1,3 @@
@echo off
rem Windows entry point for tests/resilience.py: runs restart.sh with Git Bash.
"%ProgramFiles%\Git\bin\sh.exe" "%~dp0restart.sh"
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
# Restart the LB, every API replica and PostgreSQL. The pgdata volume stays; nothing is re-seeded.
docker compose --env-file .env stop lb api
docker compose --env-file .env restart postgres
# Brings back all replicas (including one left stopped by stop-one.sh); migrate re-runs as a no-op.
docker compose --env-file .env up -d --wait
+3
View File
@@ -0,0 +1,3 @@
@echo off
rem Windows entry point for tests/resilience.py: runs stop-one.sh with Git Bash.
"%ProgramFiles%\Git\bin\sh.exe" "%~dp0stop-one.sh"
+28
View File
@@ -0,0 +1,28 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
# Stop exactly ONE API replica and leave it stopped. DB, LB and volumes are untouched.
# X-Instance-Id is the container hostname, i.e. the short Docker container ID.
# Restore afterwards with: docker compose --env-file .env up -d --wait
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
case "$TARGET_INSTANCE_ID" in
*[!0-9a-f]*) valid=no ;;
*) valid=yes ;;
esac
if [ "$valid" = no ] || [ "${#TARGET_INSTANCE_ID}" -lt 12 ]; then
echo "TARGET_INSTANCE_ID is not a container ID" >&2
exit 2
fi
project="${COMPOSE_PROJECT_NAME:-messenger-lab3}"
matches=$(docker ps -q --no-trunc \
--filter "label=com.docker.compose.project=$project" \
--filter "label=com.docker.compose.service=api" | grep "^$TARGET_INSTANCE_ID" || true)
count=$(printf '%s' "$matches" | grep -c . || true)
if [ "$count" -ne 1 ]; then
echo "expected one running api container for $TARGET_INSTANCE_ID, found $count" >&2
exit 1
fi
name=$(docker inspect --format '{{.Name}}' "$matches")
# Graceful: SIGTERM, then SIGKILL after 8 s; returns before the test's 10 s limit.
docker stop --time 8 "$matches" >/dev/null
echo "stopped api replica ${name#/} ($TARGET_INSTANCE_ID)"