Lab 2: PostgreSQL sessions and recovery experiment
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1 @@
|
||||
__all__ = ["app"]
|
||||
@@ -0,0 +1,68 @@
|
||||
import logging
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from psycopg import Error as PsycopgError
|
||||
from psycopg_pool import PoolTimeout
|
||||
|
||||
from .errors import APIError, api_error_handler, build_error_payload, http_exception_handler, validation_error_handler
|
||||
from .routes import router
|
||||
from .store import StorageUnavailable, close_pool, init_db
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
app = FastAPI(title="MTUSI Messenger Lab 2")
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
def startup_db():
|
||||
init_db()
|
||||
|
||||
|
||||
@app.on_event("shutdown")
|
||||
def shutdown_db():
|
||||
close_pool()
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def assign_request_id(request: Request, call_next):
|
||||
request_id = request.headers.get("X-Request-Id") or __import__("uuid").uuid4().hex
|
||||
request.state.request_id = request_id
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = "lab2-local-instance"
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(APIError)
|
||||
async def handle_api_error(request: Request, exc: APIError):
|
||||
return await api_error_handler(request, exc)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def handle_validation_error(request: Request, exc: RequestValidationError):
|
||||
return await validation_error_handler(request, exc)
|
||||
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def handle_http_not_found(request: Request, exc):
|
||||
return await http_exception_handler(request, exc)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def handle_unexpected_error(request: Request, exc: Exception):
|
||||
if isinstance(exc, (StorageUnavailable, PsycopgError, PoolTimeout)):
|
||||
logger.warning("Required service unavailable (%s)", type(exc).__name__)
|
||||
content = build_error_payload(request, "service_unavailable", "A required service is unavailable")
|
||||
headers = {
|
||||
"X-Request-Id": request.state.request_id,
|
||||
"X-Instance-Id": "lab2-local-instance",
|
||||
}
|
||||
return JSONResponse(status_code=503, content=content, headers=headers)
|
||||
logger.exception("Unhandled API exception", exc_info=exc)
|
||||
content = build_error_payload(request, "internal_error", "Internal server error")
|
||||
headers = {"X-Request-Id": request.state.request_id, "X-Instance-Id": "lab2-local-instance"}
|
||||
return JSONResponse(status_code=500, content=content, headers=headers)
|
||||
|
||||
|
||||
app.include_router(router)
|
||||
@@ -0,0 +1,52 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
|
||||
class APIError(Exception):
|
||||
def __init__(self, status_code: int, code: str, message: str):
|
||||
self.status_code = status_code
|
||||
self.code = code
|
||||
self.message = message
|
||||
|
||||
|
||||
def build_error_payload(request: Request, code: str, message: str):
|
||||
request_id = getattr(request.state, "request_id", None) or request.headers.get("X-Request-Id") or str(uuid.uuid4())
|
||||
return {"error": {"code": code, "message": message, "request_id": request_id}}
|
||||
|
||||
|
||||
def build_headers(request: Request, challenge: str | None = None):
|
||||
headers = {
|
||||
"X-Request-Id": getattr(request.state, "request_id", request.headers.get("X-Request-Id", "unknown")),
|
||||
"X-Instance-Id": "lab2-local-instance",
|
||||
}
|
||||
if challenge:
|
||||
headers["WWW-Authenticate"] = challenge
|
||||
return headers
|
||||
|
||||
|
||||
async def api_error_handler(request: Request, exc: APIError):
|
||||
challenge = None
|
||||
if exc.status_code == 401:
|
||||
challenge = (
|
||||
'Basic realm="messenger", charset="UTF-8"'
|
||||
if request.url.path.endswith("/auth/sessions")
|
||||
else 'Bearer realm="messenger"'
|
||||
)
|
||||
content = build_error_payload(request, exc.code, exc.message)
|
||||
return JSONResponse(status_code=exc.status_code, content=content, headers=build_headers(request, challenge))
|
||||
|
||||
|
||||
async def validation_error_handler(request: Request, exc: RequestValidationError):
|
||||
details = exc.errors()
|
||||
message = details[0].get("msg", "invalid request") if details else "invalid request"
|
||||
content = build_error_payload(request, "invalid_request", message)
|
||||
return JSONResponse(status_code=400, content=content, headers=build_headers(request))
|
||||
|
||||
|
||||
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
code = "not_found" if exc.status_code == 404 else "invalid_request"
|
||||
content = build_error_payload(request, code, exc.detail or "request failed")
|
||||
return JSONResponse(status_code=exc.status_code, content=content, headers=build_headers(request))
|
||||
@@ -0,0 +1,124 @@
|
||||
import re
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
|
||||
|
||||
class UserModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class ChatModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: str
|
||||
title: str
|
||||
member_ids: list[str]
|
||||
created_at: str
|
||||
|
||||
|
||||
class MessageModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class SessionModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
token: str
|
||||
token_type: str = "Bearer"
|
||||
expires_at: str
|
||||
user: UserModel
|
||||
|
||||
|
||||
class CreateUserInput(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
username: str = Field(..., min_length=3, max_length=32)
|
||||
display_name: str = Field(..., min_length=1, max_length=100)
|
||||
password: str = Field(..., min_length=12, max_length=128)
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def validate_username(cls, value: str):
|
||||
if not USERNAME_RE.fullmatch(value):
|
||||
raise ValueError("username format is invalid")
|
||||
return value
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def validate_display_name(cls, value: str):
|
||||
if not value.strip():
|
||||
raise ValueError("display_name is invalid")
|
||||
return value
|
||||
|
||||
@field_validator("password")
|
||||
@classmethod
|
||||
def validate_password(cls, value: str):
|
||||
if not value or not value.strip():
|
||||
raise ValueError("password is invalid")
|
||||
if any(ch == ":" for ch in value):
|
||||
return value
|
||||
return value
|
||||
|
||||
|
||||
class CreateChatInput(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str = Field(..., min_length=1, max_length=100)
|
||||
member_ids: list[str] = Field(..., min_length=1, max_length=100)
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def validate_title(cls, value: str):
|
||||
if not value.strip():
|
||||
raise ValueError("title is invalid")
|
||||
return value
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def validate_member_ids(cls, value: list[str]):
|
||||
if len(value) != len(set(value)):
|
||||
raise ValueError("member_ids must be unique")
|
||||
for member_id in value:
|
||||
try:
|
||||
uuid.UUID(str(member_id))
|
||||
except ValueError as exc:
|
||||
raise ValueError("member_ids must contain valid UUIDs") from exc
|
||||
return value
|
||||
|
||||
|
||||
class CreateMessageInput(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
text: str = Field(..., min_length=1, max_length=4000)
|
||||
|
||||
@field_validator("text")
|
||||
@classmethod
|
||||
def validate_text(cls, value: str):
|
||||
if not value.strip():
|
||||
raise ValueError("text is invalid")
|
||||
return value
|
||||
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
items: list[ChatModel]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
items: list[MessageModel]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class HealthModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
status: str = "ok"
|
||||
@@ -0,0 +1,203 @@
|
||||
import base64
|
||||
import uuid
|
||||
from typing import Annotated, Optional
|
||||
|
||||
from fastapi import APIRouter, Query, Request
|
||||
from psycopg.errors import UniqueViolation
|
||||
import redis
|
||||
from psycopg import Error as PsycopgError
|
||||
from psycopg_pool import PoolTimeout
|
||||
|
||||
from .errors import APIError
|
||||
from .models import ChatModel, ChatPage, CreateChatInput, CreateMessageInput, CreateUserInput, MessageModel, MessagePage, SessionModel, UserModel
|
||||
from .store import (
|
||||
create_chat_record,
|
||||
create_session_for_user,
|
||||
create_user_record,
|
||||
delete_session_for_token,
|
||||
get_chat_by_id,
|
||||
get_session_for_token,
|
||||
get_user_by_id,
|
||||
get_user_by_username,
|
||||
insert_message_record,
|
||||
list_chats_for_user,
|
||||
list_messages_for_chat,
|
||||
user_public_row,
|
||||
verify_password,
|
||||
)
|
||||
from .utils import decode_cursor, encode_cursor
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def require_bearer(request: Request):
|
||||
auth = request.headers.get("Authorization", "")
|
||||
if not auth.startswith("Bearer "):
|
||||
raise APIError(401, "unauthorized", "Valid bearer token is required")
|
||||
token = auth.split(" ", 1)[1].strip()
|
||||
session = get_session_for_token(token)
|
||||
if session is None:
|
||||
raise APIError(401, "unauthorized", "Valid bearer token is required")
|
||||
user = get_user_by_id(str(session["user_id"]))
|
||||
if user is None:
|
||||
raise APIError(401, "unauthorized", "Valid bearer token is required")
|
||||
return user_public_row(user), session
|
||||
|
||||
|
||||
def validated_uuid(value: str, field_name: str) -> str:
|
||||
try:
|
||||
return str(uuid.UUID(value))
|
||||
except (ValueError, AttributeError) as exc:
|
||||
raise APIError(400, "invalid_request", "{} must be a UUID".format(field_name)) from exc
|
||||
|
||||
|
||||
@router.get("/health/live")
|
||||
def health_live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/health/ready")
|
||||
def health_ready():
|
||||
try:
|
||||
from .store import get_conn, get_redis_client
|
||||
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.execute("SELECT 1").fetchone()
|
||||
finally:
|
||||
conn.close()
|
||||
get_redis_client().ping()
|
||||
return {"status": "ok"}
|
||||
except (PsycopgError, PoolTimeout, redis.RedisError) as exc:
|
||||
raise APIError(503, "service_unavailable", "A required service is unavailable") from exc
|
||||
except APIError:
|
||||
raise
|
||||
|
||||
|
||||
@router.post("/api/v1/users", status_code=201, response_model=UserModel)
|
||||
def create_user(payload: CreateUserInput):
|
||||
try:
|
||||
record = create_user_record(payload)
|
||||
except UniqueViolation as exc:
|
||||
raise APIError(409, "conflict", "username already exists") from exc
|
||||
return {
|
||||
"id": record["id"],
|
||||
"username": record["username"],
|
||||
"display_name": record["display_name"],
|
||||
"created_at": record["created_at"],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/v1/users/me", response_model=UserModel)
|
||||
def current_user(request: Request):
|
||||
user, _ = require_bearer(request)
|
||||
return user
|
||||
|
||||
|
||||
@router.post("/api/v1/chats", status_code=201, response_model=ChatModel)
|
||||
def create_chat(request: Request, payload: CreateChatInput):
|
||||
_, session = require_bearer(request)
|
||||
actor_id = str(session["user_id"])
|
||||
for member_id in payload.member_ids:
|
||||
if get_user_by_id(member_id) is None:
|
||||
raise APIError(400, "invalid_request", "member_ids contain unknown users")
|
||||
if actor_id not in [str(member_id) for member_id in payload.member_ids]:
|
||||
raise APIError(400, "invalid_request", "creator must be included in member_ids")
|
||||
chat = create_chat_record(actor_id, payload.title, [str(member_id) for member_id in payload.member_ids])
|
||||
return chat
|
||||
|
||||
|
||||
@router.get("/api/v1/chats", response_model=ChatPage)
|
||||
def list_chats(request: Request, limit: Annotated[int, Query(ge=1, le=100)] = 50, cursor: Optional[str] = None):
|
||||
user, _ = require_bearer(request)
|
||||
try:
|
||||
start_after = decode_cursor(cursor) if cursor else None
|
||||
except ValueError as exc:
|
||||
raise APIError(400, "invalid_request", "cursor is invalid") from exc
|
||||
chats = list_chats_for_user(user["id"], limit, start_after)
|
||||
page = chats[:limit]
|
||||
next_cursor = None
|
||||
if len(chats) > limit:
|
||||
last = page[-1]
|
||||
next_cursor = encode_cursor(last["created_at"], last["id"])
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}", response_model=ChatModel)
|
||||
def get_chat(request: Request, chat_id: str):
|
||||
user, _ = require_bearer(request)
|
||||
chat_id = validated_uuid(chat_id, "chat_id")
|
||||
chat = get_chat_by_id(chat_id)
|
||||
if chat is None or user["id"] not in chat["member_ids"]:
|
||||
raise APIError(404, "not_found", "Chat not found")
|
||||
return {"id": str(chat["id"]), "title": chat["title"], "member_ids": [str(v) for v in chat["member_ids"]], "created_at": chat["created_at"]}
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/messages", status_code=201, response_model=MessageModel)
|
||||
def create_message(request: Request, chat_id: str, payload: CreateMessageInput):
|
||||
user, _ = require_bearer(request)
|
||||
chat_id = validated_uuid(chat_id, "chat_id")
|
||||
chat = get_chat_by_id(chat_id)
|
||||
if chat is None or user["id"] not in chat["member_ids"]:
|
||||
raise APIError(404, "not_found", "Chat not found")
|
||||
message = insert_message_record(chat_id, user["id"], payload.text)
|
||||
return message
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
def list_messages(request: Request, chat_id: str, limit: Annotated[int, Query(ge=1, le=100)] = 50, cursor: Optional[str] = None):
|
||||
user, _ = require_bearer(request)
|
||||
chat_id = validated_uuid(chat_id, "chat_id")
|
||||
chat = get_chat_by_id(chat_id)
|
||||
if chat is None or user["id"] not in chat["member_ids"]:
|
||||
raise APIError(404, "not_found", "Chat not found")
|
||||
try:
|
||||
start_after = decode_cursor(cursor, expected_resource_id=chat_id) if cursor else None
|
||||
except ValueError as exc:
|
||||
raise APIError(400, "invalid_request", "cursor is invalid") from exc
|
||||
messages = list_messages_for_chat(chat_id, limit, start_after)
|
||||
page = messages[:limit]
|
||||
next_cursor = None
|
||||
if len(messages) > limit:
|
||||
last = page[-1]
|
||||
next_cursor = encode_cursor(last["created_at"], last["id"], chat_id)
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/sessions", status_code=201, response_model=SessionModel)
|
||||
def create_session(request: Request):
|
||||
auth = request.headers.get("Authorization", "")
|
||||
if not auth.startswith("Basic "):
|
||||
raise APIError(401, "unauthorized", "Valid basic auth is required")
|
||||
try:
|
||||
raw = base64.b64decode(auth.split(" ", 1)[1], validate=True).decode("utf-8")
|
||||
except Exception as exc:
|
||||
raise APIError(401, "unauthorized", "Valid basic auth is required") from exc
|
||||
if ":" not in raw:
|
||||
raise APIError(401, "unauthorized", "Valid basic auth is required")
|
||||
username, password = raw.split(":", 1)
|
||||
user = get_user_by_username(username)
|
||||
if user is None or not verify_password(password, user["password_hash"]):
|
||||
raise APIError(401, "unauthorized", "Valid basic auth is required")
|
||||
session = create_session_for_user(str(user["id"]))
|
||||
response_user = user_public_row(user)
|
||||
expires_value = session["expires_at"]
|
||||
expires_at_text = expires_value.strftime("%Y-%m-%dT%H:%M:%S.%fZ") if hasattr(expires_value, "strftime") else str(expires_value)
|
||||
return {
|
||||
"token": session["token"],
|
||||
"token_type": "Bearer",
|
||||
"expires_at": expires_at_text,
|
||||
"user": response_user,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def revoke_session(request: Request):
|
||||
auth = request.headers.get("Authorization", "")
|
||||
if not auth.startswith("Bearer "):
|
||||
raise APIError(401, "unauthorized", "Valid bearer token is required")
|
||||
token = auth.split(" ", 1)[1].strip()
|
||||
if get_session_for_token(token) is None:
|
||||
raise APIError(401, "unauthorized", "Valid bearer token is required")
|
||||
delete_session_for_token(token)
|
||||
return None
|
||||
@@ -0,0 +1,504 @@
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import secrets
|
||||
import threading
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import redis
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError, VerificationError
|
||||
from psycopg import OperationalError
|
||||
from psycopg.errors import UniqueViolation
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool, PoolTimeout
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DATABASE_URL = os.environ.get("DATABASE_URL", "")
|
||||
REDIS_URL = os.environ.get("REDIS_URL", "")
|
||||
SESSION_TTL_SECONDS = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
DB_POOL_MIN_SIZE = int(os.environ.get("DB_POOL_MIN_SIZE", "1"))
|
||||
DB_POOL_MAX_SIZE = int(os.environ.get("DB_POOL_MAX_SIZE", "10"))
|
||||
DB_POOL_TIMEOUT_SECONDS = float(os.environ.get("DB_POOL_TIMEOUT_SECONDS", "3"))
|
||||
DB_STATEMENT_TIMEOUT_MS = int(os.environ.get("DB_STATEMENT_TIMEOUT_MS", "5000"))
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parents[2] / "migrations"
|
||||
password_hasher = PasswordHasher()
|
||||
|
||||
_pool = None
|
||||
_pool_lock = threading.Lock()
|
||||
_redis_client = None
|
||||
_redis_lock = threading.Lock()
|
||||
|
||||
|
||||
class StorageUnavailable(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class _PooledConnection:
|
||||
def __init__(self, pool, connection):
|
||||
self._pool = pool
|
||||
self._connection = connection
|
||||
self._returned = False
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self._connection, name)
|
||||
|
||||
def close(self):
|
||||
if not self._returned:
|
||||
self._returned = True
|
||||
if self._connection.info.transaction_status != 0:
|
||||
self._connection.rollback()
|
||||
self._pool.putconn(self._connection)
|
||||
|
||||
|
||||
def _get_pool():
|
||||
global _pool
|
||||
if not DATABASE_URL.startswith("postgresql://") and not DATABASE_URL.startswith("postgres://"):
|
||||
raise StorageUnavailable("DATABASE_URL must point to PostgreSQL")
|
||||
if _pool is None:
|
||||
with _pool_lock:
|
||||
if _pool is None:
|
||||
try:
|
||||
_pool = ConnectionPool(
|
||||
conninfo=DATABASE_URL,
|
||||
min_size=DB_POOL_MIN_SIZE,
|
||||
max_size=DB_POOL_MAX_SIZE,
|
||||
timeout=DB_POOL_TIMEOUT_SECONDS,
|
||||
kwargs={
|
||||
"connect_timeout": 3,
|
||||
"options": "-c statement_timeout={}".format(DB_STATEMENT_TIMEOUT_MS),
|
||||
"row_factory": dict_row,
|
||||
},
|
||||
)
|
||||
except (OperationalError, PoolTimeout) as exc:
|
||||
raise StorageUnavailable("PostgreSQL is unavailable") from exc
|
||||
return _pool
|
||||
|
||||
|
||||
def get_conn():
|
||||
try:
|
||||
pool = _get_pool()
|
||||
return _PooledConnection(pool, pool.getconn(timeout=DB_POOL_TIMEOUT_SECONDS))
|
||||
except (OperationalError, PoolTimeout) as exc:
|
||||
raise StorageUnavailable("PostgreSQL is unavailable") from exc
|
||||
|
||||
|
||||
def close_pool():
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
_pool.close()
|
||||
_pool = None
|
||||
|
||||
|
||||
def get_redis_client():
|
||||
global _redis_client
|
||||
if not REDIS_URL:
|
||||
raise StorageUnavailable("REDIS_URL is required for session storage")
|
||||
if _redis_client is None:
|
||||
with _redis_lock:
|
||||
if _redis_client is None:
|
||||
_redis_client = redis.Redis.from_url(
|
||||
REDIS_URL,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=2,
|
||||
socket_timeout=2,
|
||||
health_check_interval=30,
|
||||
)
|
||||
return _redis_client
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def isoformat_utc(value=None) -> str:
|
||||
if value is None:
|
||||
value = utc_now()
|
||||
if isinstance(value, str):
|
||||
value = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def _row_dict(row):
|
||||
if row is None:
|
||||
return None
|
||||
return dict(row)
|
||||
|
||||
|
||||
def init_db():
|
||||
if not MIGRATIONS_DIR.is_dir():
|
||||
raise RuntimeError("migrations directory is missing")
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version TEXT PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.commit()
|
||||
for migration in sorted(MIGRATIONS_DIR.glob("*.sql")):
|
||||
version = migration.stem
|
||||
with conn.transaction():
|
||||
conn.execute("SELECT pg_advisory_xact_lock(821733204)")
|
||||
applied = conn.execute(
|
||||
"SELECT 1 FROM schema_migrations WHERE version = %s",
|
||||
(version,),
|
||||
).fetchone()
|
||||
if applied:
|
||||
continue
|
||||
for statement in migration.read_text(encoding="utf-8").split(";"):
|
||||
if statement.strip():
|
||||
conn.execute(statement)
|
||||
conn.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (version,))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def hash_password(value: str) -> str:
|
||||
return password_hasher.hash(value)
|
||||
|
||||
|
||||
def verify_password(raw: str, hashed: str) -> bool:
|
||||
try:
|
||||
return password_hasher.verify(hashed, raw)
|
||||
except (VerifyMismatchError, VerificationError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def generate_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def get_user_by_username(username: str):
|
||||
conn = get_conn()
|
||||
try:
|
||||
return conn.execute("SELECT * FROM users WHERE username = %s", (username,)).fetchone()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_user_by_id(user_id: str):
|
||||
try:
|
||||
parsed_id = str(uuid.UUID(user_id))
|
||||
except (ValueError, AttributeError):
|
||||
return None
|
||||
conn = get_conn()
|
||||
try:
|
||||
return conn.execute("SELECT * FROM users WHERE id = %s", (parsed_id,)).fetchone()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def create_user_record(payload):
|
||||
user_id = uuid.uuid4()
|
||||
password_hash = hash_password(payload.password)
|
||||
conn = get_conn()
|
||||
try:
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING id, username, display_name, password_hash, created_at
|
||||
""",
|
||||
(user_id, payload.username, payload.display_name, password_hash),
|
||||
).fetchone()
|
||||
conn.commit()
|
||||
except UniqueViolation:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": isoformat_utc(row["created_at"]),
|
||||
"password_hash": row["password_hash"],
|
||||
}
|
||||
|
||||
|
||||
def create_session_for_user(user_id: str):
|
||||
token = generate_token()
|
||||
expires_at = utc_now() + timedelta(seconds=SESSION_TTL_SECONDS)
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.execute(
|
||||
"INSERT INTO sessions (token, user_id, expires_at) VALUES (%s, %s, %s)",
|
||||
(token, user_id, expires_at),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
try:
|
||||
client = get_redis_client()
|
||||
client.setex(
|
||||
"session:{}".format(token),
|
||||
SESSION_TTL_SECONDS,
|
||||
json.dumps(
|
||||
{"token": token, "user_id": user_id, "expires_at": isoformat_utc(expires_at)},
|
||||
separators=(",", ":"),
|
||||
),
|
||||
)
|
||||
except (StorageUnavailable, redis.RedisError):
|
||||
logger.exception("Could not cache newly created session")
|
||||
delete_session_record(token)
|
||||
raise StorageUnavailable("Session storage is unavailable")
|
||||
return {"token": token, "user_id": str(user_id), "expires_at": expires_at}
|
||||
|
||||
|
||||
def delete_session_record(token: str):
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.execute("DELETE FROM sessions WHERE token = %s", (token,))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_session_for_token(token: str):
|
||||
client = get_redis_client()
|
||||
try:
|
||||
if client.exists("session:revoked:{}".format(token)):
|
||||
return None
|
||||
cached = client.get("session:{}".format(token))
|
||||
except redis.RedisError as exc:
|
||||
raise StorageUnavailable("Redis is unavailable") from exc
|
||||
if cached is not None:
|
||||
try:
|
||||
payload = json.loads(cached)
|
||||
expires_at = datetime.fromisoformat(payload["expires_at"].replace("Z", "+00:00"))
|
||||
if expires_at <= utc_now():
|
||||
client.delete("session:{}".format(token))
|
||||
return None
|
||||
return {"token": token, "user_id": payload["user_id"], "expires_at": expires_at}
|
||||
except (KeyError, TypeError, ValueError, json.JSONDecodeError):
|
||||
logger.warning("Discarding malformed session cache entry")
|
||||
try:
|
||||
client.delete("session:{}".format(token))
|
||||
except redis.RedisError as exc:
|
||||
raise StorageUnavailable("Redis is unavailable") from exc
|
||||
|
||||
conn = get_conn()
|
||||
try:
|
||||
row = conn.execute("SELECT * FROM sessions WHERE token = %s", (token,)).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
expires_at = row["expires_at"]
|
||||
if expires_at <= utc_now():
|
||||
conn.execute("DELETE FROM sessions WHERE token = %s", (token,))
|
||||
conn.commit()
|
||||
return None
|
||||
remaining = max(1, math.ceil((expires_at - utc_now()).total_seconds()))
|
||||
try:
|
||||
client.setex(
|
||||
"session:{}".format(token),
|
||||
remaining,
|
||||
json.dumps(
|
||||
{"token": token, "user_id": str(row["user_id"]), "expires_at": isoformat_utc(expires_at)},
|
||||
separators=(",", ":"),
|
||||
),
|
||||
)
|
||||
except redis.RedisError as exc:
|
||||
raise StorageUnavailable("Redis is unavailable") from exc
|
||||
return row
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def delete_session_for_token(token: str):
|
||||
client = get_redis_client()
|
||||
conn = get_conn()
|
||||
try:
|
||||
row = conn.execute("SELECT expires_at FROM sessions WHERE token = %s", (token,)).fetchone()
|
||||
ttl = SESSION_TTL_SECONDS
|
||||
if row is not None:
|
||||
ttl = max(1, math.ceil((row["expires_at"] - utc_now()).total_seconds()))
|
||||
try:
|
||||
client.setex("session:revoked:{}".format(token), ttl, "1")
|
||||
client.delete("session:{}".format(token))
|
||||
except redis.RedisError as exc:
|
||||
raise StorageUnavailable("Redis is unavailable") from exc
|
||||
conn.execute("DELETE FROM sessions WHERE token = %s", (token,))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def create_chat_record(actor_id: str, title: str, member_ids: list[str]):
|
||||
chat_id = uuid.uuid4()
|
||||
conn = get_conn()
|
||||
try:
|
||||
with conn.transaction():
|
||||
row = conn.execute(
|
||||
"INSERT INTO chats (id, title) VALUES (%s, %s) RETURNING created_at",
|
||||
(chat_id, title),
|
||||
).fetchone()
|
||||
for member_id in member_ids:
|
||||
conn.execute(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
|
||||
(chat_id, member_id),
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
return {
|
||||
"id": str(chat_id),
|
||||
"title": title,
|
||||
"member_ids": member_ids,
|
||||
"created_at": isoformat_utc(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def get_chat_by_id(chat_id: str):
|
||||
try:
|
||||
parsed_id = str(uuid.UUID(chat_id))
|
||||
except (ValueError, AttributeError):
|
||||
return None
|
||||
conn = get_conn()
|
||||
try:
|
||||
chat = conn.execute(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
COALESCE(array_agg(cm.user_id ORDER BY cm.user_id), ARRAY[]::uuid[]) AS member_ids
|
||||
FROM chats c
|
||||
LEFT JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE c.id = %s
|
||||
GROUP BY c.id
|
||||
""",
|
||||
(parsed_id,),
|
||||
).fetchone()
|
||||
if chat is None:
|
||||
return None
|
||||
result = dict(chat)
|
||||
result["id"] = str(result["id"])
|
||||
result["member_ids"] = [str(value) for value in result["member_ids"]]
|
||||
result["created_at"] = isoformat_utc(result["created_at"])
|
||||
return result
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_chats_for_user(user_id: str, limit: int, cursor=None):
|
||||
conn = get_conn()
|
||||
try:
|
||||
if cursor:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
array_agg(cm_all.user_id ORDER BY cm_all.user_id) AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = %s
|
||||
JOIN chat_members cm_all ON cm_all.chat_id = c.id
|
||||
WHERE (c.created_at, c.id) > (%s::timestamptz, %s::uuid)
|
||||
GROUP BY c.id
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT %s
|
||||
""",
|
||||
(user_id, cursor[0], cursor[1], limit + 1),
|
||||
).fetchall()
|
||||
else:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
array_agg(cm_all.user_id ORDER BY cm_all.user_id) AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = %s
|
||||
JOIN chat_members cm_all ON cm_all.chat_id = c.id
|
||||
GROUP BY c.id
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT %s
|
||||
""",
|
||||
(user_id, limit + 1),
|
||||
).fetchall()
|
||||
return [
|
||||
{
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"created_at": isoformat_utc(row["created_at"]),
|
||||
"member_ids": [str(value) for value in row["member_ids"]],
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def insert_message_record(chat_id: str, sender_id: str, text: str):
|
||||
message_id = uuid.uuid4()
|
||||
conn = get_conn()
|
||||
try:
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING created_at
|
||||
""",
|
||||
(message_id, chat_id, sender_id, text),
|
||||
).fetchone()
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return {
|
||||
"id": str(message_id),
|
||||
"chat_id": str(chat_id),
|
||||
"sender_id": str(sender_id),
|
||||
"text": text,
|
||||
"created_at": isoformat_utc(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def list_messages_for_chat(chat_id: str, limit: int, cursor=None):
|
||||
conn = get_conn()
|
||||
try:
|
||||
if cursor:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = %s AND (created_at, id) > (%s::timestamptz, %s::uuid)
|
||||
ORDER BY created_at, id
|
||||
LIMIT %s
|
||||
""",
|
||||
(chat_id, cursor[0], cursor[1], limit + 1),
|
||||
).fetchall()
|
||||
else:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = %s
|
||||
ORDER BY created_at, id
|
||||
LIMIT %s
|
||||
""",
|
||||
(chat_id, limit + 1),
|
||||
).fetchall()
|
||||
return [
|
||||
{
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": isoformat_utc(row["created_at"]),
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def user_public_row(row):
|
||||
if row is None:
|
||||
return None
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": isoformat_utc(row["created_at"]),
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import base64
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def utc_now() -> str:
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
def encode_cursor(created_at: str, item_id: str, resource_id: str | None = None) -> str:
|
||||
payload = {"created_at": created_at, "id": item_id}
|
||||
if resource_id is not None:
|
||||
payload["resource_id"] = resource_id
|
||||
encoded = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(encoded).decode("ascii")
|
||||
|
||||
|
||||
def decode_cursor(cursor_value: str | None, expected_resource_id: str | None = None):
|
||||
if cursor_value is None:
|
||||
return None
|
||||
try:
|
||||
raw = base64.b64decode(cursor_value.encode("ascii"), altchars=b"-_", validate=True)
|
||||
payload = json.loads(raw.decode("utf-8"))
|
||||
except (ValueError, UnicodeError, json.JSONDecodeError) as exc:
|
||||
raise ValueError("cursor is invalid") from exc
|
||||
if not isinstance(payload, dict) or "created_at" not in payload or "id" not in payload:
|
||||
raise ValueError("cursor is invalid")
|
||||
if not isinstance(payload["created_at"], str) or not isinstance(payload["id"], str):
|
||||
raise ValueError("cursor is invalid")
|
||||
try:
|
||||
from datetime import datetime
|
||||
import uuid
|
||||
|
||||
datetime.fromisoformat(payload["created_at"].replace("Z", "+00:00"))
|
||||
payload["id"] = str(uuid.UUID(payload["id"]))
|
||||
except (ValueError, AttributeError) as exc:
|
||||
raise ValueError("cursor is invalid") from exc
|
||||
if expected_resource_id is not None:
|
||||
if payload.get("resource_id") != expected_resource_id:
|
||||
raise ValueError("cursor belongs to another resource")
|
||||
return payload["created_at"], payload["id"]
|
||||
Reference in New Issue
Block a user