Реализовать lab3 на оценку 4: HAProxy, реплики API и общая идемпотентность.

This commit is contained in:
2026-10-30 15:27:54 +03:00
parent 0ab3a341aa
commit 5946fe214c
47 changed files with 3035 additions and 31 deletions
+3
View File
@@ -0,0 +1,3 @@
"""Messenger API for lab3 (LB + shared sessions + idempotent messages)."""
__version__ = "3.0.0"
+30
View File
@@ -0,0 +1,30 @@
"""Run the messenger HTTP server."""
from __future__ import annotations
import sys
from pathlib import Path
_SRC = Path(__file__).resolve().parents[1]
if str(_SRC) not in sys.path:
sys.path.insert(0, str(_SRC))
import uvicorn
from messenger import config
def main() -> None:
uvicorn.run(
"messenger.app:app",
host=config.app_host(),
port=config.app_port(),
log_level="info",
access_log=False,
timeout_keep_alive=5,
timeout_graceful_shutdown=8,
)
if __name__ == "__main__":
main()
+666
View File
@@ -0,0 +1,666 @@
"""HTTP API: multi-replica messenger behind LB (lab3)."""
from __future__ import annotations
import asyncio
import base64
import json
import logging
import re
import signal
import uuid
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from typing import Any, List, Optional, Tuple
from fastapi import FastAPI, Header, Query, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from starlette.exceptions import HTTPException as StarletteHTTPException
from messenger import config, db, sessions
from messenger.sessions import SessionStoreError
from messenger.store import Store, StoreUnavailable, format_ts
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}\Z")
UUID_RE = re.compile(
r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\Z"
)
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}\Z")
BODY_READ_TIMEOUT_S = 5.0
PASSWORD_MIN = 12
PASSWORD_MAX = 128
store = Store()
ready = False
INSTANCE_ID = config.instance_id()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
log = logging.getLogger("messenger")
def mark_not_ready(*_args):
global ready
if ready:
ready = False
log.info("readiness disabled; draining in-flight requests")
def _chain_signal(previous):
def handler(signum, frame):
mark_not_ready()
if callable(previous) and previous not in (signal.SIG_DFL, signal.SIG_IGN):
previous(signum, frame)
return handler
@asynccontextmanager
async def lifespan(_app: FastAPI):
try:
signal.signal(signal.SIGTERM, _chain_signal(signal.getsignal(signal.SIGTERM)))
signal.signal(signal.SIGINT, _chain_signal(signal.getsignal(signal.SIGINT)))
except (ValueError, OSError) as exc:
log.warning("signal handlers not installed: %s", exc)
global ready
db.init_pool()
# Migrations run once via `python -m messenger.migrate` (compose migrate service).
sessions.init_client()
ready = True
log.info("messenger started instance_id=%s", INSTANCE_ID)
yield
mark_not_ready()
sessions.close_client()
db.close_pool()
log.info("messenger stopped")
def request_id_from(request: Request) -> str:
incoming = request.headers.get("x-request-id")
if incoming and incoming.strip():
return incoming.strip()[:128]
return str(uuid.uuid4())
def error_body(code: str, message: str, request_id: str) -> dict:
return {"error": {"code": code, "message": message, "request_id": request_id}}
def common_headers(request_id: str, extra: Optional[dict] = None) -> dict:
headers = {"X-Request-Id": request_id, "X-Instance-Id": INSTANCE_ID}
if extra:
headers.update(extra)
return headers
def error_response(
status: int,
code: str,
message: str,
request_id: str,
www_authenticate: Optional[str] = None,
) -> JSONResponse:
headers = common_headers(request_id)
if www_authenticate:
headers["WWW-Authenticate"] = www_authenticate
return JSONResponse(
status_code=status,
content=error_body(code, message, request_id),
headers=headers,
)
def is_blank(value: str) -> bool:
return value.strip() == ""
def has_nul(value: str) -> bool:
# PostgreSQL text cannot store U+0000; reject explicitly (400), never 500/503.
return "\x00" in value
def has_lone_surrogate(value: str) -> bool:
return any(0xD800 <= ord(ch) <= 0xDFFF for ch in value)
def codepoint_len(value: str) -> int:
return len(value)
def parse_uuid(value: str) -> Optional[str]:
if not isinstance(value, str) or not UUID_RE.match(value):
return None
try:
return str(uuid.UUID(value))
except ValueError:
return None
def encode_cursor(resource: str, created_at: datetime, item_id: str) -> str:
raw = f"{resource}|{created_at.strftime('%Y-%m-%dT%H:%M:%SZ')}|{item_id}"
return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii")
def decode_cursor(cursor: str, expected_resource: str) -> Tuple[datetime, uuid.UUID]:
try:
raw = base64.urlsafe_b64decode(cursor.encode("ascii")).decode("utf-8")
resource, ts, item_id = raw.split("|", 2)
if resource != expected_resource:
raise ValueError("wrong resource")
created_at = datetime.strptime(ts, "%Y-%m-%dT%H:%M:%SZ").replace(
tzinfo=timezone.utc
)
return created_at, uuid.UUID(item_id)
except Exception as exc:
raise ValueError("invalid cursor") from exc
app = FastAPI(
title="MTUSI Messenger lab3",
docs_url=None,
redoc_url=None,
lifespan=lifespan,
)
@app.middleware("http")
async def add_request_id_and_gate(request: Request, call_next):
rid = request_id_from(request)
request.state.request_id = rid
path = request.url.path
if not ready and path not in ("/health/live",):
if path == "/health/ready":
return error_response(503, "unavailable", "Shutting down", rid)
return error_response(503, "unavailable", "Service unavailable", rid)
response = await call_next(request)
if "X-Request-Id" not in response.headers:
response.headers["X-Request-Id"] = rid
response.headers["X-Instance-Id"] = INSTANCE_ID
log.info(
"%s %s -> %s request_id=%s instance_id=%s",
request.method,
path,
response.status_code,
rid,
INSTANCE_ID,
)
return response
class ApiError(Exception):
def __init__(
self,
status: int,
code: str,
message: str,
www_authenticate: Optional[str] = None,
):
self.status = status
self.code = code
self.message = message
self.www_authenticate = www_authenticate
@app.exception_handler(ApiError)
async def api_error_handler(request: Request, exc: ApiError):
rid = getattr(request.state, "request_id", None) or request_id_from(request)
return error_response(
exc.status, exc.code, exc.message, rid, www_authenticate=exc.www_authenticate
)
@app.exception_handler(RequestValidationError)
async def validation_handler(request: Request, exc: RequestValidationError):
rid = getattr(request.state, "request_id", None) or request_id_from(request)
return error_response(400, "invalid_request", "Invalid request", rid)
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
rid = getattr(request.state, "request_id", None) or request_id_from(request)
if exc.status_code == 404:
return error_response(404, "not_found", "Not found", rid)
if exc.status_code == 405:
return error_response(400, "invalid_request", "Method not allowed", rid)
return error_response(exc.status_code, "invalid_request", "Request failed", rid)
@app.exception_handler(StoreUnavailable)
async def store_unavailable_handler(request: Request, exc: StoreUnavailable):
rid = getattr(request.state, "request_id", None) or request_id_from(request)
return error_response(503, "unavailable", "Database unavailable", rid)
@app.exception_handler(SessionStoreError)
async def session_store_unavailable_handler(request: Request, exc: SessionStoreError):
rid = getattr(request.state, "request_id", None) or request_id_from(request)
return error_response(503, "unavailable", "Session store unavailable", rid)
@app.exception_handler(Exception)
async def unhandled_handler(request: Request, exc: Exception):
rid = getattr(request.state, "request_id", None) or request_id_from(request)
log.exception("unhandled error request_id=%s", rid)
return error_response(500, "internal_error", "Internal error", rid)
async def read_json_object(request: Request) -> Any:
content_type = request.headers.get("content-type", "")
media = content_type.split(";")[0].strip().lower()
if media and media != "application/json":
raise ApiError(415, "unsupported_media_type", "Unsupported media type")
try:
body = await asyncio.wait_for(request.body(), timeout=BODY_READ_TIMEOUT_S)
except asyncio.TimeoutError:
raise ApiError(400, "invalid_request", "Request body timeout")
if not body:
raise ApiError(400, "invalid_request", "Empty body")
try:
text = body.decode("utf-8")
# Reject trailing garbage after one JSON value (read to EOF).
data, end = json.JSONDecoder().raw_decode(text)
if text[end:].strip():
raise ApiError(400, "invalid_request", "Malformed JSON")
except ApiError:
raise
except (UnicodeDecodeError, json.JSONDecodeError, ValueError):
raise ApiError(400, "invalid_request", "Malformed JSON")
if not isinstance(data, dict):
raise ApiError(400, "invalid_request", "JSON object required")
return data
def require_bearer(authorization: Optional[str]) -> Tuple[str, str]:
"""Return (user_id, token). X-User-Id is ignored."""
bearer_challenge = 'Bearer realm="messenger"'
if not authorization or not authorization.strip():
raise ApiError(
401, "unauthorized", "Missing bearer token", www_authenticate=bearer_challenge
)
parts = authorization.strip().split(None, 1)
if len(parts) != 2 or parts[0].lower() != "bearer" or not parts[1].strip():
# Basic on business endpoints must not work.
raise ApiError(
401, "unauthorized", "Invalid authorization", www_authenticate=bearer_challenge
)
token = parts[1].strip()
try:
session = sessions.get_session(token)
except SessionStoreError:
raise ApiError(503, "unavailable", "Session store unavailable")
if session is None:
raise ApiError(
401, "unauthorized", "Invalid or expired session", www_authenticate=bearer_challenge
)
user_id = session["user_id"]
user = store.get_user(user_id)
if user is None:
raise ApiError(
401, "unauthorized", "Invalid or expired session", www_authenticate=bearer_challenge
)
return user_id, token
def require_chat_member(chat_id_raw: str, user_id: str):
chat_id = parse_uuid(chat_id_raw)
if chat_id is None:
raise ApiError(400, "invalid_request", "Invalid chat_id")
chat = store.get_chat(chat_id)
if chat is None or user_id not in chat.member_ids:
raise ApiError(404, "not_found", "Chat not found")
return chat
def parse_limit(limit: Optional[int]) -> int:
if limit is None:
return 50
if not isinstance(limit, int) or isinstance(limit, bool) or limit < 1 or limit > 100:
raise ApiError(400, "invalid_request", "Invalid limit")
return limit
def validate_display_text(value: Any, field: str, max_len: int) -> str:
if not isinstance(value, str) or is_blank(value) or has_nul(value):
raise ApiError(400, "invalid_request", f"Invalid {field}")
if has_lone_surrogate(value):
raise ApiError(400, "invalid_request", f"Invalid {field}")
length = codepoint_len(value)
if length < 1 or length > max_len:
raise ApiError(400, "invalid_request", f"Invalid {field}")
return value
def validate_password(value: Any) -> str:
# Required strings must not be whitespace-only (contracts/README).
if not isinstance(value, str) or is_blank(value) or has_nul(value):
raise ApiError(400, "invalid_request", "Invalid password")
if has_lone_surrogate(value):
raise ApiError(400, "invalid_request", "Invalid password")
length = codepoint_len(value)
if length < PASSWORD_MIN or length > PASSWORD_MAX:
raise ApiError(400, "invalid_request", "Invalid password")
return value
def parse_basic_credentials(authorization: Optional[str]) -> Tuple[str, str]:
challenge = 'Basic realm="messenger", charset="UTF-8"'
if not authorization or not authorization.strip():
raise ApiError(
401, "unauthorized", "Invalid credentials", www_authenticate=challenge
)
parts = authorization.strip().split(None, 1)
if len(parts) != 2 or parts[0].lower() != "basic":
raise ApiError(
401, "unauthorized", "Invalid credentials", www_authenticate=challenge
)
try:
decoded = base64.b64decode(parts[1].strip(), validate=True).decode("utf-8")
except Exception:
raise ApiError(
401, "unauthorized", "Invalid credentials", www_authenticate=challenge
)
if ":" not in decoded:
raise ApiError(
401, "unauthorized", "Invalid credentials", www_authenticate=challenge
)
username, password = decoded.split(":", 1)
# Username ASCII-only per contract; password may contain ':'.
if not username or any(ord(ch) > 127 for ch in username):
raise ApiError(
401, "unauthorized", "Invalid credentials", www_authenticate=challenge
)
return username, password
@app.get("/health/live")
async def liveness(request: Request):
rid = request.state.request_id
return JSONResponse(content={"status": "ok"}, headers=common_headers(rid))
@app.get("/health/ready")
async def readiness(request: Request):
rid = request.state.request_id
if not ready:
return error_response(503, "unavailable", "Not ready", rid)
if not db.ping() or not sessions.ping():
return error_response(503, "unavailable", "Dependency unavailable", rid)
return JSONResponse(content={"status": "ok"}, headers=common_headers(rid))
@app.post("/api/v1/users")
async def register_user(request: Request):
rid = request.state.request_id
data = await read_json_object(request)
allowed = {"username", "display_name", "password"}
if set(data.keys()) - allowed:
raise ApiError(400, "invalid_request", "Unexpected fields")
if "username" not in data or "display_name" not in data or "password" not in data:
raise ApiError(400, "invalid_request", "Missing required fields")
username = data["username"]
display_name = data["display_name"]
if (
not isinstance(username, str)
or is_blank(username)
or has_lone_surrogate(username)
or not USERNAME_RE.match(username)
):
raise ApiError(400, "invalid_request", "Invalid username")
display_name = validate_display_text(display_name, "display_name", 100)
password = validate_password(data["password"])
try:
user = store.create_user(username, display_name, password)
except KeyError:
raise ApiError(409, "conflict", "Username already taken")
return JSONResponse(
status_code=201,
content=user.to_dict(),
headers=common_headers(rid),
)
@app.post("/api/v1/auth/sessions")
async def create_session(request: Request):
rid = request.state.request_id
challenge = 'Basic realm="messenger", charset="UTF-8"'
# Contract: Basic only, no JSON body (even with valid credentials).
try:
raw_body = await asyncio.wait_for(request.body(), timeout=BODY_READ_TIMEOUT_S)
except asyncio.TimeoutError:
raise ApiError(400, "invalid_request", "Request body timeout")
if raw_body and raw_body.strip():
raise ApiError(400, "invalid_request", "Login must not include a body")
username, password = parse_basic_credentials(
request.headers.get("authorization")
)
# Uniform 401 for wrong user / wrong password (no user enumeration).
user = store.get_user_by_username(username)
if user is None or not store.verify_password(user.password_hash, password):
raise ApiError(
401, "unauthorized", "Invalid credentials", www_authenticate=challenge
)
try:
session = sessions.create_session(user.id)
except SessionStoreError:
raise ApiError(503, "unavailable", "Session store unavailable")
body = {
"token": session["token"],
"token_type": "Bearer",
"expires_at": session["expires_at"],
"user": user.to_dict(),
}
return JSONResponse(
status_code=201, content=body, headers=common_headers(rid)
)
@app.delete("/api/v1/auth/sessions/current")
async def logout(
request: Request,
authorization: Optional[str] = Header(default=None, alias="Authorization"),
):
rid = request.state.request_id
_user_id, token = require_bearer(authorization)
try:
sessions.revoke_session(token)
except SessionStoreError:
raise ApiError(503, "unavailable", "Session store unavailable")
return Response(status_code=204, headers=common_headers(rid))
@app.get("/api/v1/users/me")
async def current_user(
request: Request,
authorization: Optional[str] = Header(default=None, alias="Authorization"),
):
rid = request.state.request_id
user_id, _token = require_bearer(authorization)
user = store.get_user(user_id)
assert user is not None
return JSONResponse(content=user.to_dict(), headers=common_headers(rid))
@app.post("/api/v1/chats")
async def create_chat(
request: Request,
authorization: Optional[str] = Header(default=None, alias="Authorization"),
):
rid = request.state.request_id
user_id, _token = require_bearer(authorization)
data = await read_json_object(request)
allowed = {"title", "member_ids"}
if set(data.keys()) - allowed:
raise ApiError(400, "invalid_request", "Unexpected fields")
if "title" not in data or "member_ids" not in data:
raise ApiError(400, "invalid_request", "Missing required fields")
title = validate_display_text(data["title"], "title", 100)
member_ids = data["member_ids"]
if not isinstance(member_ids, list) or not member_ids or len(member_ids) > 100:
raise ApiError(400, "invalid_request", "Invalid member_ids")
parsed: List[str] = []
seen = set()
for mid in member_ids:
if not isinstance(mid, str):
raise ApiError(400, "invalid_request", "Invalid member_ids")
uid = parse_uuid(mid)
if uid is None:
raise ApiError(400, "invalid_request", "Invalid member_ids")
if uid in seen:
raise ApiError(400, "invalid_request", "Duplicate member_ids")
seen.add(uid)
parsed.append(uid)
if user_id not in seen:
raise ApiError(400, "invalid_request", "Caller must be a member")
try:
chat = store.create_chat(title, parsed)
except KeyError:
raise ApiError(400, "invalid_request", "Unknown member")
return JSONResponse(
status_code=201,
content=chat.to_dict(),
headers=common_headers(rid),
)
@app.get("/api/v1/chats")
async def list_chats(
request: Request,
authorization: Optional[str] = Header(default=None, alias="Authorization"),
limit: Optional[int] = Query(default=None),
cursor: Optional[str] = Query(default=None),
):
rid = request.state.request_id
user_id, _token = require_bearer(authorization)
lim = parse_limit(limit)
resource = f"chats:{user_id}"
cursor_key = None
if cursor is not None:
if not cursor:
raise ApiError(400, "invalid_request", "Invalid cursor")
try:
cursor_ts, cursor_id = decode_cursor(cursor, resource)
except ValueError:
raise ApiError(400, "invalid_request", "Invalid cursor")
if not store.chat_exists_for_user(user_id, cursor_ts, cursor_id):
raise ApiError(400, "invalid_request", "Invalid cursor")
cursor_key = (cursor_ts, cursor_id)
chats, more = store.list_chats_for_user(user_id, lim, cursor_key)
next_cursor = None
if more and chats:
last = chats[-1]
next_cursor = encode_cursor(resource, last.created_at, last.id)
return JSONResponse(
content={"items": [c.to_dict() for c in chats], "next_cursor": next_cursor},
headers=common_headers(rid),
)
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(
chat_id: str,
request: Request,
authorization: Optional[str] = Header(default=None, alias="Authorization"),
):
rid = request.state.request_id
user_id, _token = require_bearer(authorization)
chat = require_chat_member(chat_id, user_id)
return JSONResponse(content=chat.to_dict(), headers=common_headers(rid))
def parse_idempotency_key(raw: Optional[str]) -> str:
if raw is None or not raw.strip() or not IDEMPOTENCY_KEY_RE.match(raw.strip()):
raise ApiError(400, "invalid_request", "Invalid or missing Idempotency-Key")
return raw.strip()
@app.post("/api/v1/chats/{chat_id}/messages")
async def create_message(
chat_id: str,
request: Request,
authorization: Optional[str] = Header(default=None, alias="Authorization"),
idempotency_key: Optional[str] = Header(default=None, alias="Idempotency-Key"),
):
rid = request.state.request_id
user_id, _token = require_bearer(authorization)
chat = require_chat_member(chat_id, user_id)
key = parse_idempotency_key(idempotency_key)
data = await read_json_object(request)
# Contract: absent attachment_ids ≡ []; lab3 has no uploads, so only [] is accepted.
allowed = {"text", "attachment_ids"}
if set(data.keys()) - allowed:
raise ApiError(400, "invalid_request", "Unexpected fields")
if "text" not in data:
raise ApiError(400, "invalid_request", "Missing text")
if "attachment_ids" in data:
aids = data["attachment_ids"]
if not isinstance(aids, list) or aids:
raise ApiError(400, "invalid_request", "Invalid attachment_ids")
text = data["text"]
if (
not isinstance(text, str)
or is_blank(text)
or has_nul(text)
or has_lone_surrogate(text)
or codepoint_len(text) > 4000
):
raise ApiError(400, "invalid_request", "Invalid text")
path = f"/api/v1/chats/{chat.id}/messages"
try:
message, _replayed = store.create_message_idempotent(
chat.id, user_id, text, "POST", path, key
)
except KeyError:
raise ApiError(409, "conflict", "Idempotency-Key reused with different body")
except ValueError:
raise ApiError(400, "invalid_request", "Invalid text")
return JSONResponse(
status_code=201,
content=message.to_dict(),
headers=common_headers(rid),
)
@app.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(
chat_id: str,
request: Request,
authorization: Optional[str] = Header(default=None, alias="Authorization"),
limit: Optional[int] = Query(default=None),
cursor: Optional[str] = Query(default=None),
):
rid = request.state.request_id
user_id, _token = require_bearer(authorization)
chat = require_chat_member(chat_id, user_id)
lim = parse_limit(limit)
resource = f"messages:{chat.id}"
cursor_key = None
if cursor is not None:
if not cursor:
raise ApiError(400, "invalid_request", "Invalid cursor")
try:
cursor_ts, cursor_id = decode_cursor(cursor, resource)
except ValueError:
raise ApiError(400, "invalid_request", "Invalid cursor")
if not store.message_exists(chat.id, cursor_ts, cursor_id):
raise ApiError(400, "invalid_request", "Invalid cursor")
cursor_key = (cursor_ts, cursor_id)
messages, has_more = store.list_messages(chat.id, lim, cursor_key)
next_cursor = None
if has_more and messages:
last = messages[-1]
next_cursor = encode_cursor(resource, last.created_at, last.id)
return JSONResponse(
content={
"items": [m.to_dict() for m in messages],
"next_cursor": next_cursor,
},
headers=common_headers(rid),
)
def create_app() -> FastAPI:
return app
+83
View File
@@ -0,0 +1,83 @@
"""Runtime configuration from environment / secret files."""
from __future__ import annotations
import os
import socket
from pathlib import Path
def _read_secret(env_key: str, file_key: str, default: str | None = None) -> str:
file_path = os.environ.get(file_key, "").strip()
if file_path:
path = Path(file_path)
if path.is_file():
return path.read_text(encoding="utf-8").strip()
value = os.environ.get(env_key, "").strip()
if value:
return value
if default is not None:
return default
raise RuntimeError(f"Missing secret: set {env_key} or {file_key}")
def database_url() -> str:
return _read_secret("DATABASE_URL", "DATABASE_URL_FILE")
def cache_url() -> str:
return _read_secret("CACHE_URL", "CACHE_URL_FILE")
def session_ttl_seconds() -> int:
raw = os.environ.get("SESSION_TTL_SECONDS", "3600").strip()
try:
value = int(raw)
except ValueError as exc:
raise RuntimeError("SESSION_TTL_SECONDS must be an integer") from exc
if value < 1:
raise RuntimeError("SESSION_TTL_SECONDS must be >= 1")
return value
def idempotency_ttl_seconds() -> int:
raw = os.environ.get("IDEMPOTENCY_TTL_SECONDS", "86400").strip()
try:
value = int(raw)
except ValueError as exc:
raise RuntimeError("IDEMPOTENCY_TTL_SECONDS must be an integer") from exc
if value < 1:
raise RuntimeError("IDEMPOTENCY_TTL_SECONDS must be >= 1")
return value
def instance_id() -> str:
"""Stable for process lifetime; used as X-Instance-Id (maps to container hostname)."""
override = os.environ.get("INSTANCE_ID", "").strip()
if override:
return override[:128]
return socket.gethostname()[:128]
def app_host() -> str:
return os.environ.get("APP_HOST", "0.0.0.0")
def app_port() -> int:
return int(os.environ.get("APP_PORT", "8080"))
def migrations_dir() -> Path:
override = os.environ.get("MIGRATIONS_DIR", "").strip()
if override:
return Path(override)
here = Path(__file__).resolve()
candidates = [
Path("/app/migrations"),
here.parents[2] / "migrations",
Path.cwd() / "migrations",
]
for path in candidates:
if path.is_dir():
return path
return candidates[0]
+107
View File
@@ -0,0 +1,107 @@
"""PostgreSQL connection pool and versioned migrations."""
from __future__ import annotations
import logging
import re
from pathlib import Path
from typing import List, Optional
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from messenger import config
log = logging.getLogger("messenger.db")
_pool: Optional[ConnectionPool] = None
def get_pool() -> ConnectionPool:
if _pool is None:
raise RuntimeError("Database pool is not initialized")
return _pool
def init_pool() -> ConnectionPool:
global _pool
if _pool is not None:
return _pool
url = config.database_url()
_pool = ConnectionPool(
conninfo=url,
min_size=1,
max_size=10,
kwargs={
"row_factory": dict_row,
"connect_timeout": 5,
"options": "-c statement_timeout=5000",
},
open=True,
timeout=10,
)
return _pool
def close_pool() -> None:
global _pool
if _pool is not None:
_pool.close()
_pool = None
def _split_sql(script: str) -> List[str]:
"""Split SQL file into statements (no procedure bodies in our migrations)."""
# Drop line comments.
cleaned = re.sub(r"--[^\n]*", "", script)
parts = []
for chunk in cleaned.split(";"):
stmt = chunk.strip()
if stmt:
parts.append(stmt)
return parts
def apply_migrations(migrations_path: Optional[Path] = None) -> None:
path = migrations_path or config.migrations_dir()
sql_files = sorted(path.glob("*.sql"))
if not sql_files:
raise RuntimeError(f"No migrations found in {path}")
pool = get_pool()
with pool.connection() as conn:
with conn.transaction():
conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
"""
)
for sql_file in sql_files:
version = sql_file.name
row = conn.execute(
"SELECT 1 AS ok FROM schema_migrations WHERE version = %s",
(version,),
).fetchone()
if row:
log.info("migration already applied: %s", version)
continue
script = sql_file.read_text(encoding="utf-8")
for stmt in _split_sql(script):
conn.execute(stmt)
conn.execute(
"INSERT INTO schema_migrations (version) VALUES (%s)",
(version,),
)
log.info("applied migration: %s", version)
def ping() -> bool:
try:
with get_pool().connection() as conn:
conn.execute("SELECT 1")
return True
except Exception as exc:
log.warning("postgres ping failed: %s", type(exc).__name__)
return False
+28
View File
@@ -0,0 +1,28 @@
"""One-shot migrations entrypoint (run once before API replicas)."""
from __future__ import annotations
import logging
import sys
from messenger import db
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
log = logging.getLogger("messenger.migrate")
def main() -> int:
db.init_pool()
try:
db.apply_migrations()
log.info("migrations complete")
return 0
finally:
db.close_pool()
if __name__ == "__main__":
raise SystemExit(main())
+136
View File
@@ -0,0 +1,136 @@
"""Opaque Bearer sessions in Redis with TTL (durable via Redis AOF)."""
from __future__ import annotations
import json
import logging
import secrets
from datetime import datetime, timedelta, timezone
from typing import Optional
import redis
from messenger import config
log = logging.getLogger("messenger.sessions")
_client: Optional[redis.Redis] = None
TOKEN_BYTES = 32 # 256-bit entropy
KEY_PREFIX = "sess:"
def utc_now() -> datetime:
return datetime.now(timezone.utc).replace(microsecond=0)
def format_ts(value: datetime) -> str:
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def parse_ts(value: str) -> datetime:
return datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
def init_client() -> redis.Redis:
global _client
if _client is not None:
return _client
url = config.cache_url()
_client = redis.Redis.from_url(
url,
decode_responses=True,
socket_connect_timeout=3,
socket_timeout=3,
health_check_interval=30,
)
return _client
def close_client() -> None:
global _client
if _client is not None:
try:
_client.close()
except Exception:
pass
_client = None
def get_client() -> redis.Redis:
if _client is None:
raise RuntimeError("Redis client is not initialized")
return _client
def ping() -> bool:
try:
return bool(get_client().ping())
except Exception as exc:
log.warning("redis ping failed: %s", type(exc).__name__)
return False
class SessionStoreError(Exception):
"""Raised when Redis is unavailable for session operations."""
def create_session(user_id: str) -> dict:
ttl = config.session_ttl_seconds()
token = secrets.token_urlsafe(TOKEN_BYTES)
now = utc_now()
expires_at = now + timedelta(seconds=ttl)
payload = {
"user_id": user_id,
"expires_at": format_ts(expires_at),
"created_at": format_ts(now),
}
key = KEY_PREFIX + token
try:
client = get_client()
# SET with EX: Redis is sole session store; AOF keeps it across restart.
client.set(key, json.dumps(payload), ex=ttl)
except redis.RedisError as exc:
raise SessionStoreError("session store unavailable") from exc
return {
"token": token,
"token_type": "Bearer",
"expires_at": payload["expires_at"],
"user_id": user_id,
}
def get_session(token: str) -> Optional[dict]:
if not token:
return None
key = KEY_PREFIX + token
try:
raw = get_client().get(key)
except redis.RedisError as exc:
raise SessionStoreError("session store unavailable") from exc
if not raw:
return None
try:
data = json.loads(raw)
expires_at = parse_ts(data["expires_at"])
except (ValueError, KeyError, TypeError, json.JSONDecodeError):
return None
if expires_at <= utc_now():
try:
get_client().delete(key)
except redis.RedisError:
pass
return None
return data
def revoke_session(token: str) -> bool:
if not token:
return False
key = KEY_PREFIX + token
try:
return bool(get_client().delete(key))
except redis.RedisError as exc:
raise SessionStoreError("session store unavailable") from exc
+480
View File
@@ -0,0 +1,480 @@
"""PostgreSQL repository: users, chats, membership, messages, idempotency."""
from __future__ import annotations
import hashlib
import json
import uuid
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import Any, List, Optional, Tuple
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
from psycopg import Error as PsycopgError
from psycopg import errors as pg_errors
from psycopg.types.json import Jsonb
from messenger import config
from messenger.db import get_pool
_ph = PasswordHasher()
class StoreUnavailable(Exception):
"""Raised when PostgreSQL is unreachable or timed out."""
def utc_now() -> datetime:
return datetime.now(timezone.utc).replace(microsecond=0)
def format_ts(value: datetime) -> str:
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
@dataclass
class User:
id: str
username: str
display_name: str
created_at: datetime
password_hash: str = ""
def to_dict(self) -> dict:
return {
"id": self.id,
"username": self.username,
"display_name": self.display_name,
"created_at": format_ts(self.created_at),
}
@dataclass
class Chat:
id: str
title: str
member_ids: List[str]
created_at: datetime
def to_dict(self) -> dict:
return {
"id": self.id,
"title": self.title,
"member_ids": list(self.member_ids),
"created_at": format_ts(self.created_at),
}
@dataclass
class Message:
id: str
chat_id: str
sender_id: str
text: str
created_at: datetime
def to_dict(self) -> dict:
return {
"id": self.id,
"chat_id": self.chat_id,
"sender_id": self.sender_id,
"text": self.text,
"created_at": format_ts(self.created_at),
}
def _row_user(row: dict) -> User:
return User(
id=str(row["id"]),
username=row["username"],
display_name=row["display_name"],
created_at=row["created_at"],
password_hash=row.get("password_hash", ""),
)
def _row_message(row: dict) -> Message:
return Message(
id=str(row["id"]),
chat_id=str(row["chat_id"]),
sender_id=str(row["sender_id"]),
text=row["text"],
created_at=row["created_at"],
)
class Store:
def hash_password(self, password: str) -> str:
return _ph.hash(password)
def verify_password(self, password_hash: str, password: str) -> bool:
try:
return _ph.verify(password_hash, password)
except VerifyMismatchError:
return False
except Exception:
return False
def create_user(self, username: str, display_name: str, password: str) -> User:
user_id = uuid.uuid4()
created = utc_now()
password_hash = self.hash_password(password)
try:
with get_pool().connection() as conn:
with conn.transaction():
conn.execute(
"""
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES (%s, %s, %s, %s, %s)
""",
(user_id, username, display_name, password_hash, created),
)
except (pg_errors.UniqueViolation, pg_errors.IntegrityError) as exc:
raise KeyError("username_taken") from exc
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return User(
id=str(user_id),
username=username,
display_name=display_name,
created_at=created,
)
def get_user(self, user_id: str) -> Optional[User]:
try:
with get_pool().connection() as conn:
row = conn.execute(
"""
SELECT id, username, display_name, password_hash, created_at
FROM users WHERE id = %s
""",
(user_id,),
).fetchone()
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return _row_user(row) if row else None
def get_user_by_username(self, username: str) -> Optional[User]:
try:
with get_pool().connection() as conn:
row = conn.execute(
"""
SELECT id, username, display_name, password_hash, created_at
FROM users WHERE username = %s
""",
(username,),
).fetchone()
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return _row_user(row) if row else None
def create_chat(self, title: str, member_ids: List[str]) -> Chat:
chat_id = uuid.uuid4()
created = utc_now()
try:
with get_pool().connection() as conn:
with conn.transaction():
# Atomic membership check + insert; rollback if any member missing.
rows = conn.execute(
"SELECT id FROM users WHERE id = ANY(%s::uuid[])",
(member_ids,),
).fetchall()
found = {str(r["id"]) for r in rows}
if found != set(member_ids):
raise KeyError("unknown_member")
conn.execute(
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
(chat_id, title, created),
)
for mid in member_ids:
conn.execute(
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
(chat_id, mid),
)
except KeyError:
raise
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return Chat(
id=str(chat_id),
title=title,
member_ids=list(member_ids),
created_at=created,
)
def get_chat(self, chat_id: str) -> Optional[Chat]:
try:
with get_pool().connection() as conn:
row = conn.execute(
"SELECT id, title, created_at FROM chats WHERE id = %s",
(chat_id,),
).fetchone()
if not row:
return None
members = conn.execute(
"""
SELECT user_id FROM chat_members
WHERE chat_id = %s
ORDER BY user_id
""",
(chat_id,),
).fetchall()
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return Chat(
id=str(row["id"]),
title=row["title"],
member_ids=[str(m["user_id"]) for m in members],
created_at=row["created_at"],
)
def list_chats_for_user(
self,
user_id: str,
limit: int,
cursor: Optional[Tuple[datetime, uuid.UUID]],
) -> Tuple[List[Chat], Optional[str]]:
params: list = [user_id]
where = "cm.user_id = %s"
if cursor is not None:
where += " AND (c.created_at, c.id) > (%s, %s)"
params.extend([cursor[0], cursor[1]])
params.append(limit + 1)
try:
with get_pool().connection() as conn:
rows = conn.execute(
f"""
SELECT c.id, c.title, c.created_at
FROM chats c
JOIN chat_members cm ON cm.chat_id = c.id
WHERE {where}
ORDER BY c.created_at ASC, c.id ASC
LIMIT %s
""",
params,
).fetchall()
chats: List[Chat] = []
for row in rows[:limit]:
members = conn.execute(
"""
SELECT user_id FROM chat_members
WHERE chat_id = %s
ORDER BY user_id
""",
(row["id"],),
).fetchall()
chats.append(
Chat(
id=str(row["id"]),
title=row["title"],
member_ids=[str(m["user_id"]) for m in members],
created_at=row["created_at"],
)
)
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
has_more = len(rows) > limit
return chats, "more" if has_more else None
@staticmethod
def request_hash_for_message(text: str) -> str:
# Canonical form: sorted keys; absent attachment_ids ≡ [].
canonical = json.dumps(
{"attachment_ids": [], "text": text},
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def create_message(self, chat_id: str, sender_id: str, text: str) -> Message:
msg_id = uuid.uuid4()
created = utc_now()
try:
with get_pool().connection() as conn:
with conn.transaction():
conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES (%s, %s, %s, %s, %s)
""",
(msg_id, chat_id, sender_id, text, created),
)
except pg_errors.DataError as exc:
raise ValueError("invalid_text") from exc
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return Message(
id=str(msg_id),
chat_id=chat_id,
sender_id=sender_id,
text=text,
created_at=created,
)
def create_message_idempotent(
self,
chat_id: str,
sender_id: str,
text: str,
method: str,
path: str,
idem_key: str,
) -> Tuple[Message, bool]:
"""
Create message with shared idempotency across replicas.
Returns (message, replayed).
Raises KeyError('conflict') when same key was used with another body.
"""
req_hash = self.request_hash_for_message(text)
ttl = timedelta(seconds=config.idempotency_ttl_seconds())
# Transaction-scoped advisory lock serializes same-key concurrent POSTs.
lock_material = f"{sender_id}|{method}|{path}|{idem_key}"
lock_key = int(
hashlib.sha256(lock_material.encode("utf-8")).hexdigest()[:15], 16
)
def _load_existing(conn) -> Optional[dict]:
return conn.execute(
"""
SELECT request_hash, response_status, response_body, created_at
FROM idempotency_records
WHERE user_id = %s AND method = %s AND path = %s AND idem_key = %s
""",
(sender_id, method, path, idem_key),
).fetchone()
def _message_from_body(body: Any) -> Message:
return Message(
id=str(body["id"]),
chat_id=str(body["chat_id"]),
sender_id=str(body["sender_id"]),
text=body["text"],
created_at=datetime.strptime(
body["created_at"], "%Y-%m-%dT%H:%M:%SZ"
).replace(tzinfo=timezone.utc),
)
try:
with get_pool().connection() as conn:
with conn.transaction():
conn.execute("SELECT pg_advisory_xact_lock(%s)", (lock_key,))
existing = _load_existing(conn)
if existing is not None:
if existing["created_at"] >= utc_now() - ttl:
if existing["request_hash"] != req_hash:
raise KeyError("conflict")
return _message_from_body(existing["response_body"]), True
conn.execute(
"""
DELETE FROM idempotency_records
WHERE user_id = %s AND method = %s AND path = %s AND idem_key = %s
""",
(sender_id, method, path, idem_key),
)
msg_id = uuid.uuid4()
created = utc_now()
message = Message(
id=str(msg_id),
chat_id=chat_id,
sender_id=sender_id,
text=text,
created_at=created,
)
conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES (%s, %s, %s, %s, %s)
""",
(msg_id, chat_id, sender_id, text, created),
)
conn.execute(
"""
INSERT INTO idempotency_records (
user_id, method, path, idem_key,
request_hash, response_status, response_body, created_at
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
""",
(
sender_id,
method,
path,
idem_key,
req_hash,
201,
Jsonb(message.to_dict()),
created,
),
)
return message, False
except KeyError:
raise
except pg_errors.DataError as exc:
raise ValueError("invalid_text") from exc
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
def list_messages(
self,
chat_id: str,
limit: int,
cursor: Optional[Tuple[datetime, uuid.UUID]],
) -> Tuple[List[Message], bool]:
params: list = [chat_id]
where = "chat_id = %s"
if cursor is not None:
where += " AND (created_at, id) > (%s, %s)"
params.extend([cursor[0], cursor[1]])
params.append(limit + 1)
try:
with get_pool().connection() as conn:
rows = conn.execute(
f"""
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE {where}
ORDER BY created_at ASC, id ASC
LIMIT %s
""",
params,
).fetchall()
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
messages = [_row_message(r) for r in rows[:limit]]
return messages, len(rows) > limit
def message_exists(self, chat_id: str, created_at: datetime, item_id: uuid.UUID) -> bool:
try:
with get_pool().connection() as conn:
row = conn.execute(
"""
SELECT 1 AS ok FROM messages
WHERE chat_id = %s AND created_at = %s AND id = %s
""",
(chat_id, created_at, item_id),
).fetchone()
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return bool(row)
def chat_exists_for_user(
self, user_id: str, created_at: datetime, item_id: uuid.UUID
) -> bool:
try:
with get_pool().connection() as conn:
row = conn.execute(
"""
SELECT 1 AS ok
FROM chats c
JOIN chat_members cm ON cm.chat_id = c.id
WHERE cm.user_id = %s AND c.created_at = %s AND c.id = %s
""",
(user_id, created_at, item_id),
).fetchone()
except PsycopgError as exc:
raise StoreUnavailable("database unavailable") from exc
return bool(row)