lab3: haproxy, replicas, idempotency, automated failover tests

This commit is contained in:
2026-10-26 23:39:49 +03:00
commit f33c3b2382
66 changed files with 5314 additions and 0 deletions
View File
+24
View File
@@ -0,0 +1,24 @@
"""Entry point: uvicorn as PID 1 with env-driven host/port and graceful shutdown."""
import os
import uvicorn
from .main import app
def main() -> None:
host = os.environ.get("APP_HOST", "0.0.0.0")
port = int(os.environ.get("APP_PORT", "8080"))
uvicorn.run(
app,
host=host,
port=port,
log_level="info",
access_log=True,
timeout_keep_alive=2,
timeout_graceful_shutdown=5,
)
if __name__ == "__main__":
main()
+29
View File
@@ -0,0 +1,29 @@
import os
import secrets
import redis.asyncio as redis
from passlib.context import CryptContext
# bcrypt_sha256 avoids bcrypt's 72-byte limit. Old lab2 hashes still verify.
pwd_context = CryptContext(schemes=["bcrypt_sha256", "bcrypt"], deprecated="auto")
CACHE_URL = os.environ.get("CACHE_URL", "redis://localhost:6379/0")
SESSION_TTL_SECONDS = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
redis_client = redis.from_url(CACHE_URL, decode_responses=True,
socket_connect_timeout=1, socket_timeout=1)
def hash_password(password: str) -> str:
return pwd_context.hash(password)
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
async def create_session(user_id: str) -> str:
token = secrets.token_urlsafe(32)
await redis_client.setex(f"session:{token}", SESSION_TTL_SECONDS, user_id)
return token
async def get_user_id_by_token(token: str) -> str | None:
return await redis_client.get(f"session:{token}")
async def delete_session(token: str) -> None:
await redis_client.delete(f"session:{token}")
+69
View File
@@ -0,0 +1,69 @@
import os
from datetime import datetime, timezone
from typing import List
from uuid import UUID, uuid4
from sqlalchemy import String, ForeignKey, DateTime, Index, Integer
from sqlalchemy.dialects.postgresql import UUID as PG_UUID, JSONB
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
DATABASE_URL = os.environ.get("DATABASE_URL", "postgresql+asyncpg://user:password@localhost:5432/messenger")
engine = create_async_engine(
DATABASE_URL, echo=False, pool_pre_ping=True, pool_size=5, max_overflow=5,
pool_timeout=2, connect_args={"timeout": 1, "command_timeout": 3,
"server_settings": {"statement_timeout": "2500", "lock_timeout": "2000"}},
)
async_session = async_sessionmaker(engine, expire_on_commit=False)
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = "users"
id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid4)
username: Mapped[str] = mapped_column(String(32), unique=True, index=True)
display_name: Mapped[str] = mapped_column(String(100))
password_hash: Mapped[str] = mapped_column(String(255))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
class Chat(Base):
__tablename__ = "chats"
id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid4)
title: Mapped[str] = mapped_column(String(100))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
members: Mapped[List["ChatMember"]] = relationship(back_populates="chat", lazy="selectin")
class ChatMember(Base):
__tablename__ = "chat_members"
chat_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), primary_key=True)
user_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True)
chat: Mapped["Chat"] = relationship(back_populates="members")
user: Mapped["User"] = relationship()
class Message(Base):
__tablename__ = "messages"
id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid4)
chat_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), index=True)
sender_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("users.id"))
text: Mapped[str] = mapped_column(String(4000))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
# Составной индекс для быстрой курсорной пагинации (EXPLAIN покажет Index Scan)
__table_args__ = (
Index('ix_messages_chat_created_id', 'chat_id', 'created_at', 'id'),
)
class IdempotencyKey(Base):
__tablename__ = "idempotency_keys"
user_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("users.id"), primary_key=True)
chat_id: Mapped[UUID] = mapped_column(PG_UUID(as_uuid=True), ForeignKey("chats.id"), primary_key=True)
key: Mapped[str] = mapped_column(String(128), primary_key=True)
request_text: Mapped[str] = mapped_column(String(4000))
response: Mapped[dict | None] = mapped_column(JSONB, nullable=True)
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
class SchemaVersion(Base):
__tablename__ = "schema_versions"
version: Mapped[int] = mapped_column(Integer, primary_key=True)
+372
View File
@@ -0,0 +1,372 @@
from __future__ import annotations
import base64
import asyncio
import binascii
import logging
import os
import re
import socket
import uuid
from contextlib import asynccontextmanager
from datetime import datetime, timezone, timedelta
from typing import Optional
from fastapi import Depends, FastAPI, Request, Query
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel, ConfigDict, Field, field_validator
from sqlalchemy import select, and_, or_, text
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException as StarletteHTTPException
from redis.exceptions import RedisError
from asyncpg import PostgresError
from .db import engine, async_session, User, Chat, ChatMember, Message, IdempotencyKey
from .auth import hash_password, verify_password, create_session, get_user_id_by_token, delete_session, redis_client, SESSION_TTL_SECONDS
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}", re.ASCII)
INSTANCE_ID = socket.gethostname() + ":" + str(os.getpid())
def now_iso(dt: datetime = None) -> str:
if not dt:
dt = datetime.now(timezone.utc)
return dt.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
def error_payload(request_id: str, code: str, message: str) -> dict:
return {"error": {"code": code, "message": message, "request_id": request_id}}
class ApiError(Exception):
def __init__(self, status: int, code: str, message: str):
self.status = status
self.code = code
self.message = message
super().__init__(message)
# --- Курсоры для пагинации (с точностью до микросекунд) ---
def _encode_cursor(scope: str, created_at: datetime, obj_id: uuid.UUID) -> str:
raw = f"{scope}|{created_at.isoformat()}|{obj_id}".encode("utf-8")
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
def _decode_cursor(cursor: str) -> tuple[str, datetime, uuid.UUID]:
try:
padded = cursor + "=" * (-len(cursor) % 4)
raw = base64.urlsafe_b64decode(padded).decode("utf-8")
scope, dt_str, obj_id_str = raw.split("|", 2)
dt = datetime.fromisoformat(dt_str)
if dt.tzinfo is None:
raise ValueError("timezone required")
return scope, dt, uuid.UUID(obj_id_str)
except Exception:
raise ApiError(400, "invalid_request", "invalid cursor")
# --- Схемы ---
class CreateUser(BaseModel):
model_config = ConfigDict(extra="forbid")
username: str = Field(strict=True)
display_name: str = Field(strict=True, min_length=1, max_length=100)
password: str = Field(strict=True, min_length=12, max_length=128)
@field_validator("display_name", "password")
@classmethod
def not_blank(cls, value):
if not value.strip():
raise ValueError("blank value")
return value
class CreateChat(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str = Field(strict=True, min_length=1, max_length=100)
member_ids: list[uuid.UUID] = Field(min_length=1, max_length=100)
@field_validator("title")
@classmethod
def not_blank(cls, value):
if not value.strip():
raise ValueError("blank title")
return value
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(strict=True, min_length=1, max_length=4000)
@field_validator("text")
@classmethod
def not_blank(cls, value):
if not value.strip():
raise ValueError("blank message")
return value
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
await redis_client.aclose()
await engine.dispose()
app = FastAPI(title="Messenger", version="1.3.0", lifespan=lifespan)
security_bearer = HTTPBearer(auto_error=False)
@app.middleware("http")
async def request_id_middleware(request: Request, call_next):
request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
request.state.request_id = request_id
try:
response = await call_next(request)
except Exception:
logging.getLogger(__name__).exception("Request failed: %s", request_id)
response = JSONResponse(status_code=500, content=error_payload(request_id, "internal_error", "internal error"))
response.headers["X-Request-Id"] = request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
def _rid(request: Request) -> str:
return getattr(request.state, "request_id", None) or str(uuid.uuid4())
# --- Обработчики ошибок ---
@app.exception_handler(ApiError)
async def api_error_handler(request: Request, exc: ApiError):
headers = {}
if exc.status == 401:
if request.url.path == "/api/v1/auth/sessions":
headers["WWW-Authenticate"] = 'Basic realm="messenger", charset="UTF-8"'
else:
headers["WWW-Authenticate"] = 'Bearer realm="messenger"'
return JSONResponse(status_code=exc.status, content=error_payload(_rid(request), exc.code, exc.message), headers=headers)
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
return JSONResponse(status_code=400, content=error_payload(_rid(request), "invalid_request", "invalid request"))
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
return JSONResponse(status_code=exc.status_code, content=error_payload(_rid(request), "not_found", str(exc.detail)))
@app.exception_handler(RedisError)
@app.exception_handler(SQLAlchemyError)
@app.exception_handler(PostgresError)
@app.exception_handler(OSError)
@app.exception_handler(TimeoutError)
async def dependency_error_handler(request: Request, exc: Exception):
# Если упала БД или Redis - отдаем 503, как требует контракт
return JSONResponse(status_code=503, content=error_payload(_rid(request), "unavailable", "dependency unavailable"))
@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception):
return JSONResponse(status_code=500, content=error_payload(_rid(request), "internal_error", "internal error"))
# --- Зависимости ---
async def get_actor(credentials: HTTPAuthorizationCredentials = Depends(security_bearer)) -> dict:
if not credentials:
raise ApiError(401, "unauthorized", "missing token")
user_id_str = await get_user_id_by_token(credentials.credentials)
if not user_id_str:
raise ApiError(401, "unauthorized", "invalid or expired token")
async with async_session() as session:
user = await session.get(User, uuid.UUID(user_id_str))
if not user:
raise ApiError(401, "unauthorized", "user not found")
return {"id": str(user.id), "username": user.username, "display_name": user.display_name, "created_at": now_iso(user.created_at)}
# --- Роуты ---
@app.get("/health/live")
def liveness():
return {"status": "ok"}
@app.get("/health/ready")
async def readiness():
async with asyncio.timeout(1.5):
async with async_session() as session:
version = await session.scalar(text("SELECT version FROM schema_versions WHERE version = 3"))
if version != 3:
raise ApiError(503, "unavailable", "migration required")
await redis_client.ping()
return {"status": "ok"}
@app.post("/api/v1/users", status_code=201)
async def register_user(payload: CreateUser):
if not USERNAME_RE.fullmatch(payload.username):
raise ApiError(400, "invalid_request", "invalid username")
async with async_session() as session:
existing = await session.scalar(select(User).where(User.username == payload.username))
if existing:
raise ApiError(409, "conflict", "username already exists")
password_hash = await run_in_threadpool(hash_password, payload.password)
user = User(username=payload.username, display_name=payload.display_name, password_hash=password_hash)
session.add(user)
try:
await session.commit()
except IntegrityError:
await session.rollback()
raise ApiError(409, "conflict", "username already exists")
return {"id": str(user.id), "username": user.username, "display_name": user.display_name, "created_at": now_iso(user.created_at)}
@app.post("/api/v1/auth/sessions", status_code=201)
async def create_session_endpoint(request: Request):
# HTTP Basic carries a UTF-8 password, not only ASCII.
try:
scheme, encoded = request.headers.get("Authorization", "").split(" ", 1)
if scheme.lower() != "basic":
raise ValueError("Basic required")
username, password = base64.b64decode(encoded, validate=True).decode("utf-8").split(":", 1)
except (ValueError, UnicodeError, binascii.Error):
raise ApiError(401, "unauthorized", "invalid credentials")
async with async_session() as session:
user = await session.scalar(select(User).where(User.username == username))
if not user or not await run_in_threadpool(verify_password, password, user.password_hash):
raise ApiError(401, "unauthorized", "invalid credentials")
token = await create_session(str(user.id))
expires_at = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS)
return {
"token": token,
"token_type": "Bearer",
"expires_at": now_iso(expires_at),
"user": {"id": str(user.id), "username": user.username, "display_name": user.display_name, "created_at": now_iso(user.created_at)}
}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def logout(credentials: HTTPAuthorizationCredentials = Depends(security_bearer)):
if not credentials:
raise ApiError(401, "unauthorized", "missing token")
user_id = await get_user_id_by_token(credentials.credentials)
if not user_id:
raise ApiError(401, "unauthorized", "invalid or expired token")
await delete_session(credentials.credentials)
@app.get("/api/v1/users/me")
async def current_user(actor: dict = Depends(get_actor)):
return actor
@app.post("/api/v1/chats", status_code=201)
async def create_chat(payload: CreateChat, actor: dict = Depends(get_actor)):
member_ids = [str(u) for u in payload.member_ids]
if actor["id"] not in member_ids:
raise ApiError(400, "invalid_request", "creator must be a member")
if len(set(member_ids)) != len(member_ids):
raise ApiError(400, "invalid_request", "duplicate members")
async with async_session() as session:
users = await session.scalars(select(User.id).where(User.id.in_([uuid.UUID(m) for m in member_ids])))
if len(list(users)) != len(set(member_ids)):
raise ApiError(400, "invalid_request", "unknown member")
chat = Chat(title=payload.title)
session.add(chat)
await session.flush()
for mid in member_ids:
session.add(ChatMember(chat_id=chat.id, user_id=uuid.UUID(mid)))
await session.commit()
return {"id": str(chat.id), "title": chat.title, "member_ids": member_ids, "created_at": now_iso(chat.created_at)}
@app.get("/api/v1/chats")
async def list_chats(limit: int = Query(50, ge=1, le=100), cursor: Optional[str] = None, actor: dict = Depends(get_actor)):
async with async_session() as session:
stmt = select(Chat).join(ChatMember).where(ChatMember.user_id == uuid.UUID(actor["id"]))
if cursor:
scope, c_dt, c_id = _decode_cursor(cursor)
if scope != "chats":
raise ApiError(400, "invalid_request", "invalid cursor scope")
stmt = stmt.where(or_(
Chat.created_at > c_dt,
and_(Chat.created_at == c_dt, Chat.id > c_id)
))
stmt = stmt.order_by(Chat.created_at.asc(), Chat.id.asc()).limit(limit + 1)
chats = (await session.scalars(stmt)).unique().all()
has_more = len(chats) > limit
page = chats[:limit]
next_cursor = _encode_cursor("chats", page[-1].created_at, page[-1].id) if has_more and page else None
items = []
for c in page:
items.append({
"id": str(c.id),
"title": c.title,
"created_at": now_iso(c.created_at),
"member_ids": [str(m.user_id) for m in c.members] # Теперь участники возвращаются корректно
})
return {"items": items, "next_cursor": next_cursor}
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(chat_id: uuid.UUID, actor: dict = Depends(get_actor)):
async with async_session() as session:
chat = await session.scalar(select(Chat).join(ChatMember).where(Chat.id == chat_id, ChatMember.user_id == uuid.UUID(actor["id"])))
if not chat:
raise ApiError(404, "not_found", "chat not found")
return {"id": str(chat.id), "title": chat.title, "member_ids": [str(m.user_id) for m in chat.members], "created_at": now_iso(chat.created_at)}
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def post_message(chat_id: uuid.UUID, payload: CreateMessage, request: Request, actor: dict = Depends(get_actor)):
key = request.headers.get("Idempotency-Key", "")
if not KEY_RE.fullmatch(key):
raise ApiError(400, "invalid_request", "invalid Idempotency-Key")
async with async_session() as session:
member = await session.scalar(select(ChatMember).where(and_(ChatMember.chat_id == chat_id, ChatMember.user_id == uuid.UUID(actor["id"]))))
if not member:
raise ApiError(404, "not_found", "chat not found")
now = datetime.now(timezone.utc)
scope = {"user_id": uuid.UUID(actor["id"]), "chat_id": chat_id, "key": key}
await session.execute(insert(IdempotencyKey).values(
**scope, request_text=payload.text, expires_at=now + timedelta(hours=24)
).on_conflict_do_nothing())
record = await session.scalar(select(IdempotencyKey).where(
IdempotencyKey.user_id == scope["user_id"],
IdempotencyKey.chat_id == chat_id, IdempotencyKey.key == key
).with_for_update())
if record.response is not None and record.expires_at > now:
if record.request_text != payload.text:
raise ApiError(409, "conflict", "key used with another message")
return record.response
msg = Message(chat_id=chat_id, sender_id=uuid.UUID(actor["id"]), text=payload.text)
session.add(msg)
await session.flush()
result = {"id": str(msg.id), "chat_id": str(msg.chat_id), "sender_id": str(msg.sender_id), "text": msg.text, "created_at": now_iso(msg.created_at)}
record.request_text = payload.text
record.expires_at = now + timedelta(hours=24)
record.response = result
await session.commit()
return result
@app.get("/api/v1/chats/{chat_id}/messages")
async def get_messages(chat_id: uuid.UUID, limit: int = Query(50, ge=1, le=100), cursor: Optional[str] = None, actor: dict = Depends(get_actor)):
async with async_session() as session:
member = await session.scalar(select(ChatMember).where(and_(ChatMember.chat_id == chat_id, ChatMember.user_id == uuid.UUID(actor["id"]))))
if not member:
raise ApiError(404, "not_found", "chat not found")
stmt = select(Message).where(Message.chat_id == chat_id)
if cursor:
scope, c_dt, c_id = _decode_cursor(cursor)
if scope != str(chat_id):
raise ApiError(400, "invalid_request", "invalid cursor scope")
stmt = stmt.where(or_(
Message.created_at > c_dt,
and_(Message.created_at == c_dt, Message.id > c_id)
))
stmt = stmt.order_by(Message.created_at.asc(), Message.id.asc()).limit(limit + 1)
messages = (await session.scalars(stmt)).all()
has_more = len(messages) > limit
page = messages[:limit]
next_cursor = _encode_cursor(str(chat_id), page[-1].created_at, page[-1].id) if has_more and page else None
items = [{"id": str(m.id), "chat_id": str(m.chat_id), "sender_id": str(m.sender_id), "text": m.text, "created_at": now_iso(m.created_at)} for m in page]
return {"items": items, "next_cursor": next_cursor}
+18
View File
@@ -0,0 +1,18 @@
import asyncio
from sqlalchemy import text
from .db import Base, engine
async def main():
async with engine.begin() as conn:
# Only the migrate service creates tables; concurrent operators serialize.
await conn.execute(text("SELECT pg_advisory_xact_lock(300300)"))
await conn.run_sync(Base.metadata.create_all)
await conn.execute(text("INSERT INTO schema_versions(version) VALUES (3) ON CONFLICT DO NOTHING"))
await engine.dispose()
print("Migration 3 applied: existing lab2 tables kept, idempotency added")
if __name__ == "__main__":
asyncio.run(main())