2 Commits
36 changed files with 1944 additions and 36 deletions
+5 -12
View File
@@ -1,13 +1,6 @@
# Copy to .env for your LOCAL synthetic test environment; never commit .env. # Copy to .env and choose your own LOCAL synthetic password. Never commit .env.
# These are logical interface suggestions; map actual framework names in REPORT.md. POSTGRES_USER=lab3
APP_HOST=0.0.0.0 POSTGRES_PASSWORD=
APP_PORT=8080 POSTGRES_DB=messenger
APP_ENV=lab
SESSION_TTL_SECONDS=3600 SESSION_TTL_SECONDS=3600
# Choose credentials locally. File paths contain no secret values. LAB3_HOST_PORT=8080
DATABASE_URL_FILE=/run/secrets/database_url
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
SESSION_STORE=postgres
CACHE_URL_FILE=/run/secrets/cache_url
API_REPLICAS=2
IDEMPOTENCY_TTL_SECONDS=86400
+6
View File
@@ -0,0 +1,6 @@
*.sh text eol=lf
*.py text eol=lf
*.sql text eol=lf
*.cmd text eol=crlf
*.ps1 text eol=lf
*.cfg text eol=lf
+28
View File
@@ -0,0 +1,28 @@
name: Lab 3 application
on: [push, pull_request]
permissions:
contents: read
jobs:
compose:
runs-on: ubuntu-24.04
timeout-minutes: 15
env:
COMPOSE_PROJECT_NAME: mtusi-lab3-ci
PYTHONUTF8: '1'
steps:
- uses: actions/checkout@v4
- name: Create local synthetic credentials
run: python3 scripts/init_env.py
- name: Smoke, persistence and both replica failures
shell: bash
run: |
set -o pipefail
sh scripts/verify-linux.sh 2>&1 | tee evidence/results-ci.txt
- name: Stop the test stack and retain data volume
if: always()
run: docker compose --env-file .env stop
- uses: actions/upload-artifact@v4
if: always()
with:
name: lab3-verification
path: evidence/results-ci.txt
+1
View File
@@ -1,4 +1,5 @@
# Local/private state # Local/private state
evidence/last-stopped.txt
.env .env
.env.* .env.*
!.env.example !.env.example
+9
View File
@@ -0,0 +1,9 @@
FROM python:3.12.10-slim-bookworm
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 APP_HOST=0.0.0.0 APP_PORT=8080
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app/ ./app/
COPY migrations/ ./migrations/
EXPOSE 8080
CMD ["python", "-m", "app.main"]
+159 -24
View File
@@ -1,37 +1,172 @@
# Отчёт — лабораторная 3 # Лабораторная работа №3. Балансировка и отказ API-реплики
- Автор, группа: TODO **Сабитов Бронислав Александрович, БВТ-2302**
- Целевая оценка; выбранный трек 5, если нужен: TODO Дисциплина «Высоконагруженные приложения». Целевая оценка — **3**.
- Commit/PR: TODO после публикации Запрос на слияние: https://gitea.privcloud.tech/mtusi2026/mtusi2026lab3/pulls/177
- Использованные источники, библиотеки и помощь ИИ: TODO
## Запуск из чистого clone ## Запуск в Windows из чистого clone или распакованного архива
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. Нужны запущенный Docker Desktop с Linux containers и Compose v2.20+, Python 3.9+ для проверок. Python и PostgreSQL для самого сервера устанавливаются в контейнеры. Команды выполнять в корне проекта, где находится compose.yaml.
## Архитектура и решения Полный запуск и проверка в PowerShell:
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. ~~~powershell
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\verify-windows.ps1 -Port 8083
~~~
## Доказательства критериев Скрипт создаёт локальный .env со случайным паролем, если файла ещё нет, собирает образы, ждёт готовности LB, запускает публичные и собственные проверки, перезапускает весь стенд, останавливает по очереди каждую API и восстанавливает обе. Вывод сохраняется в evidence/results-windows.txt. Порт 8083 можно заменить свободным. HTTP доступен по http://127.0.0.1:8083. Корневой URL не является страницей приложения, проверка готовности — /health/ready.
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | Только запустить приложение без испытаний отказа:
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. ~~~powershell
python -X utf8 scripts/init_env.py
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build --wait --wait-timeout 90
~~~
## Эксперименты и отказы При таком запуске порт берётся из LAB3_HOST_PORT в .env, по умолчанию 8080. Занятый порт можно изменить в .env перед запуском. .env не добавляется в Git. POSTGRES_PASSWORD в примере намеренно пустой, скрипт init_env.py заполняет только новый локальный файл.
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. Остановка с сохранением данных:
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | ~~~powershell
| --- | --- | --- | --- | docker compose --env-file .env stop
| TODO | TODO | TODO | TODO | ~~~
## Ограничения и следующие шаги Повторный запуск сохраняет данные и ещё действительные сессии. Для намеренного полного удаления учебного стенда вместе с данными применяется `docker compose --env-file .env down -v`. В restart/failover эта команда не используется.
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. ## Linux и команды make
Нужны Docker с Compose, Python 3.9+ и make. В корне проекта:
~~~sh
python3 scripts/init_env.py
chmod +x scripts/restart.sh scripts/stop-one.sh scripts/restore.sh
docker compose --env-file .env up -d --build --wait --wait-timeout 90
make check
make test
make test-persistence ACTION_SCRIPT=scripts/restart.sh
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
~~~
Последний тест оставляет выбранную реплику остановленной. Восстановление:
~~~sh
export TARGET_INSTANCE_ID="$(cat evidence/last-stopped.txt)"
sh scripts/restore.sh
~~~
Весь сценарий, включая отдельный отказ каждой из двух реплик:
~~~sh
sh scripts/verify-linux.sh
~~~
Для другого порта задаются LAB3_HOST_PORT в .env и BASE_URL, например `BASE_URL=http://localhost:8083 sh scripts/verify-linux.sh`. В Windows публичные Python-проверки вызываются с UTF-8 режимом, их исходники сохранены.
Дополнительная проверка истечения сессии:
~~~powershell
$env:BASE_URL = 'http://127.0.0.1:8083'
python -X utf8 scripts/check_expiry.py
~~~
Она временно пересоздаёт обе API с TTL 2 секунды, проверяет 401 после истечения и возвращает исходные настройки. Выполнять отдельно от других испытаний.
## Архитектура
~~~text
HTTP-клиент
|
127.0.0.1:8080 (или выбранный порт)
|
HAProxy lb
+--> api1 --+
+--> api2 --+--> PostgreSQL db --> named volume pgdata
^
migrate (разовый запуск до API)
~~~
В compose.yaml описаны пять сервисов. api1 и api2 — разные контейнеры с одинаковой реализацией FastAPI/Uvicorn, одним процессом на контейнер и собственными стабильными X-Instance-Id. Наружу публикуется только порт LB на loopback. У API и БД нет опубликованных host-портов. Отдельных container_name нет.
Версии образов закреплены: Python 3.12.10-slim-bookworm, PostgreSQL 16.16-bookworm, HAProxy 3.0.31-alpine. Версии FastAPI, Uvicorn, psycopg, pydantic и argon2-cffi закреплены в requirements.txt. Конфигурация HAProxy копируется в собственный образ при сборке.
Единственный источник истины — PostgreSQL. В нём находятся users, chats, chat_members, messages, sessions, message_requests и schema_migrations. Сессии общие для обеих API, на локальном диске API нет состояния, необходимого для корректности запросов. Закрепления клиента за репликой нет.
Из ЛР №2 сохранены регистрация, пользователи, чаты, членство, сообщения, keyset-пагинация, единый формат ошибок, Basic-вход, Bearer, TTL и logout. Пароли хешируются Argon2id. В БД хранится SHA-256-дайджест случайного Bearer-токена. Basic применяется на /api/v1/auth/sessions, регистрация и health остаются публичными. X-User-Id не предоставляет доступа.
Первоначальная миграция 001 сохранена. Отдельный сервис migrate под блокировкой PostgreSQL последовательно применяет отсутствующие версии, добавляя 002 с таблицей идемпотентности. Обе версии фиксируются одной транзакцией при первоначальном запуске. API ждут успешного завершения migrate и сами DDL не выполняют. Повторный запуск не дублирует миграции.
## Балансировка и обнаружение отказа
HAProxy использует roundrobin и проверяет /health/ready каждой API раз в секунду. Readiness проверяет БД и установленную миграцию 002. Один неуспешный healthcheck исключает backend, один успешный возвращает его. Timeout проверки 1 секунда, соединения 1 секунда, ответа backend 5 секунд. Docker DNS 127.0.0.11 используется через resolvers, адреса сервисов обновляются, включая пересоздание контейнера.
Заголовки X-Request-Id и X-Instance-Id добавляются ко всем ответам API, включая ошибки и health. При ошибке соединения ответ самого LB может не содержать их. LB не повторяет POST автоматически. Клиент повторяет неясный результат сообщения с прежними ключом и телом.
Uvicorn завершает текущие запросы в течение 2 секунд после SIGTERM, Compose даёт API до 4 секунд. stop-one останавливает ровно выбранный сервис с таймаутом 3 секунды и оставляет его остановленным. restore проверяет через docker inspect, что этот процесс действительно остановлен, а другая API, LB и PostgreSQL работают, затем возвращает реплику и ждёт её появления через LB.
## Общая идемпотентность
Для POST /api/v1/chats/{chat_id}/messages требуется один Idempotency-Key вида [A-Za-z0-9._:-]{1,128}. Неверный или отсутствующий ключ возвращает 400.
Область ключа — пользователь, POST данного endpoint, канонический UUID чата и сам ключ. Таблица message_requests обслуживает только этот метод и путь. Разные пользователи и чаты независимы.
JSON проверяется и нормализуется перед вычислением отпечатка тела. Порядок полей не влияет на результат, отсутствие attachment_ids и пустой [] равны. Вложения с непустым списком начинаются в следующей лабораторной.
В одной транзакции берётся общая advisory transaction lock по области ключа, проверяется прежний результат, записываются сообщение и запись идемпотентности. Точный составной первичный ключ дополнительно защищает область. Повтор в течение 24 часов возвращает 201 и исходное Message, другое тело возвращает 409. SHA-256 здесь применяется к отпечатку тела и токену, пароли обрабатывает Argon2id.
Ответ отправляется после COMMIT. При rollback обе записи отменяются. Повтор заново проходит проверку сессии и членства. Истёкшая запись ключа заменяется при следующем использовании, само старое сообщение сохраняется.
## Результаты проверок
Исходники задания README.md, COURSE.md, контракты, публичные Python-тесты и Makefile сохранены. Собственные проверки добавлены отдельными файлами. tests/contract_edge_tests.py и tests/student_tests.py перенесены из собственного решения ЛР №2, с учётом обязательного ключа в ЛР №3.
Основной реальный вывод — [evidence/results-make-2026-12-01.txt](evidence/results-make-2026-12-01.txt). Команды make выполнялись в Linux-контейнере с GNU Make 4.4.1, Python 3.12.16 и Docker Compose v2.35.0. BASE_URL=http://lb:8080, все запросы проходили через HAProxy. Контейнер проверки присоединялся к сети стенда и использовал Docker socket для операторских hooks.
Дополнительно полный сценарий Windows выполнен в отдельном проекте с новой БД через 127.0.0.1:18086. Его вывод — [evidence/results-windows.txt](evidence/results-windows.txt). Проверка TTL — [evidence/results-expiry-2026-12-01.txt](evidence/results-expiry-2026-12-01.txt).
| Требование уровня 3 | Проверка | Наблюдаемый результат |
| --- | --- | --- |
| Две API, одна точка входа, общая БД и сессии | Compose, operator_state.py, запросы через LB | Разные container ID, только LB публикует порт, одна БД |
| Одна сессия на разных репликах | lab3_tests.py, публичный failover | Наблюдались api1 и api2, повторный вход не выполнялся |
| Остановка любой одной API | failover_each.py | Оба варианта прошли, другая API, LB и БД продолжили работу |
| Конкурентный повтор сообщения | 16 одновременных POST через LB | Ответы обеих реплик, один ID и ровно одна запись в истории |
| Повтор после переключения и неясного ответа | lab3_tests.py, failover_each.py | Исходное Message, повтор не создал дубля |
| Сохранность после restart всего стенда | make test-persistence, operator_state.py | Новые StartedAt обеих API, LB и БД, прежний том и действующая сессия |
| Сохранность ключа после restart | lab3_tests.py --restart-script | Повтор вернул точное прежнее Message через обе реплики |
| Публичные проверки | make check, make test | PASS, также финальный smoke после всех отказов |
| Прежняя валидация и безопасность | student_tests.py, contract_edge_tests.py, проверка TTL | PASS, 22 проверки граничных случаев, истечение сессии, logout |
| Повторные миграции | operator_state.py до/после restart | Ровно по одной записи версий 1 и 2 |
Docker Engine 29.4.0, Docker Desktop Linux VM, доступно 16 CPU и 7 992 442 880 байт RAM. Все компоненты на одном компьютере. Это функциональный локальный эксперимент с синтетическими данными. Нагрузочный benchmark и уровень 4/5 не заявлены.
Публичный failover длился 15 секунд с паузой 0,1 секунды между итерациями. До отказа наблюдались две реплики. Результат Linux: 88 успешных записей, 3 неуспешные попытки, первая успешная запись после завершения hook через 2,907 секунды от старта воздействия. Все подтверждённые сообщения прочитаны прежней сессией, дубли не обнаружены.
Дополнительные отдельные воздействия длились по 6 секунд:
| Остановлена | Выжившая API | Успешные записи Linux | Ошибки итераций | Первое восстановление |
| --- | --- | --- | --- | --- |
| api1 | api2 | 16 | 5 | 2,992 с |
| api2 | api1 | 18 | 4 | 2,886 с |
В каждой итерации проверялись повтор прежнего сообщения, новая запись и чтение истории. Ошибки в коротком переходном интервале учитывались, ключ неясной записи сохранялся для повтора. Отдельно проверено реальное состояние контейнеров перед восстановлением.
В Windows эти же остановки дали восстановление за 3,020 с и 0,885 с. Это отдельные прогоны, значения зависят от момента healthcheck. Оба результата укладываются в требуемые 10 секунд.
## Ограничения
PostgreSQL, HAProxy и Docker-host остаются единичными точками отказа. Выдерживается остановка одной API при живой второй. Удаление pgdata уничтожает данные. Остановка всего хоста не обслуживается резервным узлом.
Два сервиса API заданы явно. Для добавления третьего нужно добавить сервис и backend в HAProxy. HTTP предназначен для локальной изолированной демонстрации. Сборка впервые требует доступа к Docker Hub и PyPI. При временной сетевой ошибке сборка повторяется той же командой.
Время сессий, идемпотентности и created_at использует часы хоста. Пагинация гарантирует порядок (created_at, id) в неизменной истории. Между несколькими запросами нет общего snapshot при конкурентных вставках. Фоновая очистка давно истёкших сессий и неиспользуемых ключей не реализована, для длительной эксплуатации нужна периодическая уборка.
## Источники и использование ИИ
Использованы материалы преподавателя из этого репозитория и собственная реализация ЛР №2. Официальные источники:
- [Docker Compose services](https://docs.docker.com/reference/compose-file/services/).
- [HAProxy 3.0 Configuration Manual](https://docs.haproxy.org/3.0/configuration.html).
- [Psycopg — Transactions management](https://www.psycopg.org/psycopg3/docs/basic/transactions.html).
- [argon2-cffi — How to Hash a Password](https://argon2-cffi.readthedocs.io/en/stable/howto.html).
При подготовке реализации, тестов и отчёта использовалась помощь ChatGPT/Codex. Результаты в evidence получены реальным запуском Docker и HTTP-проверок.
+1
View File
@@ -0,0 +1 @@
"""HTTP API of the MTUCI course messenger, lab 2."""
+482
View File
@@ -0,0 +1,482 @@
"""Lab 3: interchangeable APIs with shared sessions and atomic message retries."""
from __future__ import annotations
import base64
import hashlib
import json
import logging
import os
import re
import secrets
import socket
import time
import uuid
from datetime import datetime, timedelta, timezone
from typing import Annotated
import psycopg
from psycopg.errors import UniqueViolation
from psycopg.rows import dict_row
from argon2 import PasswordHasher
from argon2.exceptions import VerificationError
from fastapi import Depends, FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from pydantic import BaseModel, ConfigDict, Field, StrictStr
log = logging.getLogger('messenger')
logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s')
app = FastAPI(title='MTUCI Messenger / lab 3', docs_url=None, redoc_url=None, openapi_url=None)
KDF = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
# Even for a nonexistent user, a failed login runs a password KDF check.
DUMMY_HASH = KDF.hash('Dummy-password-not-a-real-user-123')
TTL_SECONDS = int(os.environ.get('SESSION_TTL_SECONDS', '3600'))
NAME = re.compile(r'^[a-z0-9_]{3,32}$')
TOKEN = re.compile(r'[A-Za-z0-9_-]{64}')
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
INSTANCE_ID = os.environ.get('INSTANCE_ID') or socket.gethostname()
IDEMPOTENCY_KEY = re.compile(r'[A-Za-z0-9._:-]{1,128}')
def utc_now() -> datetime:
return datetime.now(timezone.utc)
def timestamp(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
def db():
"""Open a connection whose context manager commits or rolls back."""
dsn = os.environ.get('DATABASE_URL', '')
if dsn:
return psycopg.connect(dsn, row_factory=dict_row, connect_timeout=3)
return psycopg.connect(
host=os.environ.get('POSTGRES_HOST', 'db'),
dbname=os.environ['POSTGRES_DB'],
user=os.environ['POSTGRES_USER'],
password=os.environ['POSTGRES_PASSWORD'],
row_factory=dict_row,
connect_timeout=3,
)
@app.on_event('startup')
def on_startup():
if TTL_SECONDS <= 0:
raise RuntimeError('SESSION_TTL_SECONDS must be a positive integer')
for attempt in range(20):
try:
# DDL belongs to the separate migrate service, before both APIs start.
with db() as conn:
version = conn.execute('SELECT max(version) AS version FROM schema_migrations').fetchone()
if version['version'] != 2:
raise RuntimeError('Run the migrate service before starting API')
return
except psycopg.OperationalError:
if attempt == 19:
raise
time.sleep(1)
class Error(Exception):
def __init__(self, status: int, code: str, message: str, challenge: str | None = None):
self.status, self.code, self.message, self.challenge = status, code, message, challenge
def fail(status: int, code: str, message: str, challenge: str | None = None):
raise Error(status, code, message, challenge)
def error_response(request: Request, status: int, code: str, message: str, challenge: str | None = None):
rid = getattr(request.state, 'rid', str(uuid.uuid4()))
headers = {'WWW-Authenticate': challenge} if challenge else {}
return JSONResponse(status_code=status, headers=headers,
content={'error': {'code': code, 'message': message, 'request_id': rid}})
@app.middleware('http')
async def add_request_id(request: Request, call_next):
request.state.rid = str(uuid.uuid4())
try:
response = await call_next(request)
except (psycopg.OperationalError, psycopg.InterfaceError):
log.warning('Database unavailable, request_id=%s', request.state.rid)
response = error_response(request, 503, 'unavailable', 'Хранилище недоступно')
except Exception as exc:
log.error('Unexpected %s, request_id=%s', type(exc).__name__, request.state.rid)
response = error_response(request, 500, 'internal_error', 'Внутренняя ошибка сервера')
response.headers['X-Request-Id'] = request.state.rid
response.headers['X-Instance-Id'] = INSTANCE_ID
return response
@app.exception_handler(Error)
async def on_error(request: Request, exc: Error):
return error_response(request, exc.status, exc.code, exc.message, exc.challenge)
@app.exception_handler(RequestValidationError)
async def on_validation_error(request: Request, exc: RequestValidationError):
return error_response(request, 400, 'invalid_request', 'Неверные поля или типы запроса')
@app.exception_handler(404)
async def on_not_found(request: Request, exc):
return error_response(request, 404, 'not_found', 'Объект не найден')
@app.exception_handler(405)
async def on_method_not_allowed(request: Request, exc):
return error_response(request, 405, 'invalid_request', 'Метод не поддерживается')
class StrictModel(BaseModel):
model_config = ConfigDict(extra='forbid', strict=True)
class NewUser(StrictModel):
username: StrictStr = Field(min_length=3, max_length=32, pattern=r'^[a-z0-9_]{3,32}$')
display_name: StrictStr = Field(min_length=1, max_length=100)
password: StrictStr = Field(min_length=12, max_length=128)
class NewChat(StrictModel):
title: StrictStr = Field(min_length=1, max_length=100)
member_ids: list[StrictStr] = Field(min_length=1, max_length=100)
class NewMessage(StrictModel):
text: StrictStr = Field(min_length=1, max_length=4000)
# In lab 3, omission and [] mean the same body. Attachments start in lab 4.
attachment_ids: list[StrictStr] = Field(default_factory=list, max_length=0)
async def json_body(request: Request, model):
media_type = request.headers.get('Content-Type', '').split(';', 1)[0].strip().lower()
if media_type != 'application/json':
fail(415, 'unsupported_media_type', 'Ожидается application/json')
body = bytearray()
async for chunk in request.stream():
if len(body) + len(chunk) > 1024 * 1024:
fail(413, 'payload_too_large', 'Слишком большой запрос')
body.extend(chunk)
try:
return model.model_validate(json.loads(body.decode('utf-8')))
except (ValueError, RecursionError):
fail(400, 'invalid_request', 'Неверный JSON, поля или типы запроса')
async def user_body(request: Request):
return await json_body(request, NewUser)
async def chat_body(request: Request):
return await json_body(request, NewChat)
async def message_body(request: Request):
return await json_body(request, NewMessage)
def validate_text(value: str, *, postgres: bool = True):
if not value.strip() or (postgres and '\x00' in value):
fail(400, 'invalid_request', 'Некорректная обязательная строка')
try:
value.encode('utf-8')
except UnicodeEncodeError:
fail(400, 'invalid_request', 'Некорректный Unicode')
def valid_uuid(value: str) -> uuid.UUID:
try:
parsed = uuid.UUID(value)
if str(parsed) != value.lower():
raise ValueError()
return parsed
except (TypeError, ValueError, AttributeError):
fail(400, 'invalid_request', 'Неверный UUID')
def view_user(row: dict) -> dict:
return {key: str(row[key]) if key == 'id' else timestamp(row[key]) if key == 'created_at' else row[key]
for key in ('id', 'username', 'display_name', 'created_at')}
def view_chat(row: dict, member_ids) -> dict:
return {'id': str(row['id']), 'title': row['title'],
'member_ids': [str(i) for i in member_ids], 'created_at': timestamp(row['created_at'])}
def view_message(row: dict) -> dict:
return {'id': str(row['id']), 'chat_id': str(row['chat_id']), 'sender_id': str(row['sender_id']),
'text': row['text'], 'created_at': timestamp(row['created_at'])}
def authorization(request: Request, scheme: str) -> str:
values = request.headers.getlist('Authorization')
if len(values) != 1:
return ''
prefix, _, credential = values[0].partition(' ')
return credential.lstrip(' ') if prefix.lower() == scheme else ''
def token_digest(token: str) -> str:
return hashlib.sha256(token.encode('ascii')).hexdigest()
def bearer_user(request: Request) -> dict:
token = authorization(request, 'bearer')
if TOKEN.fullmatch(token) is None:
fail(401, 'unauthorized', 'Нужен действительный Bearer-токен', BEARER_CHALLENGE)
digest = token_digest(token)
with db() as conn:
row = conn.execute('''SELECT u.id, u.username, u.display_name, u.created_at
FROM sessions s JOIN users u ON u.id = s.user_id
WHERE s.token_hash=%s AND s.expires_at > %s''', (digest, utc_now())).fetchone()
if not row:
fail(401, 'unauthorized', 'Сессия отсутствует или истекла', BEARER_CHALLENGE)
return row
Actor = Annotated[dict, Depends(bearer_user)]
def parse_limit(raw: str) -> int:
if not re.fullmatch(r'[0-9]{1,3}', raw or ''):
fail(400, 'invalid_request', 'Неверный limit')
value = int(raw)
if not (1 <= value <= 100):
fail(400, 'invalid_request', 'limit должен быть от 1 до 100')
return value
def encode_cursor(scope: str, row: dict) -> str:
payload = {'scope': scope, 'created_at': timestamp(row['created_at']), 'id': str(row['id'])}
return base64.urlsafe_b64encode(json.dumps(payload, separators=(',', ':')).encode()).decode().rstrip('=')
def decode_cursor(raw: str | None, scope: str):
if raw is None:
return None
try:
if len(raw) > 1024 or re.fullmatch(r'[A-Za-z0-9_-]+', raw) is None:
raise ValueError()
data = base64.b64decode(raw + '=' * (-len(raw) % 4), altchars=b'-_', validate=True)
if base64.urlsafe_b64encode(data).decode('ascii').rstrip('=') != raw:
raise ValueError()
payload = json.loads(data.decode('utf-8'))
if not isinstance(payload, dict) or set(payload) != {'scope', 'created_at', 'id'} or payload['scope'] != scope:
raise ValueError()
at = datetime.fromisoformat(payload['created_at'].replace('Z', '+00:00'))
cursor_id = uuid.UUID(payload['id'])
if at.tzinfo is None or timestamp(at) != payload['created_at'] or str(cursor_id) != payload['id']:
raise ValueError()
return at, cursor_id
except (ValueError, TypeError, AttributeError, OverflowError, RecursionError):
fail(400, 'invalid_request', 'Неверный cursor')
def page_options(request: Request, scope: str):
query = request.query_params
if set(query) - {'limit', 'cursor'} or any(len(query.getlist(name)) > 1 for name in ('limit', 'cursor')):
fail(400, 'invalid_request', 'Некорректные параметры страницы')
return parse_limit(query.get('limit', '50')), decode_cursor(query.get('cursor'), scope)
@app.get('/health/live')
def live():
return {'status': 'ok'}
@app.get('/health/ready')
def ready():
try:
with db() as conn:
migrated = conn.execute('SELECT 1 FROM schema_migrations WHERE version = 2').fetchone()
except psycopg.Error:
fail(503, 'unavailable', 'PostgreSQL недоступен')
if not migrated:
fail(503, 'unavailable', 'Схема PostgreSQL не готова')
return {'status': 'ok'}
@app.post('/api/v1/users', status_code=201)
def create_user(data: Annotated[NewUser, Depends(user_body)]):
validate_text(data.display_name)
validate_text(data.password, postgres=False)
record = (uuid.uuid4(), data.username, data.display_name, KDF.hash(data.password), utc_now())
try:
with db() as conn:
row = conn.execute('''INSERT INTO users(id,username,display_name,password_hash,created_at)
VALUES (%s,%s,%s,%s,%s) RETURNING *''', record).fetchone()
except UniqueViolation:
fail(409, 'conflict', 'Имя пользователя занято')
return view_user(row)
async def basic_credentials(request: Request):
try:
decoded = base64.b64decode(authorization(request, 'basic'), validate=True).decode('utf-8')
username, password = decoded.split(':', 1)
if not NAME.fullmatch(username) or not (12 <= len(password) <= 128):
raise ValueError()
except ValueError:
fail(401, 'unauthorized', 'Неверные учётные данные', BASIC_CHALLENGE)
async for chunk in request.stream():
if chunk:
fail(400, 'invalid_request', 'Вход принимает только заголовок Authorization')
return username, password
@app.post('/api/v1/auth/sessions', status_code=201)
def login(credentials: Annotated[tuple[str, str], Depends(basic_credentials)]):
username, password = credentials
with db() as conn:
row = conn.execute('SELECT * FROM users WHERE username=%s', (username,)).fetchone()
try:
verified = KDF.verify(row['password_hash'] if row else DUMMY_HASH, password)
except VerificationError:
verified = False
if not row or not verified:
fail(401, 'unauthorized', 'Неверные учётные данные', BASIC_CHALLENGE)
token = secrets.token_urlsafe(48)
issued = utc_now()
expires = issued + timedelta(seconds=TTL_SECONDS)
with db() as conn:
conn.execute('''INSERT INTO sessions(token_hash,user_id,expires_at,created_at)
VALUES (%s,%s,%s,%s)''', (token_digest(token), row['id'], expires, issued))
return {'token': token, 'token_type': 'Bearer', 'expires_at': timestamp(expires), 'user': view_user(row)}
@app.delete('/api/v1/auth/sessions/current', status_code=204)
def logout(request: Request, actor: Actor):
token = authorization(request, 'bearer')
with db() as conn:
removed = conn.execute('DELETE FROM sessions WHERE token_hash=%s', (token_digest(token),)).rowcount
if not removed:
fail(401, 'unauthorized', 'Сессия отсутствует или истекла', BEARER_CHALLENGE)
return Response(status_code=204)
@app.get('/api/v1/users/me')
def me(actor: Actor):
return view_user(actor)
def get_members(conn, chat_id):
return [r['user_id'] for r in conn.execute('SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id', (chat_id,)).fetchall()]
def accessible_chat(conn, chat_id: str, user_id: uuid.UUID):
cid = valid_uuid(chat_id)
row = conn.execute('''SELECT c.id,c.title,c.created_at FROM chats c
JOIN chat_members m ON m.chat_id=c.id
WHERE c.id=%s AND m.user_id=%s''', (cid, user_id)).fetchone()
if not row:
fail(404, 'not_found', 'Чат не найден')
return row
@app.post('/api/v1/chats', status_code=201)
def create_chat(actor: Actor, data: Annotated[NewChat, Depends(chat_body)]):
validate_text(data.title)
ids = [valid_uuid(item) for item in data.member_ids]
if len(ids) != len(set(ids)) or actor['id'] not in ids:
fail(400, 'invalid_request', 'Некорректный список участников')
cid = uuid.uuid4()
created_at = utc_now()
with db() as conn:
n = conn.execute('SELECT COUNT(*) AS total FROM users WHERE id=ANY(%s::uuid[])', (ids,)).fetchone()['total']
if n != len(ids):
fail(400, 'invalid_request', 'Неизвестный участник')
row = conn.execute('INSERT INTO chats(id,title,created_at) VALUES (%s,%s,%s) RETURNING *',
(cid, data.title, created_at)).fetchone()
with conn.cursor() as cur:
cur.executemany('INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)', [(cid, i) for i in ids])
return view_chat(row, sorted(ids))
@app.get('/api/v1/chats')
def list_chats(request: Request, actor: Actor):
scope = 'chats:' + str(actor['id'])
page_size, since = page_options(request, scope)
with db() as conn:
rows = conn.execute('''SELECT c.id,c.title,c.created_at FROM chats c
JOIN chat_members m ON m.chat_id=c.id WHERE m.user_id=%s
AND (%s::timestamptz IS NULL OR (c.created_at,c.id)>(%s::timestamptz,%s::uuid))
ORDER BY c.created_at,c.id LIMIT %s''',
(actor['id'], since[0] if since else None, since[0] if since else None,
since[1] if since else None, page_size + 1)).fetchall()
page = rows[:page_size]
items = [view_chat(r, get_members(conn, r['id'])) for r in page]
return {'items': items, 'next_cursor': encode_cursor(scope, page[-1]) if len(rows) > page_size else None}
@app.get('/api/v1/chats/{chat_id}')
def get_chat(chat_id: str, actor: Actor):
with db() as conn:
row = accessible_chat(conn, chat_id, actor['id'])
members = get_members(conn, row['id'])
return view_chat(row, members)
@app.post('/api/v1/chats/{chat_id}/messages', status_code=201)
def create_message(chat_id: str, request: Request, actor: Actor, data: Annotated[NewMessage, Depends(message_body)]):
validate_text(data.text)
keys = request.headers.getlist('Idempotency-Key')
if len(keys) != 1 or IDEMPOTENCY_KEY.fullmatch(keys[0]) is None:
fail(400, 'invalid_request', 'Нужен корректный Idempotency-Key')
key = keys[0]
canonical = json.dumps(data.model_dump(), sort_keys=True, separators=(',', ':'), ensure_ascii=False)
digest = hashlib.sha256(canonical.encode('utf-8')).hexdigest()
with db() as conn:
chat = accessible_chat(conn, chat_id, actor['id'])
# This table covers only POST /chats/{id}/messages; method/prefix are implicit.
scope = json.dumps([str(actor['id']), 'POST', str(chat['id']), key])
lock = int.from_bytes(hashlib.sha256(scope.encode()).digest()[:8], 'big', signed=True)
# Same transaction lock on every replica. Hash collisions only serialize
# unrelated requests; exact scope is still enforced by the primary key.
conn.execute('SELECT pg_advisory_xact_lock(%s)', (lock,))
saved = conn.execute('''SELECT * FROM message_requests
WHERE user_id=%s AND chat_id=%s AND request_key=%s''',
(actor['id'], chat['id'], key)).fetchone()
now = utc_now()
if saved and saved['expires_at'] > now:
if saved['body_hash'] != digest:
fail(409, 'conflict', 'Ключ уже использован для другого сообщения')
row = conn.execute('SELECT * FROM messages WHERE id=%s', (saved['message_id'],)).fetchone()
else:
row = conn.execute('''INSERT INTO messages(id,chat_id,sender_id,text,created_at)
VALUES (%s,%s,%s,%s,%s) RETURNING *''',
(uuid.uuid4(), chat['id'], actor['id'], data.text, now)).fetchone()
conn.execute('''INSERT INTO message_requests(user_id,chat_id,request_key,body_hash,message_id,expires_at)
VALUES (%s,%s,%s,%s,%s,%s)
ON CONFLICT (user_id,chat_id,request_key) DO UPDATE SET
body_hash=EXCLUDED.body_hash, message_id=EXCLUDED.message_id,
expires_at=EXCLUDED.expires_at''',
(actor['id'], chat['id'], key, digest, row['id'], now + timedelta(hours=24)))
# Context exit commits both records before the HTTP confirmation.
return view_message(row)
@app.get('/api/v1/chats/{chat_id}/messages')
def list_messages(chat_id: str, request: Request, actor: Actor):
with db() as conn:
chat = accessible_chat(conn, chat_id, actor['id'])
scope = 'messages:' + str(chat['id'])
page_size, since = page_options(request, scope)
rows = conn.execute('''SELECT * FROM messages WHERE chat_id=%s
AND (%s::timestamptz IS NULL OR (created_at,id)>(%s::timestamptz,%s::uuid))
ORDER BY created_at,id LIMIT %s''',
(chat['id'], since[0] if since else None, since[0] if since else None,
since[1] if since else None, page_size + 1)).fetchall()
return {'items': [view_message(row) for row in rows[:page_size]],
'next_cursor': encode_cursor(scope, rows[page_size - 1]) if len(rows) > page_size else None}
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host=os.environ.get('APP_HOST', '0.0.0.0'), port=int(os.environ.get('APP_PORT', '8080')),
access_log=False, workers=1, timeout_graceful_shutdown=2)
+23
View File
@@ -0,0 +1,23 @@
"""Single-purpose Compose migration job. APIs never apply DDL on startup."""
from pathlib import Path
from .main import db, log
def main():
directory = Path(__file__).resolve().parent.parent / 'migrations'
with db() as conn:
conn.execute('SELECT pg_advisory_xact_lock(2026, 2)')
conn.execute('''CREATE TABLE IF NOT EXISTS schema_migrations (
version integer PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP)''')
for path in sorted(directory.glob('*.sql')):
version = int(path.name.split('_', 1)[0])
if not conn.execute('SELECT 1 FROM schema_migrations WHERE version=%s', (version,)).fetchone():
conn.execute(path.read_text(encoding='utf-8'))
conn.execute('INSERT INTO schema_migrations(version) VALUES (%s)', (version,))
log.info('Applied migration %03d', version)
log.info('Migrations complete')
if __name__ == '__main__':
main()
+73
View File
@@ -0,0 +1,73 @@
name: mtusi-lab3
x-db-env: &db-env
POSTGRES_HOST: db
POSTGRES_USER: ${POSTGRES_USER:?set POSTGRES_USER in .env}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
POSTGRES_DB: ${POSTGRES_DB:?set POSTGRES_DB in .env}
x-api: &api
build: .
restart: unless-stopped
stop_grace_period: 4s
depends_on:
db:
condition: service_healthy
migrate:
condition: service_completed_successfully
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2).close()"]
interval: 2s
timeout: 3s
retries: 20
start_period: 3s
services:
db:
image: postgres:16.16-bookworm
restart: unless-stopped
environment: *db-env
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U \"$$POSTGRES_USER\" -d \"$$POSTGRES_DB\""]
interval: 2s
timeout: 3s
retries: 20
migrate:
build: .
environment: *db-env
command: ["python", "-m", "app.migrate"]
restart: "no"
depends_on:
db:
condition: service_healthy
api1:
<<: *api
environment:
<<: *db-env
INSTANCE_ID: api1
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
api2:
<<: *api
environment:
<<: *db-env
INSTANCE_ID: api2
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
lb:
build:
context: .
dockerfile: infra/Dockerfile.lb
restart: unless-stopped
depends_on:
api1:
condition: service_healthy
api2:
condition: service_healthy
ports:
- "127.0.0.1:${LAB3_HOST_PORT:-8080}:8080"
healthcheck:
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:8080/health/ready"]
interval: 2s
timeout: 3s
retries: 20
start_period: 3s
volumes:
pgdata:
+28
View File
@@ -0,0 +1,28 @@
Container mtusi-lab3-check-api2-1 Recreate
Container mtusi-lab3-check-api1-1 Recreate
Container mtusi-lab3-check-api1-1 Recreated
Container mtusi-lab3-check-api2-1 Recreated
Container mtusi-lab3-check-api2-1 Starting
Container mtusi-lab3-check-api1-1 Starting
Container mtusi-lab3-check-api1-1 Started
Container mtusi-lab3-check-api2-1 Started
Container mtusi-lab3-check-api2-1 Waiting
Container mtusi-lab3-check-api1-1 Waiting
Container mtusi-lab3-check-api1-1 Healthy
Container mtusi-lab3-check-api2-1 Healthy
PASS: both replicas observed through LB
PASS: Bearer session expires without logout
Container mtusi-lab3-check-api2-1 Recreate
Container mtusi-lab3-check-api1-1 Recreate
Container mtusi-lab3-check-api1-1 Recreated
Container mtusi-lab3-check-api2-1 Recreated
Container mtusi-lab3-check-api1-1 Starting
Container mtusi-lab3-check-api2-1 Starting
Container mtusi-lab3-check-api2-1 Started
Container mtusi-lab3-check-api1-1 Started
Container mtusi-lab3-check-api1-1 Waiting
Container mtusi-lab3-check-api2-1 Waiting
Container mtusi-lab3-check-api2-1 Healthy
Container mtusi-lab3-check-api1-1 Healthy
PASS: both replicas observed through LB
PASS: session expiration tested with TTL=2; original API settings restored
+367
View File
@@ -0,0 +1,367 @@
Lab 3 verification 2026-12-01T11:55:05Z
Compose can now delegate builds to bake for better performance.
To do so, set COMPOSE_BAKE=true.
#0 building with "default" instance using docker driver
#1 [migrate internal] load build definition from Dockerfile
#1 transferring dockerfile: 334B 0.1s done
#1 DONE 0.1s
#2 [migrate internal] load metadata for docker.io/library/python:3.12.10-slim-bookworm
#2 DONE 0.7s
#3 [migrate internal] load .dockerignore
#3 transferring context: 196B 0.1s done
#3 DONE 0.1s
#4 [migrate 1/6] FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db
#4 resolve docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db 0.0s done
#4 DONE 0.0s
#5 [migrate internal] load build context
#5 transferring context: 24.76kB 0.1s done
#5 DONE 0.1s
#6 [migrate 2/6] WORKDIR /app
#6 CACHED
#7 [migrate 3/6] COPY requirements.txt .
#7 DONE 0.0s
#8 [migrate 4/6] RUN pip install --no-cache-dir -r requirements.txt
#8 2.131 Collecting fastapi==0.115.12 (from -r requirements.txt (line 1))
#8 2.815 Downloading fastapi-0.115.12-py3-none-any.whl.metadata (27 kB)
#8 3.044 Collecting uvicorn==0.34.2 (from -r requirements.txt (line 2))
#8 3.156 Downloading uvicorn-0.34.2-py3-none-any.whl.metadata (6.5 kB)
#8 3.308 Collecting psycopg==3.2.6 (from psycopg[binary]==3.2.6->-r requirements.txt (line 3))
#8 3.423 Downloading psycopg-3.2.6-py3-none-any.whl.metadata (4.4 kB)
#8 3.560 Collecting argon2-cffi==25.1.0 (from -r requirements.txt (line 4))
#8 3.663 Downloading argon2_cffi-25.1.0-py3-none-any.whl.metadata (4.1 kB)
#8 4.001 Collecting pydantic==2.14.3 (from -r requirements.txt (line 5))
#8 4.070 Downloading pydantic-2.14.3-py3-none-any.whl.metadata (141 kB)
#8 4.344 Collecting starlette<0.47.0,>=0.40.0 (from fastapi==0.115.12->-r requirements.txt (line 1))
#8 4.419 Downloading starlette-0.46.2-py3-none-any.whl.metadata (6.2 kB)
#8 4.558 Collecting typing-extensions>=4.8.0 (from fastapi==0.115.12->-r requirements.txt (line 1))
#8 4.700 Downloading typing_extensions-4.16.0-py3-none-any.whl.metadata (3.3 kB)
#8 4.811 Collecting click>=7.0 (from uvicorn==0.34.2->-r requirements.txt (line 2))
#8 4.909 Downloading click-8.5.1-py3-none-any.whl.metadata (2.6 kB)
#8 4.990 Collecting h11>=0.8 (from uvicorn==0.34.2->-r requirements.txt (line 2))
#8 5.064 Downloading h11-0.16.0-py3-none-any.whl.metadata (8.3 kB)
#8 5.199 Collecting argon2-cffi-bindings (from argon2-cffi==25.1.0->-r requirements.txt (line 4))
#8 5.304 Downloading argon2_cffi_bindings-26.2.0-cp310-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl.metadata (7.6 kB)
#8 5.391 Collecting annotated-types>=0.6.0 (from pydantic==2.14.3->-r requirements.txt (line 5))
#8 5.588 Downloading annotated_types-0.8.0-py3-none-any.whl.metadata (15 kB)
#8 6.869 Collecting pydantic-core==2.50.4 (from pydantic==2.14.3->-r requirements.txt (line 5))
#8 6.956 Downloading pydantic_core-2.50.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (6.6 kB)
#8 7.061 Collecting typing-inspection>=0.4.4 (from pydantic==2.14.3->-r requirements.txt (line 5))
#8 7.148 Downloading typing_inspection-0.4.5-py3-none-any.whl.metadata (2.6 kB)
#8 7.374 Collecting psycopg-binary==3.2.6 (from psycopg[binary]==3.2.6->-r requirements.txt (line 3))
#8 7.476 Downloading psycopg_binary-3.2.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (2.8 kB)
#8 7.640 Collecting anyio<5,>=3.6.2 (from starlette<0.47.0,>=0.40.0->fastapi==0.115.12->-r requirements.txt (line 1))
#8 7.737 Downloading anyio-4.16.0-py3-none-any.whl.metadata (4.7 kB)
#8 7.915 Collecting cffi>=1.0.1 (from argon2-cffi-bindings->argon2-cffi==25.1.0->-r requirements.txt (line 4))
#8 8.011 Downloading cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (2.5 kB)
#8 8.139 Collecting idna>=2.8 (from anyio<5,>=3.6.2->starlette<0.47.0,>=0.40.0->fastapi==0.115.12->-r requirements.txt (line 1))
#8 8.234 Downloading idna-3.20-py3-none-any.whl.metadata (7.2 kB)
#8 8.352 Collecting pycparser (from cffi>=1.0.1->argon2-cffi-bindings->argon2-cffi==25.1.0->-r requirements.txt (line 4))
#8 8.437 Downloading pycparser-3.12-py3-none-any.whl.metadata (9.7 kB)
#8 8.555 Downloading fastapi-0.115.12-py3-none-any.whl (95 kB)
#8 8.689 Downloading uvicorn-0.34.2-py3-none-any.whl (62 kB)
#8 8.911 Downloading psycopg-3.2.6-py3-none-any.whl (199 kB)
#8 9.222 Downloading argon2_cffi-25.1.0-py3-none-any.whl (14 kB)
#8 9.478 Downloading pydantic-2.14.3-py3-none-any.whl (494 kB)
#8 9.919 Downloading psycopg_binary-3.2.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.3 MB)
#8 10.36 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 4.3/4.3 MB 10.0 MB/s eta 0:00:00
#8 10.47 Downloading pydantic_core-2.50.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (2.3 MB)
#8 10.79 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.3/2.3 MB 7.3 MB/s eta 0:00:00
#8 10.90 Downloading annotated_types-0.8.0-py3-none-any.whl (13 kB)
#8 10.98 Downloading click-8.5.1-py3-none-any.whl (126 kB)
#8 11.10 Downloading h11-0.16.0-py3-none-any.whl (37 kB)
#8 11.20 Downloading starlette-0.46.2-py3-none-any.whl (72 kB)
#8 11.36 Downloading typing_extensions-4.16.0-py3-none-any.whl (45 kB)
#8 11.50 Downloading typing_inspection-0.4.5-py3-none-any.whl (14 kB)
#8 11.59 Downloading argon2_cffi_bindings-26.2.0-cp310-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl (26 kB)
#8 11.66 Downloading anyio-4.16.0-py3-none-any.whl (134 kB)
#8 11.79 Downloading cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (221 kB)
#8 12.03 Downloading idna-3.20-py3-none-any.whl (69 kB)
#8 12.14 Downloading pycparser-3.12-py3-none-any.whl (62 kB)
#8 12.21 Installing collected packages: typing-extensions, pycparser, psycopg-binary, idna, h11, click, annotated-types, uvicorn, typing-inspection, pydantic-core, psycopg, cffi, anyio, starlette, pydantic, argon2-cffi-bindings, fastapi, argon2-cffi
#8 13.54 Successfully installed annotated-types-0.8.0 anyio-4.16.0 argon2-cffi-25.1.0 argon2-cffi-bindings-26.2.0 cffi-2.1.1 click-8.5.1 fastapi-0.115.12 h11-0.16.0 idna-3.20 psycopg-3.2.6 psycopg-binary-3.2.6 pycparser-3.12 pydantic-2.14.3 pydantic-core-2.50.4 starlette-0.46.2 typing-extensions-4.16.0 typing-inspection-0.4.5 uvicorn-0.34.2
#8 13.54 WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager, possibly rendering your system unusable. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv. Use the --root-user-action option if you know what you are doing and want to suppress this warning.
#8 14.04
#8 14.04 [notice] A new release of pip is available: 25.0.1 -> 26.3
#8 14.04 [notice] To update, run: pip install --upgrade pip
#8 DONE 14.3s
#9 [migrate 5/6] COPY app/ ./app/
#9 DONE 0.1s
#10 [migrate 6/6] COPY migrations/ ./migrations/
#10 DONE 0.0s
#11 [migrate] exporting to image
#11 exporting layers
#11 exporting layers 1.2s done
#11 exporting manifest sha256:f62cc5f322f91b2e1992116f40d69ea443593d929f87c0337aa76ee8b15af770 0.0s done
#11 exporting config sha256:8ce992a7f5fd7ab610471bbd55a85ef141c2eb1384713466da5d6a9395badfcd 0.0s done
#11 exporting attestation manifest sha256:0739dbadaabfce7d482857da3008aecea56bc2b4f269d42e233143bdb4581390 0.0s done
#11 exporting manifest list sha256:2db74a25b3d7456db92d3a8e711d5f46a399fe36ae0f52c5e4e657baf278527e 0.0s done
#11 naming to docker.io/library/mtusi-lab3-check-migrate:latest done
#11 unpacking to docker.io/library/mtusi-lab3-check-migrate:latest
#11 unpacking to docker.io/library/mtusi-lab3-check-migrate:latest 0.2s done
#11 DONE 1.5s
#12 [migrate] resolving provenance for metadata file
#12 DONE 0.0s
#13 [api2 internal] load build definition from Dockerfile
#13 transferring dockerfile: 30B 0.0s
#13 transferring dockerfile: 334B 0.0s done
#13 DONE 0.1s
#14 [api1 internal] load build definition from Dockerfile
#14 transferring dockerfile: 334B 0.0s done
#14 DONE 0.1s
#2 [api1 internal] load metadata for docker.io/library/python:3.12.10-slim-bookworm
#2 DONE 1.0s
#15 [api2 internal] load .dockerignore
#15 transferring context: 196B 0.0s done
#15 DONE 0.1s
#16 [api1 internal] load .dockerignore
#16 transferring context: 196B 0.0s done
#16 DONE 0.1s
#4 [api1 1/6] FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db
#4 resolve docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db 0.0s done
#4 DONE 0.0s
#17 [api2 internal] load build context
#17 transferring context: 286B 0.1s done
#17 DONE 0.1s
#18 [api2 4/6] RUN pip install --no-cache-dir -r requirements.txt
#18 CACHED
#19 [api2 3/6] COPY requirements.txt .
#19 CACHED
#20 [api2 5/6] COPY app/ ./app/
#20 CACHED
#6 [api2 2/6] WORKDIR /app
#6 CACHED
#21 [api1 6/6] COPY migrations/ ./migrations/
#21 CACHED
#22 [api1 internal] load build context
#22 transferring context: 24.76kB 0.1s done
#22 DONE 0.1s
#23 [api1] exporting to image
#23 exporting layers done
#23 exporting manifest sha256:76c29a965790c5277e24bfe0abd47a4522d518d2ceb9e2a794e96291db0f6e6c 0.0s done
#23 exporting config sha256:cb2ca18d172305cd6c54d1aabdee3b4038e855a03fa58495e13587c97a03184b
#23 exporting config sha256:cb2ca18d172305cd6c54d1aabdee3b4038e855a03fa58495e13587c97a03184b 0.0s done
#23 exporting attestation manifest sha256:9dcc9dae412bf9a2e334abd3074ad6d0ae1229eb37f14ab7097093b3723d11b2 0.0s done
#23 exporting manifest list sha256:8e37efe2f772356931364b7f2b1c8f962aaa958220fbcb3dd448b30d5cd327c7 0.0s done
#23 naming to docker.io/library/mtusi-lab3-check-api1:latest done
#23 unpacking to docker.io/library/mtusi-lab3-check-api1:latest
#23 unpacking to docker.io/library/mtusi-lab3-check-api1:latest done
#23 DONE 0.1s
#24 [api2] exporting to image
#24 exporting layers done
#24 exporting manifest sha256:516e77522c70cf0be98352900ce694dd29a4a8fddd821683998f394c29af9073 0.0s done
#24 exporting config sha256:ee9f2e124c2910da9ed914e8a2ce8fe5c3dabcf04f70ec26f248a229b819a3fe 0.0s done
#24 exporting attestation manifest sha256:c6f8db22f0889c6fab131188ac6ddb1dbb9e7c4873f60552d09d41681da799aa 0.0s done
#24 exporting manifest list sha256:d57dc475b809b0bfe7a9b740f6e4b4a4581ab010e3bbede48402abda9199a154 0.0s done
#24 naming to docker.io/library/mtusi-lab3-check-api2:latest done
#24 unpacking to docker.io/library/mtusi-lab3-check-api2:latest 0.0s done
#24 DONE 0.2s
#25 [api2] resolving provenance for metadata file
#25 DONE 0.0s
#26 [api1] resolving provenance for metadata file
#26 DONE 0.0s
#27 [lb internal] load build definition from Dockerfile.lb
#27 transferring dockerfile: 180B 0.0s done
#27 DONE 0.0s
#28 [lb internal] load metadata for docker.io/library/haproxy:3.0.31-alpine
#28 DONE 0.1s
#29 [lb internal] load .dockerignore
#29 transferring context: 196B 0.1s done
#29 DONE 0.1s
#30 [lb internal] load build context
#30 DONE 0.0s
#31 [lb 1/3] FROM docker.io/library/haproxy:3.0.31-alpine@sha256:7430e63d3052198b18a40665b59a5826bc428e8bceb0c561d82258149ef855ee
#31 resolve docker.io/library/haproxy:3.0.31-alpine@sha256:7430e63d3052198b18a40665b59a5826bc428e8bceb0c561d82258149ef855ee 0.0s done
#31 CACHED
#30 [lb internal] load build context
#30 transferring context: 884B 0.1s done
#30 DONE 0.1s
#32 [lb 2/3] COPY infra/haproxy.cfg /usr/local/etc/haproxy/haproxy.cfg
#32 DONE 0.0s
#33 [lb 3/3] RUN haproxy -c -f /usr/local/etc/haproxy/haproxy.cfg
#33 DONE 0.4s
#34 [lb] exporting to image
#34 exporting layers 0.1s done
#34 exporting manifest sha256:0fb6c9ea668efa41bf86933e711efda484c1fdd0089c8a906fec7d3817ea849b 0.0s done
#34 exporting config sha256:37e78d6e10079d84cbcf5ddd89272b3240b634d4da9d60715fce665d72082e6b
#34 exporting config sha256:37e78d6e10079d84cbcf5ddd89272b3240b634d4da9d60715fce665d72082e6b 0.0s done
#34 exporting attestation manifest sha256:8be5010a17e9a5eaebfbc6774ac7189d713810dd8478ecbb7b5ea97b158c745b 0.0s done
#34 exporting manifest list sha256:dac7c4b841859be274274a29bad1b3ab496c368fb3cbc1d42563816a7c61fd43 0.0s done
#34 naming to docker.io/library/mtusi-lab3-check-lb:latest done
#34 unpacking to docker.io/library/mtusi-lab3-check-lb:latest 0.0s done
#34 DONE 0.2s
#35 [lb] resolving provenance for metadata file
#35 DONE 0.0s
api1 Built
api2 Built
lb Built
migrate Built
Container mtusi-lab3-check-db-1 Running
Container mtusi-lab3-check-migrate-1 Recreate
Container mtusi-lab3-check-migrate-1 Recreated
Container mtusi-lab3-check-api2-1 Recreate
Container mtusi-lab3-check-api1-1 Recreate
Container mtusi-lab3-check-api2-1 Recreated
Container mtusi-lab3-check-api1-1 Recreated
Container mtusi-lab3-check-lb-1 Recreate
Container mtusi-lab3-check-lb-1 Recreated
Container mtusi-lab3-check-db-1 Waiting
Container mtusi-lab3-check-db-1 Healthy
Container mtusi-lab3-check-migrate-1 Starting
Container mtusi-lab3-check-migrate-1 Started
Container mtusi-lab3-check-migrate-1 Waiting
Container mtusi-lab3-check-migrate-1 Waiting
Container mtusi-lab3-check-db-1 Waiting
Container mtusi-lab3-check-db-1 Waiting
Container mtusi-lab3-check-db-1 Healthy
Container mtusi-lab3-check-db-1 Healthy
Container mtusi-lab3-check-migrate-1 Exited
Container mtusi-lab3-check-api2-1 Starting
Container mtusi-lab3-check-migrate-1 Exited
Container mtusi-lab3-check-api1-1 Starting
Container mtusi-lab3-check-api1-1 Started
Container mtusi-lab3-check-api2-1 Started
Container mtusi-lab3-check-api1-1 Waiting
Container mtusi-lab3-check-api2-1 Waiting
Container mtusi-lab3-check-api2-1 Healthy
Container mtusi-lab3-check-api1-1 Healthy
Container mtusi-lab3-check-lb-1 Starting
Container mtusi-lab3-check-lb-1 Started
Container mtusi-lab3-check-api2-1 Waiting
Container mtusi-lab3-check-lb-1 Waiting
Container mtusi-lab3-check-db-1 Waiting
Container mtusi-lab3-check-migrate-1 Waiting
Container mtusi-lab3-check-api1-1 Waiting
Container mtusi-lab3-check-api1-1 Healthy
Container mtusi-lab3-check-migrate-1 Exited
Container mtusi-lab3-check-db-1 Healthy
Container mtusi-lab3-check-api2-1 Healthy
Container mtusi-lab3-check-lb-1 Healthy
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
python3 tests/smoke.py --base-url "http://lb:8080"
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
PASS: validation, Unicode Basic login, access, pagination and logout
PASS: 22 Lab 2 contract edge-case HTTP checks
{"parallel_requests": 16, "instances": ["api1", "api2"], "messages_created": 1}
PASS: same session and exact Message replay after full-stack restart
PASS: concurrent replay, normalized JSON, key scope, conflict, invalid key, access, uncertain response and logout
{"services": {"api1": {"id": "4f12f9335130", "started": "2026-12-01T11:55:51.834557036Z"}, "api2": {"id": "8e1e20f30425", "started": "2026-12-01T11:55:51.833399974Z"}, "db": {"id": "c79e32dfab85", "started": "2026-12-01T11:55:47.75484728Z"}, "lb": {"id": "cd866ba0ec62", "started": "2026-12-01T11:55:57.59387041Z"}}, "volume": "mtusi-lab3-check_pgdata", "volume_created": "2026-12-01T11:51:00Z"}
PASS: migrations 001 and 002 each installed exactly once; only LB publishes a host port
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://lb:8080"
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
{"services": {"api1": {"id": "4f12f9335130", "started": "2026-12-01T11:56:11.332600543Z"}, "api2": {"id": "8e1e20f30425", "started": "2026-12-01T11:56:11.335751641Z"}, "db": {"id": "c79e32dfab85", "started": "2026-12-01T11:56:07.403967566Z"}, "lb": {"id": "cd866ba0ec62", "started": "2026-12-01T11:56:17.060748867Z"}}, "volume": "mtusi-lab3-check_pgdata", "volume_created": "2026-12-01T11:51:00Z"}
PASS: both APIs, LB and PostgreSQL restarted; same persistent volume retained
PASS: migrations 001 and 002 each installed exactly once; only LB publishes a host port
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://lb:8080"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 88, "failed_attempts": 3, "first_recovery_seconds": 2.907}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
PASS: api1 really stopped; the other API, LB and database stayed running
Container mtusi-lab3-check-db-1 Running
Container mtusi-lab3-check-migrate-1 Created
Container mtusi-lab3-check-api1-1 Created
Container mtusi-lab3-check-db-1 Waiting
Container mtusi-lab3-check-db-1 Healthy
Container mtusi-lab3-check-migrate-1 Starting
Container mtusi-lab3-check-migrate-1 Started
Container mtusi-lab3-check-migrate-1 Waiting
Container mtusi-lab3-check-db-1 Waiting
Container mtusi-lab3-check-db-1 Healthy
Container mtusi-lab3-check-migrate-1 Exited
Container mtusi-lab3-check-api1-1 Starting
Container mtusi-lab3-check-api1-1 Started
Container mtusi-lab3-check-db-1 Waiting
Container mtusi-lab3-check-migrate-1 Waiting
Container mtusi-lab3-check-api1-1 Waiting
Container mtusi-lab3-check-db-1 Healthy
Container mtusi-lab3-check-migrate-1 Exited
Container mtusi-lab3-check-api1-1 Healthy
PASS: both replicas observed through LB
PASS: api1 really stopped; the other API, LB and database stayed running
Container mtusi-lab3-check-db-1 Running
Container mtusi-lab3-check-migrate-1 Created
Container mtusi-lab3-check-api1-1 Created
Container mtusi-lab3-check-db-1 Waiting
Container mtusi-lab3-check-db-1 Healthy
Container mtusi-lab3-check-migrate-1 Starting
Container mtusi-lab3-check-migrate-1 Started
Container mtusi-lab3-check-db-1 Waiting
Container mtusi-lab3-check-migrate-1 Waiting
Container mtusi-lab3-check-db-1 Healthy
Container mtusi-lab3-check-migrate-1 Exited
Container mtusi-lab3-check-api1-1 Starting
Container mtusi-lab3-check-api1-1 Started
Container mtusi-lab3-check-api1-1 Waiting
Container mtusi-lab3-check-db-1 Waiting
Container mtusi-lab3-check-migrate-1 Waiting
Container mtusi-lab3-check-migrate-1 Exited
Container mtusi-lab3-check-db-1 Healthy
Container mtusi-lab3-check-api1-1 Healthy
PASS: both replicas observed through LB
PASS: api2 really stopped; the other API, LB and database stayed running
Container mtusi-lab3-check-db-1 Running
Container mtusi-lab3-check-migrate-1 Created
Container mtusi-lab3-check-api2-1 Created
Container mtusi-lab3-check-db-1 Waiting
Container mtusi-lab3-check-db-1 Healthy
Container mtusi-lab3-check-migrate-1 Starting
Container mtusi-lab3-check-migrate-1 Started
Container mtusi-lab3-check-migrate-1 Waiting
Container mtusi-lab3-check-db-1 Waiting
Container mtusi-lab3-check-db-1 Healthy
Container mtusi-lab3-check-migrate-1 Exited
Container mtusi-lab3-check-api2-1 Starting
Container mtusi-lab3-check-api2-1 Started
Container mtusi-lab3-check-api2-1 Waiting
Container mtusi-lab3-check-db-1 Waiting
Container mtusi-lab3-check-migrate-1 Waiting
Container mtusi-lab3-check-migrate-1 Exited
Container mtusi-lab3-check-db-1 Healthy
Container mtusi-lab3-check-api2-1 Healthy
PASS: both replicas observed through LB
{"stopped": "api1", "observed_before": ["api1", "api2"], "survivors": ["api2"], "writes": 16, "errors": 5, "recovery_seconds": 2.992}
{"stopped": "api2", "observed_before": ["api1", "api2"], "survivors": ["api1"], "writes": 18, "errors": 4, "recovery_seconds": 2.886}
PASS: stopping either replica preserved sessions, reads, writes and idempotency
python3 tests/smoke.py --base-url "http://lb:8080"
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
PASS: full Lab 3 verification completed
+41
View File
@@ -0,0 +1,41 @@
Lab 3 verification 2026-12-01T15:43:51.9945339+03:00
PASS: Compose startup, public entrypoint http://127.0.0.1:8083
python scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
python tests/smoke.py --base-url http://127.0.0.1:8083
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
python tests/student_tests.py --base-url http://127.0.0.1:8083
PASS: validation, Unicode Basic login, access, pagination and logout
python tests/contract_edge_tests.py --base-url http://127.0.0.1:8083
PASS: 22 Lab 2 contract edge-case HTTP checks
python tests/lab3_tests.py --base-url http://127.0.0.1:8083 --restart-script scripts/restart.cmd
{"parallel_requests": 16, "instances": ["api1", "api2"], "messages_created": 1}
PASS: same session and exact Message replay after full-stack restart
PASS: concurrent replay, normalized JSON, key scope, conflict, invalid key, access, uncertain response and logout
python scripts/operator_state.py --save C:\Users\Asus\AppData\Local\Temp\5ed503a4-a237-45b7-b23a-cfd65dbcba44.json
{"services": {"api1": {"id": "b14183c8c5e2", "started": "2026-12-01T12:44:24.518932806Z"}, "api2": {"id": "3316cf1579ba", "started": "2026-12-01T12:44:24.52044701Z"}, "db": {"id": "533f4913ec8b", "started": "2026-12-01T12:44:20.573632868Z"}, "lb": {"id": "895a6a1efc90", "started": "2026-12-01T12:44:30.298876773Z"}}, "volume": "mtusi-lab3_pgdata", "volume_created": "2026-12-01T12:43:56Z"}
PASS: migrations 001 and 002 each installed exactly once; only LB publishes a host port
python tests/resilience.py --mode persistence --base-url http://127.0.0.1:8083 --action-script scripts/restart.cmd
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
python scripts/operator_state.py --compare C:\Users\Asus\AppData\Local\Temp\5ed503a4-a237-45b7-b23a-cfd65dbcba44.json
{"services": {"api1": {"id": "b14183c8c5e2", "started": "2026-12-01T12:44:45.879307353Z"}, "api2": {"id": "3316cf1579ba", "started": "2026-12-01T12:44:45.87734148Z"}, "db": {"id": "533f4913ec8b", "started": "2026-12-01T12:44:41.92745116Z"}, "lb": {"id": "895a6a1efc90", "started": "2026-12-01T12:44:51.660854445Z"}}, "volume": "mtusi-lab3_pgdata", "volume_created": "2026-12-01T12:43:56Z"}
PASS: both APIs, LB and PostgreSQL restarted; same persistent volume retained
PASS: migrations 001 and 002 each installed exactly once; only LB publishes a host port
python tests/resilience.py --mode failover --base-url http://127.0.0.1:8083 --action-script scripts/stop-one.cmd
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 83, "failed_attempts": 3, "first_recovery_seconds": 3.106}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
PASS: api1 really stopped; the other API, LB and database stayed running
PASS: both replicas observed through LB
python tests/failover_each.py --base-url http://127.0.0.1:8083 --action-script scripts/stop-one.cmd --restore-script scripts/restore.cmd
PASS: api1 really stopped; the other API, LB and database stayed running
PASS: both replicas observed through LB
PASS: api2 really stopped; the other API, LB and database stayed running
PASS: both replicas observed through LB
{"stopped": "api1", "observed_before": ["api1", "api2"], "survivors": ["api2"], "writes": 20, "errors": 3, "recovery_seconds": 2.08}
{"stopped": "api2", "observed_before": ["api1", "api2"], "survivors": ["api1"], "writes": 16, "errors": 3, "recovery_seconds": 2.983}
PASS: stopping either replica preserved sessions, reads, writes and idempotency
python tests/smoke.py --base-url http://127.0.0.1:8083
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
PASS: full Lab 3 verification completed
+3
View File
@@ -0,0 +1,3 @@
PASS: 28 supplied files preserved byte-for-byte, including public tests, contracts, README, COURSE and Makefile.
Only .env.example, .gitignore and REPORT.md intentionally updated among original files.
PASS: no local .env, private key or literal Bearer token included; local database password absent.
+3
View File
@@ -0,0 +1,3 @@
FROM haproxy:3.0.31-alpine
COPY infra/haproxy.cfg /usr/local/etc/haproxy/haproxy.cfg
RUN haproxy -c -f /usr/local/etc/haproxy/haproxy.cfg
+37
View File
@@ -0,0 +1,37 @@
global
log stdout format raw local0
maxconn 512
defaults
log global
mode http
timeout connect 1s
timeout client 10s
timeout server 5s
timeout check 1s
# Never transparently replay a POST with an unknown outcome.
retries 0
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold obsolete 1s
hold nx 1s
hold timeout 1s
hold refused 1s
hold other 1s
frontend public
bind :8080
default_backend messenger
backend messenger
balance roundrobin
option httpchk GET /health/ready
http-check expect status 200
default-server inter 1s fall 1 rise 1 resolvers docker init-addr last,none
server api1 api1:8080 check
server api2 api2:8080 check
+37
View File
@@ -0,0 +1,37 @@
-- Lab 2, migration 001. Transactional, idempotent DDL for an empty database.
CREATE TABLE IF NOT EXISTS users (
id uuid PRIMARY KEY,
username varchar(32) NOT NULL UNIQUE,
display_name varchar(100) NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT users_name_format CHECK (username ~ '^[a-z0-9_]{3,32}$')
);
CREATE TABLE IF NOT EXISTS chats (
id uuid PRIMARY KEY,
title varchar(100) NOT NULL,
created_at timestamptz NOT NULL
);
CREATE TABLE IF NOT EXISTS chat_members (
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
PRIMARY KEY (chat_id, user_id)
);
CREATE INDEX IF NOT EXISTS idx_members_user ON chat_members(user_id, chat_id);
CREATE INDEX IF NOT EXISTS idx_chats_order ON chats(created_at, id);
CREATE TABLE IF NOT EXISTS messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
text varchar(4000) NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT message_not_blank CHECK (length(btrim(text)) > 0)
);
CREATE INDEX IF NOT EXISTS idx_messages_page ON messages(chat_id, created_at, id);
CREATE TABLE IF NOT EXISTS sessions (
token_hash char(64) PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at timestamptz NOT NULL,
created_at timestamptz NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_sessions_expiry ON sessions(expires_at);
+10
View File
@@ -0,0 +1,10 @@
CREATE TABLE message_requests (
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
request_key varchar(128) NOT NULL,
body_hash char(64) NOT NULL,
message_id uuid NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
expires_at timestamptz NOT NULL,
PRIMARY KEY (user_id, chat_id, request_key)
);
CREATE INDEX idx_message_requests_expiry ON message_requests(expires_at);
+5
View File
@@ -0,0 +1,5 @@
fastapi==0.115.12
uvicorn==0.34.2
psycopg[binary]==3.2.6
argon2-cffi==25.1.0
pydantic==2.14.3
+20
View File
@@ -0,0 +1,20 @@
"""Temporarily use a two-second TTL, then restore both API configurations."""
import os
from pathlib import Path
import subprocess
import sys
os.chdir(Path(__file__).resolve().parents[1])
base = os.environ.get('BASE_URL', 'http://localhost:' + os.environ.get('LAB3_HOST_PORT', '8080'))
compose = ['docker', 'compose', '--env-file', '.env', 'up', '-d', '--no-deps',
'--force-recreate', '--wait', '--wait-timeout', '60', 'api1', 'api2']
normal = dict(os.environ, BASE_URL=base)
short = dict(normal, SESSION_TTL_SECONDS='2')
try:
subprocess.run(compose, env=short, check=True, timeout=90)
subprocess.run([sys.executable, 'scripts/wait_replicas.py'], env=short, check=True)
subprocess.run([sys.executable, 'tests/student_tests.py', '--base-url', base, '--expiry'], env=short, check=True)
finally:
subprocess.run(compose, env=normal, check=True, timeout=90)
subprocess.run([sys.executable, 'scripts/wait_replicas.py'], env=normal, check=True)
print('PASS: session expiration tested with TTL=2; original API settings restored')
+14
View File
@@ -0,0 +1,14 @@
"""Create local credentials once. Never print or overwrite an existing secret."""
from pathlib import Path
import secrets
root = Path(__file__).resolve().parents[1]
path = root / '.env'
if path.exists():
print('Existing .env retained')
else:
settings = (root / '.env.example').read_text(encoding='utf-8')
settings = settings.replace('POSTGRES_PASSWORD=', 'POSTGRES_PASSWORD=' + secrets.token_hex(24))
with path.open('x', encoding='utf-8', newline='\n') as output:
output.write(settings)
print('Created local .env with a random password; keep it outside Git')
+54
View File
@@ -0,0 +1,54 @@
"""Nonsecret Docker process/volume evidence. Does not output container environment."""
import argparse
import json
from pathlib import Path
import subprocess
def command(*args):
return subprocess.check_output(args, text=True, encoding='utf-8').strip()
def snapshot():
services = {}
for service in ('db', 'api1', 'api2', 'lb'):
container = command('docker', 'compose', '--env-file', '.env', 'ps', '-q', service)
assert container, service + ' is not running'
info = json.loads(command('docker', 'inspect', container))[0]
bindings = info['HostConfig'].get('PortBindings') or {}
if service != 'lb':
assert not bindings, 'Internal ports must not be published: ' + service
else:
assert set(bindings) == {'8080/tcp'}
assert bindings['8080/tcp'][0]['HostIp'] == '127.0.0.1'
services[service] = {'id': container[:12], 'started': info['State']['StartedAt']}
if service == 'db':
volume = next(m['Name'] for m in info['Mounts'] if m['Destination'] == '/var/lib/postgresql/data')
created = command('docker', 'volume', 'inspect', '--format', '{{.CreatedAt}}', volume)
return {'services': services, 'volume': volume, 'volume_created': created}
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--save')
parser.add_argument('--compare')
args = parser.parse_args()
state = snapshot()
print(json.dumps(state, sort_keys=True))
if args.save:
Path(args.save).write_text(json.dumps(state), encoding='utf-8')
if args.compare:
before = json.loads(Path(args.compare).read_text(encoding='utf-8'))
assert before['volume'] == state['volume'] and before['volume_created'] == state['volume_created'], 'Volume replaced'
for service in state['services']:
assert before['services'][service]['started'] != state['services'][service]['started'], service + ' did not restart'
print('PASS: both APIs, LB and PostgreSQL restarted; same persistent volume retained')
# psql reads its own environment inside the container. No password is printed.
versions = command('docker', 'compose', '--env-file', '.env', 'exec', '-T', 'db', 'sh', '-c',
'psql -X -At -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "SELECT version FROM schema_migrations ORDER BY version"')
assert versions.splitlines() == ['1', '2'], 'Unexpected migration versions'
print('PASS: migrations 001 and 002 each installed exactly once; only LB publishes a host port')
if __name__ == '__main__':
main()
+6
View File
@@ -0,0 +1,6 @@
@echo off
cd /d "%~dp0.."
docker compose --env-file .env stop -t 3 lb api1 api2 db
if errorlevel 1 exit /b 1
docker compose --env-file .env up -d --wait --wait-timeout 60
exit /b %errorlevel%
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
docker compose --env-file .env stop -t 3 lb api1 api2 db
docker compose --env-file .env up -d --wait --wait-timeout 60
+4
View File
@@ -0,0 +1,4 @@
@echo off
cd /d "%~dp0.."
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\restore.ps1
exit /b %errorlevel%
+19
View File
@@ -0,0 +1,19 @@
$ErrorActionPreference = 'Stop'
if ($env:TARGET_INSTANCE_ID -notin @('api1', 'api2')) { throw 'Invalid target' }
$target = $env:TARGET_INSTANCE_ID
$id = docker compose --env-file .env ps -a -q $target
if ($LASTEXITCODE -ne 0 -or !$id) { throw 'Target container missing' }
$running = docker inspect --format '{{.State.Running}}' $id
if ($LASTEXITCODE -ne 0 -or $running -ne 'false') { throw 'Target must actually be stopped' }
foreach ($service in @('db', 'lb', 'api1', 'api2')) {
if ($service -eq $target) { continue }
$id = docker compose --env-file .env ps -q $service
if ($LASTEXITCODE -ne 0 -or !$id) { throw "$service must be running" }
$running = docker inspect --format '{{.State.Running}}' $id
if ($LASTEXITCODE -ne 0 -or $running -ne 'true') { throw "$service stopped unexpectedly" }
}
Write-Output "PASS: $target really stopped; the other API, LB and database stayed running"
docker compose --env-file .env up -d --wait --wait-timeout 60 $target
if ($LASTEXITCODE -ne 0) { throw 'Restore failed' }
python -X utf8 scripts/wait_replicas.py
if ($LASTEXITCODE -ne 0) { throw 'LB recovery failed' }
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
case "${TARGET_INSTANCE_ID:-}" in api1|api2) ;; *) exit 2 ;; esac
id=$(docker compose --env-file .env ps -a -q "$TARGET_INSTANCE_ID")
test "$(docker inspect --format '{{.State.Running}}' "$id")" = false
for service in db lb api1 api2; do
test "$service" = "$TARGET_INSTANCE_ID" && continue
id=$(docker compose --env-file .env ps -q "$service")
test -n "$id"
test "$(docker inspect --format '{{.State.Running}}' "$id")" = true
done
echo "PASS: $TARGET_INSTANCE_ID really stopped; the other API, LB and database stayed running"
docker compose --env-file .env up -d --wait --wait-timeout 60 "$TARGET_INSTANCE_ID"
# Wait for HAProxy's next successful check; do not assume Compose health is LB health.
python3 scripts/wait_replicas.py
+11
View File
@@ -0,0 +1,11 @@
@echo off
cd /d "%~dp0.."
if "%TARGET_INSTANCE_ID%"=="api1" goto stop
if "%TARGET_INSTANCE_ID%"=="api2" goto stop
echo Expected TARGET_INSTANCE_ID=api1 or api2
exit /b 2
:stop
docker compose --env-file .env stop -t 3 %TARGET_INSTANCE_ID%
if errorlevel 1 exit /b 1
>evidence\last-stopped.txt echo %TARGET_INSTANCE_ID%
exit /b 0
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
case "${TARGET_INSTANCE_ID:-}" in
api1|api2) target="$TARGET_INSTANCE_ID" ;;
*) echo 'Expected TARGET_INSTANCE_ID=api1 or api2' >&2; exit 2 ;;
esac
docker compose --env-file .env stop -t 3 "$target"
# Only a nonsecret service alias, used by verification to prove both targets.
printf '%s\n' "$target" > evidence/last-stopped.txt
+28
View File
@@ -0,0 +1,28 @@
#!/bin/sh
# Requires Docker Compose, Python 3.9+ and make. Run from a clone or unpacked folder.
set -eu
cd "$(dirname "$0")/.."
export PYTHONUTF8=1
export PYTHONDONTWRITEBYTECODE=1
export BASE_URL="${BASE_URL:-http://localhost:${LAB3_HOST_PORT:-8080}}"
chmod +x scripts/restart.sh scripts/stop-one.sh scripts/restore.sh
echo "Lab 3 verification $(date -u '+%Y-%m-%dT%H:%M:%SZ')"
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build --wait --wait-timeout 90
make check
make test BASE_URL="$BASE_URL"
python3 tests/student_tests.py --base-url "$BASE_URL"
python3 tests/contract_edge_tests.py --base-url "$BASE_URL"
python3 tests/lab3_tests.py --base-url "$BASE_URL" --restart-script scripts/restart.sh
state=$(mktemp)
trap 'rm -f "$state"' EXIT
python3 scripts/operator_state.py --save "$state"
make test-persistence BASE_URL="$BASE_URL" ACTION_SCRIPT=scripts/restart.sh
python3 scripts/operator_state.py --compare "$state"
make test-failover BASE_URL="$BASE_URL" ACTION_SCRIPT=scripts/stop-one.sh
TARGET_INSTANCE_ID=$(cat evidence/last-stopped.txt)
export TARGET_INSTANCE_ID
sh scripts/restore.sh
python3 tests/failover_each.py --base-url "$BASE_URL" --action-script scripts/stop-one.sh --restore-script scripts/restore.sh
make test BASE_URL="$BASE_URL"
echo 'PASS: full Lab 3 verification completed'
+68
View File
@@ -0,0 +1,68 @@
param(
[ValidateRange(1, 65535)]
[int]$Port = 8080
)
$ErrorActionPreference = 'Stop'
$previousPort = $env:LAB3_HOST_PORT
$previousBase = $env:BASE_URL
$previousUtf8 = $env:PYTHONUTF8
$previousBytecode = $env:PYTHONDONTWRITEBYTECODE
function Assert-Success([string]$Step) {
if ($LASTEXITCODE -ne 0) { throw "$Step failed (exit code $LASTEXITCODE)" }
}
function Write-Evidence([string]$Line) {
Add-Content -LiteralPath $evidence -Value $Line -Encoding UTF8
Write-Host $Line
}
function Run-Python([string[]]$Arguments) {
Write-Evidence ("python " + ($Arguments -join ' '))
& python -X utf8 @Arguments | ForEach-Object { Write-Evidence $_ }
Assert-Success 'Python check'
}
Push-Location -LiteralPath (Join-Path $PSScriptRoot '..')
$state = Join-Path ([IO.Path]::GetTempPath()) ([guid]::NewGuid().ToString() + '.json')
try {
$env:PYTHONUTF8 = '1'
$env:PYTHONDONTWRITEBYTECODE = '1'
$env:LAB3_HOST_PORT = [string]$Port
if (!(Test-Path -LiteralPath '.env')) {
$password = python -X utf8 -c 'import secrets; print(secrets.token_hex(24))'
Assert-Success 'Local password generation'
(Get-Content -LiteralPath '.env.example') -replace '^POSTGRES_PASSWORD=.*', "POSTGRES_PASSWORD=$password" |
Set-Content -LiteralPath '.env' -Encoding Ascii
}
$evidence = 'evidence/results-windows.txt'
Set-Content -LiteralPath $evidence -Value ("Lab 3 verification " + (Get-Date -Format o)) -Encoding UTF8
docker compose --env-file .env config --quiet
Assert-Success 'Compose configuration'
docker compose --env-file .env up -d --build --wait --wait-timeout 90
Assert-Success 'Compose startup'
$address = docker compose --env-file .env port lb 8080
Assert-Success 'LB port lookup'
if ($address -notmatch '^127\.0\.0\.1:\d+$') { throw 'Expected local LB address' }
$env:BASE_URL = "http://$address"
Write-Evidence "PASS: Compose startup, public entrypoint $env:BASE_URL"
Run-Python @('scripts/check_contract.py')
Run-Python @('tests/smoke.py', '--base-url', $env:BASE_URL)
Run-Python @('tests/student_tests.py', '--base-url', $env:BASE_URL)
Run-Python @('tests/contract_edge_tests.py', '--base-url', $env:BASE_URL)
Run-Python @('tests/lab3_tests.py', '--base-url', $env:BASE_URL, '--restart-script', 'scripts/restart.cmd')
Run-Python @('scripts/operator_state.py', '--save', $state)
Run-Python @('tests/resilience.py', '--mode', 'persistence', '--base-url', $env:BASE_URL, '--action-script', 'scripts/restart.cmd')
Run-Python @('scripts/operator_state.py', '--compare', $state)
Run-Python @('tests/resilience.py', '--mode', 'failover', '--base-url', $env:BASE_URL, '--action-script', 'scripts/stop-one.cmd')
$env:TARGET_INSTANCE_ID = (Get-Content -LiteralPath 'evidence/last-stopped.txt').Trim()
& powershell -NoProfile -ExecutionPolicy Bypass -File scripts/restore.ps1 | ForEach-Object { Write-Evidence $_ }
Assert-Success 'Restore after public failover'
Run-Python @('tests/failover_each.py', '--base-url', $env:BASE_URL, '--action-script', 'scripts/stop-one.cmd', '--restore-script', 'scripts/restore.cmd')
Run-Python @('tests/smoke.py', '--base-url', $env:BASE_URL)
Write-Evidence 'PASS: full Lab 3 verification completed'
}
finally {
if (Test-Path -LiteralPath $state) { Remove-Item -LiteralPath $state }
$env:LAB3_HOST_PORT = $previousPort
$env:BASE_URL = $previousBase
$env:PYTHONUTF8 = $previousUtf8
$env:PYTHONDONTWRITEBYTECODE = $previousBytecode
Pop-Location
}
+20
View File
@@ -0,0 +1,20 @@
"""Wait until both real API aliases are observed through the LB."""
import os
import time
import urllib.request
base = os.environ.get('BASE_URL', 'http://localhost:8080')
seen = set()
deadline = time.monotonic() + 20
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(base + '/health/ready', timeout=2) as reply:
seen.add(reply.headers['X-Instance-Id'])
except OSError:
pass
if {'api1', 'api2'} <= seen:
print('PASS: both replicas observed through LB')
break
time.sleep(0.15)
else:
raise SystemExit('Both API replicas did not return to LB')
+108
View File
@@ -0,0 +1,108 @@
"""Inherited contract checks (stdlib only). Needs running LB + API + PostgreSQL.
Run: python tests/contract_edge_tests.py --base-url http://localhost:8080
Prints only status summary; credentials/tokens remain in process memory.
"""
import argparse
import base64
import json
import urllib.error
import urllib.parse
import urllib.request
import uuid
class Client:
def __init__(self, base):
self.base = base.rstrip('/')
self.count = 0
def call(self, method, path, expected, payload=None, auth=None, raw=None, content_type=None):
headers = {'Accept': 'application/json'}
if method == 'POST' and path.endswith('/messages'):
headers['Idempotency-Key'] = uuid.uuid4().hex
if auth:
headers['Authorization'] = auth
if payload is not None:
raw = json.dumps(payload, ensure_ascii=True).encode('utf-8')
content_type = 'application/json'
if content_type:
headers['Content-Type'] = content_type
req = urllib.request.Request(self.base + path, data=raw, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=15) as response:
code = response.status
body = response.read()
reply_headers = response.headers
except urllib.error.HTTPError as error:
code = error.code
body = error.read()
reply_headers = error.headers
if code != expected:
raise AssertionError(f'{method} {path}: expected {expected}, received {code}')
if not reply_headers.get('X-Request-Id'):
raise AssertionError(f'{method} {path}: missing X-Request-Id')
if not reply_headers.get('X-Instance-Id'):
raise AssertionError(f'{method} {path}: missing X-Instance-Id')
self.count += 1
return json.loads(body) if body else None
def run(base):
c = Client(base)
prefix = uuid.uuid4().hex[:14]
name = 'ct_' + prefix
password = 'ContractTest-' + uuid.uuid4().hex[:16]
user_path = '/api/v1/users'
actor_path = '/api/v1/auth/sessions'
registration = {'username': name, 'display_name': 'Тест Unicode', 'password': password}
# Public registration must reject unknown fields and malformed Unicode.
c.call('POST', user_path, 400, payload={**registration, 'unknown': 'field'})
c.call('POST', user_path, 400, payload={**registration, 'display_name': '\ud800'})
c.call('POST', user_path, 415, raw=b'{}', content_type='text/plain')
user = c.call('POST', user_path, 201, payload=registration)
if user['username'] != name:
raise AssertionError('registration username mismatch')
basic = 'Basic ' + base64.b64encode((name + ':' + password).encode('utf-8')).decode('ascii')
# Login is Basic-only, without a JSON request body.
c.call('POST', actor_path, 400, auth=basic, payload={'unknown': 'field'})
session = c.call('POST', actor_path, 201, auth=basic)
bearer = 'Bearer ' + session['token']
# Protected POST endpoints must authenticate before parsing malformed JSON.
c.call('POST', '/api/v1/chats', 401, raw=b'{invalid', content_type='application/json')
c.call('POST', '/api/v1/chats', 400, auth=bearer, raw=b'{invalid', content_type='application/json')
c.call('POST', '/api/v1/chats', 415, auth=bearer, raw=b'{}', content_type='text/plain')
c.call('GET', '/api/v1/chats/' + uuid.uuid4().hex, 400, auth=bearer)
c.call('POST', '/api/v1/chats', 400, auth=bearer,
payload={'title': 'duplicate', 'member_ids': [user['id'], user['id']]})
c.call('POST', '/api/v1/chats', 400, auth=bearer,
payload={'title': 'missing author', 'member_ids': [str(uuid.uuid4())]})
chat1 = c.call('POST', '/api/v1/chats', 201, auth=bearer,
payload={'title': 'Page A', 'member_ids': [user['id']]})
chat2 = c.call('POST', '/api/v1/chats', 201, auth=bearer,
payload={'title': 'Page B', 'member_ids': [user['id']]})
msg_path1 = '/api/v1/chats/' + chat1['id'] + '/messages'
msg_path2 = '/api/v1/chats/' + chat2['id'] + '/messages'
c.call('POST', msg_path1, 401, raw=b'{invalid', content_type='application/json')
c.call('POST', msg_path1, 400, auth=bearer, raw=b'{invalid', content_type='application/json')
for i in range(2):
c.call('POST', msg_path1, 201, auth=bearer, payload={'text': f'Page test {i}'})
page = c.call('GET', msg_path1 + '?limit=1', 200, auth=bearer)
cursor = page.get('next_cursor')
if not cursor or len(page['items']) != 1:
raise AssertionError('expected next_cursor for two messages')
c.call('GET', msg_path2 + '?limit=1&cursor=' + urllib.parse.quote(cursor, safe=''), 400, auth=bearer)
c.call('GET', msg_path1 + '?limit=1&limit=2', 400, auth=bearer)
c.call('GET', msg_path1 + '?limit=1&cursor=@invalid@', 400, auth=bearer)
print(f'PASS: {c.count} Lab 2 contract edge-case HTTP checks')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--base-url', default='http://localhost:8080')
args = parser.parse_args()
run(args.base_url)
+74
View File
@@ -0,0 +1,74 @@
"""Operator scenario: stop each real replica and verify writes, reads and replay via LB."""
import json
import os
from pathlib import Path
import subprocess
import time
import uuid
from client import Client, Failure, arguments, check, run
from resilience import history
def configure(p):
p.add_argument('--action-script', required=True)
p.add_argument('--restore-script', required=True)
def main():
args = arguments('Stop either API replica with the other running', configure)
c = Client(args.base_url, args.ca_file, timeout=2)
alice, bob, _, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/messages'
for target in ('api1', 'api2'):
seen = {c.call('GET', '/api/v1/users/me', actor=alice)['headers']['X-Instance-Id'] for _ in range(20)}
check(seen == {'api1', 'api2'}, 'both replicas required before stop')
key = uuid.uuid4().hex
original = c.message(alice, chat, 'Сохранить ' + key, key=key)['json']
env = dict(os.environ, TARGET_INSTANCE_ID=target)
action = Path(args.action_script).resolve()
start = time.monotonic()
proc = subprocess.Popen([str(action)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
errors, confirmed, instances = 0, [], []
recovery = None
pending_key = uuid.uuid4().hex
try:
while time.monotonic() - start < 6:
check(proc.poll() in (None, 0), 'stop hook failed')
try:
# Same session, same message/key even after losing its original replica.
repeated = c.message(alice, chat, original['text'], key=key)
reply = c.message(alice, chat, 'После отказа ' + pending_key, key=pending_key)
confirmed.append(reply['json'])
pending_key = uuid.uuid4().hex
page = history(c, bob, chat)
except Failure:
errors += 1
else:
check(repeated['json'] == original, 'failover changed replayed Message')
check(original in page and all(m in page for m in confirmed), 'confirmed data lost')
if proc.poll() == 0:
instances.append(reply['headers']['X-Instance-Id'])
if recovery is None:
recovery = time.monotonic() - start
time.sleep(0.1)
check(proc.wait(timeout=3) == 0, 'stop hook failed')
check(recovery is not None and recovery <= 10, 'recovery exceeded ten seconds')
check(len(instances) >= 5 and target not in instances[-5:], 'stopped replica still serves requests')
page = history(c, bob, chat)
check(original in page and all(m in page for m in confirmed), 'confirmed data lost')
for text in {m['text'] for m in confirmed}:
check(sum(m['text'] == text for m in page) == 1, 'retry duplicate')
print(json.dumps({'stopped': target, 'observed_before': sorted(seen),
'survivors': sorted(set(instances[-5:])), 'writes': len(confirmed),
'errors': errors, 'recovery_seconds': round(recovery, 3)}))
finally:
if proc.poll() is None:
proc.kill()
proc.wait()
# Record actual stopped process and intact dependencies before restoring.
subprocess.run([str(Path(args.restore_script).resolve())], check=True, timeout=60, env=env)
print('PASS: stopping either replica preserved sessions, reads, writes and idempotency')
if __name__ == '__main__':
run(main)
+100
View File
@@ -0,0 +1,100 @@
"""Black-box cross-replica idempotency tests. All HTTP goes through the LB."""
from concurrent.futures import ThreadPoolExecutor
import json
import os
from pathlib import Path
import socket
import subprocess
import threading
import time
from urllib.parse import urlsplit
import uuid
from client import Client, arguments, check, run
def configure(p):
p.add_argument('--restart-script', help='Optional full-stack restart, preserving volumes')
def main():
args = arguments('Shared idempotency and previous-lab behavior', configure)
c = Client(args.base_url, args.ca_file, timeout=8)
alice, bob, outsider, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/messages'
key = uuid.uuid4().hex
barrier = threading.Barrier(16)
def send(i):
local = Client(args.base_url, args.ca_file, timeout=8)
barrier.wait(timeout=10)
# Reordered keys, explicit [] and omission must be equivalent.
body = {'attachment_ids': [], 'text': 'Одна параллельная запись'} if i % 2 else {'text': 'Одна параллельная запись'}
return local.call('POST', path, 201, actor=alice, body=body,
headers={'Idempotency-Key': key}, schema='Message')
with ThreadPoolExecutor(max_workers=16) as pool:
replies = list(pool.map(send, range(16)))
original = replies[0]['json']
check(all(r['json'] == original for r in replies), 'concurrent replay changed the Message')
instances = sorted({r['headers']['X-Instance-Id'] for r in replies})
check(len(instances) >= 2, 'race did not reach two API processes')
page = c.call('GET', path, actor=alice, schema='MessagePage')['json']
check(page['items'] == [original], 'concurrent repeat inserted duplicate messages')
print(json.dumps({'parallel_requests': 16, 'instances': instances, 'messages_created': 1}))
c.call('POST', path, 409, actor=alice, body={'text': 'Другой текст'}, headers={'Idempotency-Key': key})
for invalid in ('', 'with space', 'a' * 129, 'with/slash', 'bad,key'):
c.call('POST', path, 400, actor=alice, body={'text': 'bad key'}, headers={'Idempotency-Key': invalid})
c.call('POST', path, 400, actor=alice, body={'text': 'missing'})
c.call('POST', path, 404, actor=outsider, body={'text': original['text']}, headers={'Idempotency-Key': key})
# The same key belongs independently to another user or chat.
other = c.message(bob, chat, 'Другой отправитель', key=key)['json']
check(other['id'] != original['id'], 'key incorrectly shared between users')
second_chat = c.call('POST', '/api/v1/chats', 201, actor=alice, schema='Chat',
body={'title': 'Другой чат', 'member_ids': [alice['id'], bob['id']]})['json']
separate = c.message(alice, second_chat, original['text'], key=key)['json']
check(separate['id'] != original['id'], 'key incorrectly shared between chats')
# Send a complete POST and close the connection without reading its outcome.
# Retry the exact key/body through the LB, regardless of which API committed.
uncertain_key = uuid.uuid4().hex
body = json.dumps({'text': 'Неизвестный клиенту результат'}, ensure_ascii=False).encode()
url = urlsplit(args.base_url)
check(url.scheme == 'http', 'local lost-response scenario expects http')
raw = (f'POST {path} HTTP/1.1\r\nHost: {url.netloc}\r\n'
f'Authorization: Bearer {alice["token"]}\r\nIdempotency-Key: {uncertain_key}\r\n'
f'Content-Type: application/json\r\nContent-Length: {len(body)}\r\nConnection: close\r\n\r\n').encode() + body
with socket.create_connection((url.hostname, url.port or 80), timeout=5) as conn:
conn.sendall(raw)
conn.shutdown(socket.SHUT_WR)
replayed = c.message(alice, chat, 'Неизвестный клиенту результат', key=uncertain_key)['json']
repeated = c.message(alice, chat, 'Неизвестный клиенту результат', key=uncertain_key)['json']
check(replayed == repeated, 'uncertain write cannot be retried')
messages = c.call('GET', path, actor=bob, schema='MessagePage')['json']['items']
check(sum(m['text'] == replayed['text'] for m in messages) == 1, 'uncertain result created a duplicate')
if args.restart_script:
script = Path(args.restart_script).resolve()
subprocess.run([str(script)], check=True, timeout=90, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
deadline = time.monotonic() + 60
while True:
try:
c.call('GET', '/health/ready', schema='Health')
break
except AssertionError:
check(time.monotonic() < deadline, 'LB did not recover')
time.sleep(0.25)
recovered = [c.message(alice, chat, original['text'], key=key) for _ in range(12)]
check(all(r['json'] == original for r in recovered), 'restart lost idempotency record')
check(len({r['headers']['X-Instance-Id'] for r in recovered}) >= 2, 'both APIs did not recover')
print('PASS: same session and exact Message replay after full-stack restart')
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
for _ in range(6):
c.call('POST', path, 401, actor=alice, body={'text': original['text']}, headers={'Idempotency-Key': key})
print('PASS: concurrent replay, normalized JSON, key scope, conflict, invalid key, access, uncertain response and logout')
if __name__ == '__main__':
run(main)
+69
View File
@@ -0,0 +1,69 @@
"""Simple grade-3 negative scenarios; run with the API+Postgres already started."""
import base64
import time
import uuid
from urllib.parse import quote
from client import Client, arguments, check, run
def configure(parser):
parser.add_argument('--expiry', action='store_true', help='Run only with SESSION_TTL_SECONDS=2')
def main():
args = arguments('Lab 2 student tests', configure)
c = Client(args.base_url, args.ca_file)
if args.expiry:
user = c.user('expiry')
c.call('GET', '/api/v1/users/me', actor=user, schema='User')
deadline = time.monotonic() + 12
while time.monotonic() < deadline:
response = c.call('GET', '/api/v1/users/me', (200, 401), actor=user, schema='User')
if response['status'] == 401:
print('PASS: Bearer session expires without logout')
return
time.sleep(0.25)
check(False, 'session did not expire; start API with SESSION_TTL_SECONDS=2')
alice, _, outsider, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id']
login_path = '/api/v1/auth/sessions'
json_header = {'Content-Type': 'application/json'}
c.call('POST', '/api/v1/users', 409, body=alice['registration'])
c.call('POST', '/api/v1/users', 400, raw=b'{invalid', headers=json_header)
c.call('POST', '/api/v1/chats', 401, raw=b'{invalid', headers=json_header)
c.call('POST', path + '/messages', 401, raw=b'{invalid', headers=json_header)
c.call('GET', path, 404, actor=outsider)
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']})
c.call('GET', path + '/messages?limit=0', 400, actor=alice)
c.call('GET', '/api/v1/chats/' + chat['id'].replace('-', ''), 400, actor=alice)
username = 'unicode_' + uuid.uuid4().hex[:12]
password = 'Пароль:abc-123456'
bad = f'{{"username":"{username}","display_name":"\\ud800","password":"{password}"}}'.encode('utf-8')
c.call('POST', '/api/v1/users', 400, raw=bad, headers=json_header)
registered = c.call('POST', '/api/v1/users', 201, schema='User',
body={'username': username, 'display_name': 'Проверка 👋', 'password': password})['json']
credentials = base64.b64encode(f'{username}:{password}'.encode('utf-8')).decode('ascii')
auth = {'Authorization': 'Basic ' + credentials}
c.call('POST', login_path, 400, body={}, headers=auth)
session = c.call('POST', login_path, 201, headers=auth, schema='Session')['json']
check(session['user'] == registered, 'Unicode Basic login returned the wrong user')
c.message(alice, chat, 'Первая запись')
c.message(alice, chat, 'Вторая запись')
first = c.call('GET', path + '/messages?limit=1', actor=alice, schema='MessagePage')['json']
check(bool(first['next_cursor']), 'missing second page')
c.call('GET', path + '/messages?cursor=' + quote(first['next_cursor'] + '!', safe=''), 400, actor=alice)
second = c.call('GET', path + '/messages?limit=1&cursor=' + quote(first['next_cursor'], safe=''),
actor=alice, schema='MessagePage')['json']
check(len(second['items']) == 1 and second['next_cursor'] is None, 'incorrect last page')
check(first['items'][0]['id'] != second['items'][0]['id'], 'pagination repeated a message')
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
c.call('GET', '/api/v1/users/me', 401, actor=alice)
print('PASS: validation, Unicode Basic login, access, pagination and logout')
if __name__ == '__main__':
run(main)