forked from mtusi2026/mtusi2026lab3
Добавить балансировку API и атомарные повторы сообщений
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""One-process implementation of the lab 1 messenger contract."""
|
||||
@@ -0,0 +1,24 @@
|
||||
import logging
|
||||
import os
|
||||
|
||||
import uvicorn
|
||||
|
||||
|
||||
def main():
|
||||
level = os.getenv("APP_LOG_LEVEL", "INFO").upper()
|
||||
logging.basicConfig(level=level, format="%(message)s")
|
||||
uvicorn.run(
|
||||
"messenger.app:create_app",
|
||||
factory=True,
|
||||
host=os.getenv("APP_HOST", "0.0.0.0"),
|
||||
port=int(os.getenv("APP_PORT", "8080")),
|
||||
workers=1,
|
||||
access_log=False,
|
||||
log_level=level.lower(),
|
||||
timeout_keep_alive=2,
|
||||
timeout_graceful_shutdown=5,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,286 @@
|
||||
"""HTTP adapter. The instructor's OpenAPI, not FastAPI defaults, defines errors."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from contextlib import asynccontextmanager
|
||||
from time import perf_counter
|
||||
from typing import Annotated
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import Depends, FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from starlette.exceptions import HTTPException
|
||||
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
||||
|
||||
from messenger.auth import AuthService, Identity, basic_credentials, bearer_digest, unauthorized
|
||||
from messenger.cache import SessionCache
|
||||
from messenger.domain import DomainError, User, invalid
|
||||
from messenger.repository import PostgresRepository
|
||||
from messenger.schemas import (
|
||||
ChatPage,
|
||||
ChatView,
|
||||
CreateChat,
|
||||
CreateMessage,
|
||||
CreateUser,
|
||||
MessagePage,
|
||||
MessageView,
|
||||
SessionView,
|
||||
UserView,
|
||||
canonical_uuid,
|
||||
)
|
||||
from messenger.service import Messenger
|
||||
from messenger.settings import Settings
|
||||
|
||||
logger = logging.getLogger("messenger")
|
||||
|
||||
|
||||
class RequestContext:
|
||||
def __init__(self, app: ASGIApp, instance_id: str):
|
||||
self.app = app
|
||||
self.instance_id = instance_id
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send):
|
||||
if scope["type"] != "http":
|
||||
return await self.app(scope, receive, send)
|
||||
request_id = str(uuid4())
|
||||
scope.setdefault("state", {})["request_id"] = request_id
|
||||
start, status, response_started = perf_counter(), 500, False
|
||||
|
||||
async def with_id(message: Message):
|
||||
nonlocal status, response_started
|
||||
if message["type"] == "http.response.start":
|
||||
response_started = True
|
||||
status = message["status"]
|
||||
message["headers"] = [
|
||||
pair
|
||||
for pair in message.get("headers", [])
|
||||
if pair[0].lower() not in (b"x-request-id", b"x-instance-id")
|
||||
] + [
|
||||
(b"x-request-id", request_id.encode()),
|
||||
(b"x-instance-id", self.instance_id.encode()),
|
||||
]
|
||||
await send(message)
|
||||
|
||||
try:
|
||||
await self.app(scope, receive, with_id)
|
||||
except Exception as exc:
|
||||
# Do not let Uvicorn print exception values that could contain user data.
|
||||
if response_started:
|
||||
raise
|
||||
logger.error(json.dumps({"event": "internal_error", "type": type(exc).__name__}))
|
||||
response = error_response(
|
||||
Request(scope), 500, "internal_error", "Внутренняя ошибка сервера"
|
||||
)
|
||||
await response(scope, receive, with_id)
|
||||
finally:
|
||||
route = getattr(scope.get("route"), "path", "unmatched")
|
||||
logger.info(
|
||||
json.dumps(
|
||||
{
|
||||
"event": "request",
|
||||
"request_id": request_id,
|
||||
"method": scope["method"],
|
||||
"route": route,
|
||||
"status": status,
|
||||
"duration_ms": round((perf_counter() - start) * 1000, 3),
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def error_response(
|
||||
request: Request, status: int, code: str, message: str, headers: dict | None = None
|
||||
) -> JSONResponse:
|
||||
identity = getattr(request.state, "request_id", str(uuid4()))
|
||||
return JSONResponse(
|
||||
status_code=status,
|
||||
content={"error": {"code": code, "message": message, "request_id": identity}},
|
||||
headers={"X-Request-Id": identity, **(headers or {})},
|
||||
)
|
||||
|
||||
|
||||
def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
settings = settings or Settings.from_env()
|
||||
repository = PostgresRepository(
|
||||
settings.database_url,
|
||||
settings.pool_size,
|
||||
settings.idempotency_ttl,
|
||||
settings.read_autocommit,
|
||||
)
|
||||
cache = SessionCache(settings.cache_url)
|
||||
authentication = AuthService(repository, cache, settings.session_ttl)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
repository.open()
|
||||
app.state.ready = True
|
||||
logger.info(json.dumps({"event": "started", "environment": os.getenv("APP_ENV", "lab")}))
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
app.state.ready = False
|
||||
repository.close()
|
||||
cache.close()
|
||||
logger.info(json.dumps({"event": "stopped"}))
|
||||
|
||||
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
|
||||
app.state.instance_id = uuid4().hex
|
||||
app.add_middleware(RequestContext, instance_id=app.state.instance_id)
|
||||
app.state.messenger = Messenger(repository)
|
||||
app.state.repository = repository
|
||||
app.state.authentication = authentication
|
||||
app.state.cache = cache
|
||||
app.state.ready = False
|
||||
|
||||
@app.exception_handler(DomainError)
|
||||
async def domain_error(request: Request, exc: DomainError):
|
||||
return error_response(request, exc.status, exc.code, exc.message, exc.headers)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error(request: Request, exc: RequestValidationError):
|
||||
return error_response(request, 400, "invalid_request", "Некорректные поля или JSON")
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_error(request: Request, exc: HTTPException):
|
||||
code = "not_found" if exc.status_code == 404 else "invalid_request"
|
||||
return error_response(request, exc.status_code, code, "Некорректный HTTP-запрос")
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unexpected_error(request: Request, exc: Exception):
|
||||
logger.error(json.dumps({"event": "internal_error", "type": type(exc).__name__}))
|
||||
return error_response(request, 500, "internal_error", "Внутренняя ошибка сервера")
|
||||
|
||||
def service(request: Request) -> Messenger:
|
||||
return request.app.state.messenger
|
||||
|
||||
def token_digest(request: Request) -> bytes:
|
||||
if len(request.headers.getlist("authorization")) != 1:
|
||||
raise unauthorized()
|
||||
return bearer_digest(request.headers.get("authorization"))
|
||||
|
||||
def identity(
|
||||
digest: Annotated[bytes, Depends(token_digest)],
|
||||
) -> Identity:
|
||||
return authentication.identify(digest)
|
||||
|
||||
def actor(current: Annotated[Identity, Depends(identity)]) -> User:
|
||||
return current.user
|
||||
|
||||
async def credentials(request: Request) -> tuple[str, str]:
|
||||
if len(request.headers.getlist("authorization")) != 1:
|
||||
raise unauthorized("Basic")
|
||||
result = basic_credentials(request.headers.get("authorization"))
|
||||
if await request.body():
|
||||
raise invalid("Вход не принимает тело запроса")
|
||||
return result
|
||||
|
||||
def resource_id(chat_id: str) -> str:
|
||||
try:
|
||||
return canonical_uuid(chat_id)
|
||||
except ValueError:
|
||||
raise invalid("Некорректный UUID чата") from None
|
||||
|
||||
def pagination(request: Request) -> tuple[int, str | None]:
|
||||
for key in ("limit", "cursor"):
|
||||
if len(request.query_params.getlist(key)) > 1:
|
||||
raise invalid("Параметр пагинации указан несколько раз")
|
||||
raw = request.query_params.get("limit", "50")
|
||||
try:
|
||||
if not re.fullmatch(r"[0-9]+", raw):
|
||||
raise ValueError
|
||||
limit = int(raw)
|
||||
if not 1 <= limit <= 100:
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
raise invalid("limit должен быть целым от 1 до 100") from None
|
||||
return limit, request.query_params.get("cursor")
|
||||
|
||||
def json_input(request: Request):
|
||||
media = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||
if media != "application/json":
|
||||
raise DomainError(415, "unsupported_media_type", "Требуется application/json")
|
||||
|
||||
def message_key(request: Request) -> str:
|
||||
values = request.headers.getlist("idempotency-key")
|
||||
if len(values) != 1 or not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", values[0]):
|
||||
raise invalid("Требуется корректный Idempotency-Key")
|
||||
return values[0]
|
||||
|
||||
CurrentUser = Annotated[User, Depends(actor)]
|
||||
Service = Annotated[Messenger, Depends(service)]
|
||||
ChatId = Annotated[str, Depends(resource_id)]
|
||||
Pagination = Annotated[tuple[int, str | None], Depends(pagination)]
|
||||
|
||||
@app.get("/health/live")
|
||||
def live():
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.get("/health/ready")
|
||||
def ready(request: Request):
|
||||
if not request.app.state.ready:
|
||||
raise DomainError(503, "unavailable", "Приложение не готово")
|
||||
repository.ready()
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.post(
|
||||
"/api/v1/users",
|
||||
status_code=201,
|
||||
response_model=UserView,
|
||||
dependencies=[Depends(json_input)],
|
||||
)
|
||||
def register(body: CreateUser):
|
||||
return authentication.register(body.username, body.display_name, body.password)
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201, response_model=SessionView)
|
||||
def login(value: Annotated[tuple[str, str], Depends(credentials)]):
|
||||
return authentication.login(*value)
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def logout(current: Annotated[Identity, Depends(identity)]):
|
||||
authentication.logout(current)
|
||||
return Response(status_code=204)
|
||||
|
||||
@app.get("/api/v1/users/me", response_model=UserView)
|
||||
def me(current: CurrentUser):
|
||||
return current
|
||||
|
||||
@app.post(
|
||||
"/api/v1/chats",
|
||||
status_code=201,
|
||||
response_model=ChatView,
|
||||
dependencies=[Depends(json_input)],
|
||||
)
|
||||
def create_chat(body: CreateChat, current: CurrentUser, messenger: Service):
|
||||
return messenger.create_chat(current, body.title, body.member_ids)
|
||||
|
||||
@app.get("/api/v1/chats", response_model=ChatPage)
|
||||
def chats(current: CurrentUser, messenger: Service, page: Pagination):
|
||||
return messenger.chats(current, *page)
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}", response_model=ChatView)
|
||||
def chat(current: CurrentUser, chat: ChatId, messenger: Service):
|
||||
return messenger.chat(current, chat)
|
||||
|
||||
@app.post(
|
||||
"/api/v1/chats/{chat_id}/messages",
|
||||
status_code=201,
|
||||
response_model=MessageView,
|
||||
dependencies=[Depends(json_input)],
|
||||
)
|
||||
def send_message(
|
||||
body: CreateMessage,
|
||||
current: CurrentUser,
|
||||
chat: ChatId,
|
||||
messenger: Service,
|
||||
key: Annotated[str, Depends(message_key)],
|
||||
):
|
||||
return messenger.send(current, chat, body.text, key)
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
def messages(current: CurrentUser, chat: ChatId, messenger: Service, page: Pagination):
|
||||
return messenger.messages(current, chat, *page)
|
||||
|
||||
return app
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Argon2id passwords and opaque sessions. Cache hits never authorize a request."""
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import re
|
||||
import secrets
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from threading import BoundedSemaphore
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError
|
||||
from argon2.profiles import RFC_9106_LOW_MEMORY
|
||||
|
||||
from messenger.cache import SessionCache
|
||||
from messenger.domain import DomainError, User
|
||||
from messenger.repository import PostgresRepository
|
||||
|
||||
|
||||
def unauthorized(scheme: str = "Bearer") -> DomainError:
|
||||
challenge = scheme + ' realm="messenger"'
|
||||
if scheme == "Basic":
|
||||
challenge += ', charset="UTF-8"'
|
||||
return DomainError(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Требуется действительная идентификация",
|
||||
{"WWW-Authenticate": challenge},
|
||||
)
|
||||
|
||||
|
||||
def basic_credentials(header: str | None) -> tuple[str, str]:
|
||||
try:
|
||||
if header is None or len(header) > 2048:
|
||||
raise ValueError
|
||||
scheme, encoded = header.split(" ", 1)
|
||||
if scheme.lower() != "basic":
|
||||
raise ValueError
|
||||
raw = base64.b64decode(encoded, validate=True).decode("utf-8")
|
||||
username, password = raw.split(":", 1)
|
||||
if not re.fullmatch(r"[a-z0-9_]{3,32}", username):
|
||||
raise ValueError
|
||||
if not 12 <= len(password) <= 128 or not password.strip():
|
||||
raise ValueError
|
||||
return username, password
|
||||
except ValueError, UnicodeError, binascii.Error:
|
||||
raise unauthorized("Basic") from None
|
||||
|
||||
|
||||
def bearer_digest(header: str | None) -> bytes:
|
||||
if header:
|
||||
parts = header.split(" ")
|
||||
if len(parts) == 2 and parts[0].lower() == "bearer":
|
||||
if re.fullmatch(r"[A-Za-z0-9_-]{43}", parts[1]):
|
||||
return hashlib.sha256(parts[1].encode()).digest()
|
||||
raise unauthorized()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Identity:
|
||||
user: User
|
||||
token_hash: bytes
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Session:
|
||||
token: str
|
||||
token_type: str
|
||||
expires_at: str
|
||||
user: User
|
||||
|
||||
|
||||
class AuthService:
|
||||
def __init__(self, repository: PostgresRepository, cache: SessionCache, ttl: int):
|
||||
self.repository, self.cache, self.ttl = repository, cache, ttl
|
||||
self.hasher = PasswordHasher.from_parameters(RFC_9106_LOW_MEMORY)
|
||||
self.kdf_slots = BoundedSemaphore(2)
|
||||
self.dummy_hash = self.hasher.hash(secrets.token_urlsafe(32))
|
||||
|
||||
@contextmanager
|
||||
def kdf(self):
|
||||
if not self.kdf_slots.acquire(timeout=0.5):
|
||||
raise DomainError(503, "unavailable", "Обработка пароля временно занята")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self.kdf_slots.release()
|
||||
|
||||
def register(self, username: str, display_name: str, password: str) -> User:
|
||||
with self.kdf():
|
||||
encoded = self.hasher.hash(password)
|
||||
return self.repository.add_user(username, display_name, encoded)
|
||||
|
||||
def login(self, username: str, password: str) -> Session:
|
||||
credentials = self.repository.credentials(username)
|
||||
encoded = credentials[1] if credentials else self.dummy_hash
|
||||
try:
|
||||
with self.kdf():
|
||||
self.hasher.verify(encoded, password)
|
||||
except VerificationError, InvalidHashError:
|
||||
raise unauthorized("Basic") from None
|
||||
if credentials is None:
|
||||
raise unauthorized("Basic")
|
||||
token = secrets.token_urlsafe(32)
|
||||
digest = hashlib.sha256(token.encode()).digest()
|
||||
user = credentials[0]
|
||||
expires = self.repository.create_session(digest, user.id, self.ttl)
|
||||
return Session(token, "Bearer", expires, user)
|
||||
|
||||
def identify(self, digest: bytes) -> Identity:
|
||||
session = self.repository.active_session(digest)
|
||||
if session is None:
|
||||
raise unauthorized()
|
||||
user_id = str(session["user_id"])
|
||||
user = self.cache.get(digest, user_id)
|
||||
if user is None:
|
||||
user = self.repository.get_user(user_id)
|
||||
if user is None:
|
||||
raise unauthorized()
|
||||
ttl = int((session["expires_at"] - session["checked_at"]).total_seconds())
|
||||
self.cache.put(digest, user, ttl)
|
||||
return Identity(user, digest)
|
||||
|
||||
def logout(self, identity: Identity):
|
||||
self.repository.revoke_session(identity.token_hash)
|
||||
self.cache.delete(identity.token_hash)
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Disposable session-user cache; PostgreSQL always decides token validity."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from dataclasses import asdict
|
||||
|
||||
from redis import Redis
|
||||
from redis.backoff import NoBackoff
|
||||
from redis.exceptions import RedisError
|
||||
from redis.retry import Retry
|
||||
|
||||
from messenger.domain import User
|
||||
|
||||
logger = logging.getLogger("messenger")
|
||||
|
||||
|
||||
class SessionCache:
|
||||
def __init__(self, url: str):
|
||||
self.client = Redis.from_url(
|
||||
url,
|
||||
socket_connect_timeout=0.2,
|
||||
socket_timeout=0.2,
|
||||
max_connections=8,
|
||||
decode_responses=True,
|
||||
retry_on_timeout=False,
|
||||
retry=Retry(NoBackoff(), 0),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def key(digest: bytes) -> str:
|
||||
return "session-user:" + digest.hex()
|
||||
|
||||
def get(self, digest: bytes, user_id: str) -> User | None:
|
||||
try:
|
||||
raw = self.client.get(self.key(digest))
|
||||
if raw:
|
||||
value = User(**json.loads(raw))
|
||||
if value.id == user_id:
|
||||
return value
|
||||
except RedisError, ValueError, TypeError:
|
||||
logger.warning('{"event":"session_cache_unavailable","operation":"get"}')
|
||||
return None
|
||||
|
||||
def put(self, digest: bytes, user: User, ttl: int):
|
||||
try:
|
||||
self.client.set(self.key(digest), json.dumps(asdict(user)), ex=max(1, ttl))
|
||||
except RedisError:
|
||||
logger.warning('{"event":"session_cache_unavailable","operation":"set"}')
|
||||
|
||||
def delete(self, digest: bytes):
|
||||
try:
|
||||
self.client.delete(self.key(digest))
|
||||
except RedisError:
|
||||
logger.warning('{"event":"session_cache_unavailable","operation":"delete"}')
|
||||
|
||||
def close(self):
|
||||
self.client.close()
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Versioned keyset position, bound to a list and its resource, never an offset."""
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
from datetime import UTC, datetime
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.domain import HistoryKey, invalid
|
||||
|
||||
|
||||
def encode_cursor(scope: str, position: HistoryKey) -> str:
|
||||
value = {"v": 1, "scope": scope, "created_at": position[0], "id": position[1]}
|
||||
return (
|
||||
base64.urlsafe_b64encode(json.dumps(value, separators=(",", ":")).encode())
|
||||
.decode()
|
||||
.rstrip("=")
|
||||
)
|
||||
|
||||
|
||||
def decode_cursor(value: str | None, scope: str) -> HistoryKey | None:
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if not value or len(value) > 1024:
|
||||
raise ValueError
|
||||
raw = base64.b64decode(value + "=" * (-len(value) % 4), altchars=b"-_", validate=True)
|
||||
data = json.loads(raw)
|
||||
if not isinstance(data, dict) or set(data) != {"v", "scope", "created_at", "id"}:
|
||||
raise ValueError
|
||||
if type(data["v"]) is not int or data["v"] != 1 or data["scope"] != scope:
|
||||
raise ValueError
|
||||
if not isinstance(data["created_at"], str) or not data["created_at"].endswith("Z"):
|
||||
raise ValueError
|
||||
stamp = datetime.fromisoformat(data["created_at"])
|
||||
if stamp.tzinfo != UTC or not isinstance(data["id"], str):
|
||||
raise ValueError
|
||||
identity = str(UUID(data["id"]))
|
||||
return stamp.isoformat(timespec="microseconds").replace("+00:00", "Z"), identity
|
||||
except ValueError, TypeError, KeyError, UnicodeError, binascii.Error:
|
||||
raise invalid("Некорректный cursor или другая область пагинации") from None
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Immutable domain values; no dependency on HTTP or a storage technology."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
def utc_now() -> str:
|
||||
return datetime.now(UTC).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def new_id() -> str:
|
||||
return str(uuid4())
|
||||
|
||||
|
||||
class DomainError(Exception):
|
||||
def __init__(self, status: int, code: str, message: str, headers: dict | None = None):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
def invalid(message: str = "Некорректный запрос") -> DomainError:
|
||||
return DomainError(400, "invalid_request", message)
|
||||
|
||||
|
||||
def not_found() -> DomainError:
|
||||
return DomainError(404, "not_found", "Объект не найден")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class User:
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Chat:
|
||||
id: str
|
||||
title: str
|
||||
member_ids: tuple[str, ...]
|
||||
created_at: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Message:
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: str
|
||||
|
||||
|
||||
type HistoryKey = tuple[str, str]
|
||||
|
||||
|
||||
def history_key(item: Chat | Message) -> HistoryKey:
|
||||
return item.created_at, item.id
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Transactional, checksummed migrations, serialized across concurrent starts."""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
|
||||
from messenger.settings import secret
|
||||
|
||||
|
||||
def migrate(conninfo: str, directory: Path):
|
||||
with psycopg.connect(conninfo, connect_timeout=5) as conn:
|
||||
conn.execute("SELECT pg_advisory_xact_lock(2301002)")
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS schema_migrations ("
|
||||
"version text PRIMARY KEY, checksum text NOT NULL, "
|
||||
"applied_at timestamptz NOT NULL DEFAULT clock_timestamp())"
|
||||
)
|
||||
for path in sorted(directory.glob("*.sql")):
|
||||
content = path.read_text()
|
||||
checksum = hashlib.sha256(content.encode()).hexdigest()
|
||||
current = conn.execute(
|
||||
"SELECT checksum FROM schema_migrations WHERE version=%s", (path.stem,)
|
||||
).fetchone()
|
||||
if current:
|
||||
if current[0] != checksum:
|
||||
raise RuntimeError("Applied migration checksum changed: " + path.stem)
|
||||
continue
|
||||
conn.execute(content)
|
||||
conn.execute(
|
||||
"INSERT INTO schema_migrations (version,checksum) VALUES (%s,%s)",
|
||||
(path.stem, checksum),
|
||||
)
|
||||
print("Applied migration " + path.stem)
|
||||
|
||||
|
||||
def main():
|
||||
migrate(
|
||||
secret("DATABASE_URL_FILE", "/run/secrets/database_url"),
|
||||
Path(os.getenv("MIGRATIONS_DIR", "/app/migrations")),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,263 @@
|
||||
"""PostgreSQL adapter: bounded connections, parameterized SQL, commit before return."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from contextlib import contextmanager, nullcontext
|
||||
from datetime import datetime
|
||||
from typing import Protocol
|
||||
|
||||
import psycopg
|
||||
from psycopg import errors
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool, PoolTimeout, TooManyRequests
|
||||
|
||||
from messenger.domain import Chat, DomainError, HistoryKey, Message, User, invalid, new_id
|
||||
|
||||
|
||||
def stamp(value: datetime) -> str:
|
||||
return value.isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def user_value(row) -> User:
|
||||
return User(str(row["id"]), row["username"], row["display_name"], stamp(row["created_at"]))
|
||||
|
||||
|
||||
def chat_value(row) -> Chat:
|
||||
return Chat(
|
||||
str(row["id"]),
|
||||
row["title"],
|
||||
tuple(str(x) for x in row["member_ids"]),
|
||||
stamp(row["created_at"]),
|
||||
)
|
||||
|
||||
|
||||
def message_value(row) -> Message:
|
||||
return Message(
|
||||
str(row["id"]),
|
||||
str(row["chat_id"]),
|
||||
str(row["sender_id"]),
|
||||
row["text"],
|
||||
stamp(row["created_at"]),
|
||||
)
|
||||
|
||||
|
||||
class Repository(Protocol):
|
||||
def get_user(self, user_id: str) -> User | None: ...
|
||||
def add_chat(self, title: str, member_ids: tuple[str, ...]) -> Chat: ...
|
||||
def get_chat(self, chat_id: str) -> Chat | None: ...
|
||||
def page_chats(self, user_id: str, after: HistoryKey | None, limit: int) -> list[Chat]: ...
|
||||
def add_message(self, chat_id: str, sender_id: str, text: str) -> Message: ...
|
||||
def idempotent_message(self, chat_id: str, sender_id: str, text: str, key: str) -> Message: ...
|
||||
def page_messages(
|
||||
self, chat_id: str, after: HistoryKey | None, limit: int
|
||||
) -> list[Message]: ...
|
||||
|
||||
|
||||
CHAT_COLUMNS = """c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY position) AS member_ids"""
|
||||
|
||||
|
||||
class PostgresRepository:
|
||||
def __init__(
|
||||
self,
|
||||
conninfo: str,
|
||||
pool_size: int = 8,
|
||||
idempotency_ttl: int = 86400,
|
||||
read_autocommit: bool = True,
|
||||
):
|
||||
self.read_autocommit = read_autocommit
|
||||
self.idempotency_ttl = idempotency_ttl
|
||||
self.pool = ConnectionPool(
|
||||
conninfo,
|
||||
min_size=1,
|
||||
max_size=pool_size,
|
||||
timeout=1,
|
||||
max_waiting=32,
|
||||
open=False,
|
||||
check=ConnectionPool.check_connection,
|
||||
kwargs={
|
||||
"row_factory": dict_row,
|
||||
"autocommit": True,
|
||||
"connect_timeout": 2,
|
||||
"options": "-c statement_timeout=2500 -c lock_timeout=1000 "
|
||||
"-c idle_in_transaction_session_timeout=5000 -c timezone=UTC",
|
||||
},
|
||||
)
|
||||
|
||||
def open(self):
|
||||
self.pool.open(wait=True, timeout=15)
|
||||
|
||||
def close(self):
|
||||
self.pool.close(timeout=5)
|
||||
|
||||
@contextmanager
|
||||
def connection(self, *, write: bool = False):
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
transaction = (
|
||||
conn.transaction() if write or not self.read_autocommit else nullcontext()
|
||||
)
|
||||
with transaction:
|
||||
yield conn
|
||||
except (
|
||||
psycopg.OperationalError,
|
||||
psycopg.InterfaceError,
|
||||
PoolTimeout,
|
||||
TooManyRequests,
|
||||
errors.QueryCanceled,
|
||||
errors.LockNotAvailable,
|
||||
):
|
||||
raise DomainError(503, "unavailable", "Хранилище временно недоступно") from None
|
||||
|
||||
def ready(self):
|
||||
with self.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT count(*) AS n FROM schema_migrations "
|
||||
"WHERE version IN ('001_initial','002_idempotency')"
|
||||
).fetchone()
|
||||
if row["n"] != 2:
|
||||
raise DomainError(503, "unavailable", "Схема ещё не готова")
|
||||
|
||||
def add_user(self, username: str, display_name: str, password_hash: str) -> User:
|
||||
try:
|
||||
with self.connection(write=True) as conn:
|
||||
row = conn.execute(
|
||||
"INSERT INTO users (id,username,display_name,password_hash) "
|
||||
"VALUES (%s,%s,%s,%s) RETURNING *",
|
||||
(new_id(), username, display_name, password_hash),
|
||||
).fetchone()
|
||||
return user_value(row)
|
||||
except errors.UniqueViolation:
|
||||
raise DomainError(409, "conflict", "Имя пользователя уже занято") from None
|
||||
|
||||
def credentials(self, username: str):
|
||||
with self.connection() as conn:
|
||||
row = conn.execute("SELECT * FROM users WHERE username=%s", (username,)).fetchone()
|
||||
return (user_value(row), row["password_hash"]) if row else None
|
||||
|
||||
def get_user(self, user_id: str) -> User | None:
|
||||
with self.connection() as conn:
|
||||
row = conn.execute("SELECT * FROM users WHERE id=%s", (user_id,)).fetchone()
|
||||
return user_value(row) if row else None
|
||||
|
||||
def add_chat(self, title: str, member_ids: tuple[str, ...]) -> Chat:
|
||||
try:
|
||||
with self.connection(write=True) as conn:
|
||||
row = conn.execute(
|
||||
"INSERT INTO chats (id,title) VALUES (%s,%s) RETURNING *", (new_id(), title)
|
||||
).fetchone()
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany(
|
||||
"INSERT INTO chat_members (chat_id,user_id,position) VALUES (%s,%s,%s)",
|
||||
[(row["id"], member, i) for i, member in enumerate(member_ids)],
|
||||
)
|
||||
return Chat(str(row["id"]), title, member_ids, stamp(row["created_at"]))
|
||||
except errors.ForeignKeyViolation:
|
||||
raise invalid("Указан неизвестный участник") from None
|
||||
|
||||
def get_chat(self, chat_id: str) -> Chat | None:
|
||||
with self.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT " + CHAT_COLUMNS + " FROM chats c WHERE c.id=%s", (chat_id,)
|
||||
).fetchone()
|
||||
return chat_value(row) if row else None
|
||||
|
||||
def page_chats(self, user_id: str, after: HistoryKey | None, limit: int) -> list[Chat]:
|
||||
condition = " AND (c.created_at,c.id) > (%s::timestamptz,%s::uuid)" if after else ""
|
||||
params = (user_id, *after, limit) if after else (user_id, limit)
|
||||
with self.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT " + CHAT_COLUMNS + " FROM chats c WHERE EXISTS "
|
||||
"(SELECT 1 FROM chat_members m WHERE m.chat_id=c.id AND m.user_id=%s)"
|
||||
+ condition
|
||||
+ " ORDER BY c.created_at,c.id LIMIT %s",
|
||||
params,
|
||||
).fetchall()
|
||||
return [chat_value(row) for row in rows]
|
||||
|
||||
def add_message(self, chat_id: str, sender_id: str, text: str) -> Message:
|
||||
with self.connection(write=True) as conn:
|
||||
row = conn.execute(
|
||||
"INSERT INTO messages (id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *",
|
||||
(new_id(), chat_id, sender_id, text),
|
||||
).fetchone()
|
||||
return message_value(row)
|
||||
|
||||
def page_messages(self, chat_id: str, after: HistoryKey | None, limit: int) -> list[Message]:
|
||||
condition = " AND (created_at,id) > (%s::timestamptz,%s::uuid)" if after else ""
|
||||
params = (chat_id, *after, limit) if after else (chat_id, limit)
|
||||
with self.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM messages WHERE chat_id=%s"
|
||||
+ condition
|
||||
+ " ORDER BY created_at,id LIMIT %s",
|
||||
params,
|
||||
).fetchall()
|
||||
return [message_value(row) for row in rows]
|
||||
|
||||
def idempotent_message(self, chat_id: str, sender_id: str, text: str, key: str) -> Message:
|
||||
scope = json.dumps([sender_id, "POST", chat_id, key], separators=(",", ":"))
|
||||
lock = int.from_bytes(hashlib.sha256(scope.encode()).digest()[:8], "big", signed=True)
|
||||
payload = json.dumps(
|
||||
{"text": text, "attachment_ids": []},
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
ensure_ascii=False,
|
||||
)
|
||||
digest = hashlib.sha256(payload.encode()).digest()
|
||||
with self.connection(write=True) as conn:
|
||||
conn.execute("SELECT pg_advisory_xact_lock(%s)", (lock,))
|
||||
previous = conn.execute(
|
||||
"SELECT r.payload_hash,m.* FROM message_requests r "
|
||||
"JOIN messages m ON m.id=r.response_message_id "
|
||||
"WHERE r.user_id=%s AND r.http_method='POST' AND r.chat_id=%s "
|
||||
"AND r.idempotency_key=%s AND r.expires_at > clock_timestamp()",
|
||||
(sender_id, chat_id, key),
|
||||
).fetchone()
|
||||
if previous:
|
||||
if previous["payload_hash"] != digest:
|
||||
raise DomainError(409, "conflict", "Ключ уже использован с другим сообщением")
|
||||
return message_value(previous)
|
||||
conn.execute(
|
||||
"DELETE FROM message_requests WHERE user_id=%s AND http_method='POST' "
|
||||
"AND chat_id=%s AND idempotency_key=%s",
|
||||
(sender_id, chat_id, key),
|
||||
)
|
||||
message = message_value(
|
||||
conn.execute(
|
||||
"INSERT INTO messages (id,chat_id,sender_id,text) "
|
||||
"VALUES (%s,%s,%s,%s) RETURNING *",
|
||||
(new_id(), chat_id, sender_id, text),
|
||||
).fetchone()
|
||||
)
|
||||
self._save_request(conn, sender_id, chat_id, key, digest, message.id)
|
||||
return message
|
||||
|
||||
def _save_request(self, conn, user_id, chat_id, key, digest, message_id):
|
||||
conn.execute(
|
||||
"INSERT INTO message_requests "
|
||||
"(user_id,chat_id,idempotency_key,payload_hash,response_message_id,expires_at) "
|
||||
"VALUES (%s,%s,%s,%s,%s,clock_timestamp()+make_interval(secs => %s))",
|
||||
(user_id, chat_id, key, digest, message_id, self.idempotency_ttl),
|
||||
)
|
||||
|
||||
def create_session(self, token_hash: bytes, user_id: str, ttl: int) -> str:
|
||||
with self.connection(write=True) as conn:
|
||||
row = conn.execute(
|
||||
"INSERT INTO sessions (token_hash,user_id,expires_at) "
|
||||
"VALUES (%s,%s,clock_timestamp() + make_interval(secs => %s)) RETURNING expires_at",
|
||||
(token_hash, user_id, ttl),
|
||||
).fetchone()
|
||||
return stamp(row["expires_at"])
|
||||
|
||||
def active_session(self, token_hash: bytes):
|
||||
with self.connection() as conn:
|
||||
return conn.execute(
|
||||
"SELECT user_id,expires_at,clock_timestamp() AS checked_at FROM sessions "
|
||||
"WHERE token_hash=%s AND expires_at > clock_timestamp()",
|
||||
(token_hash,),
|
||||
).fetchone()
|
||||
|
||||
def revoke_session(self, token_hash: bytes):
|
||||
with self.connection(write=True) as conn:
|
||||
conn.execute("DELETE FROM sessions WHERE token_hash=%s", (token_hash,))
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Strict lab 2 wire types; password never belongs to a response User."""
|
||||
|
||||
import re
|
||||
from typing import Annotated
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import AfterValidator, BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
def canonical_uuid(value: str) -> str:
|
||||
if not re.fullmatch(r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", value):
|
||||
raise ValueError("Ожидается UUID")
|
||||
return str(UUID(value))
|
||||
|
||||
|
||||
def nonblank(value: str) -> str:
|
||||
if not value.strip() or any(0xD800 <= ord(char) <= 0xDFFF for char in value):
|
||||
raise ValueError("Ожидается непустая строка Unicode")
|
||||
return value
|
||||
|
||||
|
||||
type Identifier = Annotated[str, AfterValidator(canonical_uuid)]
|
||||
type ShortText = Annotated[str, Field(min_length=1, max_length=100), AfterValidator(nonblank)]
|
||||
|
||||
|
||||
class Input(BaseModel):
|
||||
model_config = ConfigDict(strict=True, extra="forbid")
|
||||
|
||||
|
||||
class CreateUser(Input):
|
||||
username: str = Field(min_length=3, max_length=32)
|
||||
display_name: ShortText
|
||||
password: Annotated[str, Field(min_length=12, max_length=128), AfterValidator(nonblank)]
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def valid_username(cls, value: str) -> str:
|
||||
if not re.fullmatch(r"[a-z0-9_]{3,32}", value):
|
||||
raise ValueError("Недопустимое имя пользователя")
|
||||
return value
|
||||
|
||||
|
||||
class CreateChat(Input):
|
||||
title: ShortText
|
||||
member_ids: list[Identifier] = Field(min_length=1, max_length=100)
|
||||
|
||||
|
||||
class CreateMessage(Input):
|
||||
text: Annotated[str, Field(min_length=1, max_length=4000), AfterValidator(nonblank)]
|
||||
|
||||
|
||||
class View(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True, extra="forbid")
|
||||
|
||||
|
||||
class UserView(View):
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class SessionView(View):
|
||||
token: str
|
||||
token_type: str
|
||||
expires_at: str
|
||||
user: UserView
|
||||
|
||||
|
||||
class ChatView(View):
|
||||
id: str
|
||||
title: str
|
||||
member_ids: list[str]
|
||||
created_at: str
|
||||
|
||||
|
||||
class MessageView(View):
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class ChatPage(View):
|
||||
items: list[ChatView]
|
||||
next_cursor: str | None
|
||||
|
||||
|
||||
class MessagePage(View):
|
||||
items: list[MessageView]
|
||||
next_cursor: str | None
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Use cases shared by HTTP and tests. Authorization precedes resource access."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from messenger.cursor import decode_cursor, encode_cursor
|
||||
from messenger.domain import Chat, Message, User, history_key, invalid, not_found
|
||||
from messenger.repository import Repository
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Page[T]:
|
||||
items: list[T]
|
||||
next_cursor: str | None
|
||||
|
||||
|
||||
class Messenger:
|
||||
def __init__(self, repository: Repository):
|
||||
self.repository = repository
|
||||
|
||||
def create_chat(self, actor: User, title: str, member_ids: list[str]) -> Chat:
|
||||
if len(member_ids) != len(set(member_ids)) or actor.id not in member_ids:
|
||||
raise invalid("Участники не должны повторяться; вызывающий должен входить в чат")
|
||||
return self.repository.add_chat(title, tuple(member_ids))
|
||||
|
||||
def chat(self, actor: User, chat_id: str) -> Chat:
|
||||
chat = self.repository.get_chat(chat_id)
|
||||
if chat is None or actor.id not in chat.member_ids:
|
||||
raise not_found()
|
||||
return chat
|
||||
|
||||
def chats(self, actor: User, limit: int, cursor: str | None) -> Page[Chat]:
|
||||
scope = "chats:" + actor.id
|
||||
after = decode_cursor(cursor, scope)
|
||||
return self._page(self.repository.page_chats(actor.id, after, limit + 1), limit, scope)
|
||||
|
||||
def send(self, actor: User, chat_id: str, text: str, key: str) -> Message:
|
||||
self.chat(actor, chat_id)
|
||||
return self.repository.idempotent_message(chat_id, actor.id, text, key)
|
||||
|
||||
def messages(self, actor: User, chat_id: str, limit: int, cursor: str | None) -> Page[Message]:
|
||||
self.chat(actor, chat_id)
|
||||
scope = "messages:" + chat_id
|
||||
after = decode_cursor(cursor, scope)
|
||||
return self._page(self.repository.page_messages(chat_id, after, limit + 1), limit, scope)
|
||||
|
||||
@staticmethod
|
||||
def _page[T: Chat | Message](items: list[T], limit: int, scope: str) -> Page[T]:
|
||||
visible = items[:limit]
|
||||
cursor = encode_cursor(scope, history_key(visible[-1])) if len(items) > limit else None
|
||||
return Page(visible, cursor)
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Explicit configuration; credentials are read from untracked secret files."""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def secret(name: str, default: str) -> str:
|
||||
return Path(os.getenv(name, default)).read_text().strip()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
database_url: str = field(repr=False)
|
||||
cache_url: str = field(repr=False)
|
||||
session_ttl: int = 3600
|
||||
pool_size: int = 8
|
||||
idempotency_ttl: int = 86400
|
||||
read_autocommit: bool = True
|
||||
|
||||
@classmethod
|
||||
def from_env(cls):
|
||||
ttl = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
size = int(os.getenv("DATABASE_POOL_SIZE", "8"))
|
||||
idempotency_ttl = int(os.getenv("IDEMPOTENCY_TTL_SECONDS", "86400"))
|
||||
if idempotency_ttl < 86400:
|
||||
raise ValueError("Idempotency retention must be at least 24 hours")
|
||||
if not 1 <= ttl <= 2_592_000 or not 1 <= size <= 32:
|
||||
raise ValueError("Invalid session lifetime or connection pool size")
|
||||
return cls(
|
||||
secret("DATABASE_URL_FILE", "/run/secrets/database_url"),
|
||||
secret("CACHE_URL_FILE", "/run/secrets/cache_url"),
|
||||
ttl,
|
||||
size,
|
||||
idempotency_ttl,
|
||||
os.getenv("DATABASE_READ_AUTOCOMMIT", "1") == "1",
|
||||
)
|
||||
Reference in New Issue
Block a user