chore(solution): port lab3 sources

This commit is contained in:
2026-11-20 03:05:34 +03:00
parent ec540a1a72
commit 083d0d80cc
44 changed files with 2745 additions and 1 deletions
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
import sys
import threading
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, check
WORKERS = 20
def main():
c = Client()
alice, _, _, chat = c.bootstrap()
key = uuid.uuid4().hex
text = 'Одновременный повтор ' + key
barrier = threading.Barrier(WORKERS)
results, errors = [], []
lock = threading.Lock()
def send():
barrier.wait()
try:
r = c.message(alice, chat, text, key=key)
with lock:
results.append((r['json'], r['headers']['X-Instance-Id']))
except AssertionError as exc:
with lock:
errors.append(str(exc))
threads = [threading.Thread(target=send) for _ in range(WORKERS)]
for t in threads:
t.start()
for t in threads:
t.join()
history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100', actor=alice, schema='MessagePage')['json']['items']
stored = [m for m in history if m['text'] == text]
instances = sorted({i for _, i in results})
ids = {m['id'] for m, _ in results}
print('parallel requests with one key:', WORKERS)
print('successful responses (201):', len(results))
print('failed requests:', len(errors), errors[:3])
print('distinct message ids in responses:', len(ids))
print('messages stored in history:', len(stored))
print('instances that served requests:', instances)
check(not errors, 'some requests failed')
check(len(ids) == 1 and len(stored) == 1, 'duplicate message created')
check(all(m == results[0][0] for m, _ in results), 'replayed responses differ')
check(len(instances) >= 2, 'requests were not spread across replicas')
print('OK: exactly one message created')
if __name__ == '__main__':
main()
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
mkdir -p secrets
chmod 700 secrets
if [ ! -f secrets/postgres_password ]; then
head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n' > secrets/postgres_password
fi
password=$(cat secrets/postgres_password)
[ -f secrets/database_url ] ||
printf 'postgres://messenger:%s@postgres:5432/messenger?sslmode=disable\n' "$password" > secrets/database_url
[ -f secrets/cache_url ] ||
printf 'redis://redis:6379/0\n' > secrets/cache_url
chmod 644 secrets/postgres_password secrets/database_url secrets/cache_url
echo "secrets ready in ./secrets"
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
ENGINE=${ENGINE:-$(command -v podman >/dev/null 2>&1 && echo podman || echo docker)}
COMPOSE=${COMPOSE:-$([ "$ENGINE" = podman ] && echo podman-compose || echo "docker compose")}
$COMPOSE stop lb api redis postgres
$COMPOSE start postgres redis api lb
+37
View File
@@ -0,0 +1,37 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
ENGINE=${ENGINE:-$(command -v podman >/dev/null 2>&1 && echo podman || echo docker)}
COMPOSE=${COMPOSE:-$([ "$ENGINE" = podman ] && echo podman-compose || echo "docker compose")}
PROJECT=${PROJECT:-messenger-lab3}
replicas() {
$ENGINE ps -aq --no-trunc --filter "label=com.docker.compose.project=$PROJECT" --filter "label=com.docker.compose.service=api" | sort
}
wait_healthy() {
for _ in $(seq 1 60); do
if [ "$($ENGINE inspect -f '{{.State.Health.Status}}' "$1" 2>/dev/null)" = "healthy" ]; then
return 0
fi
sleep 1
done
echo "replica $1 did not become healthy" >&2
exit 1
}
$ENGINE build --build-arg "BUILD_ID=${BUILD_ID:-$(date +%s)}" -t localhost/messenger-api:lab3 .
$COMPOSE run --rm migrate
for old in $(replicas); do
before=$(replicas)
$ENGINE stop -t 10 "$old"
$ENGINE rm "$old"
$COMPOSE up -d --no-deps --no-recreate api
for id in $(replicas); do
if ! echo "$before" | grep -q "$id"; then
wait_healthy "$id"
fi
done
sleep 2
done
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
set -eu
ENGINE=${ENGINE:-$(command -v podman >/dev/null 2>&1 && echo podman || echo docker)}
PROJECT=${PROJECT:-messenger-lab3}
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}"
for id in $($ENGINE ps -q --filter "label=com.docker.compose.project=$PROJECT" --filter "label=com.docker.compose.service=api"); do
if [ "$($ENGINE inspect -f '{{.Config.Hostname}}' "$id")" = "$TARGET_INSTANCE_ID" ]; then
$ENGINE stop -t 10 "$id" >/dev/null
exit 0
fi
done
exit 1