выполнение лр2 на 4
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Ilya
2026-10-07 18:28:12 +03:00
parent 65003b6119
commit e914e384fc
32 changed files with 2054 additions and 15 deletions
View File
+122
View File
@@ -0,0 +1,122 @@
"""Passwords (Argon2id), Basic login and opaque Bearer sessions."""
from __future__ import annotations
import asyncio
import base64
import binascii
import hashlib
import secrets
from datetime import datetime, timezone
from typing import Optional, Tuple
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError
from starlette.concurrency import run_in_threadpool
from app import config
from app.cache import REVOKED, SessionCache
from app.errors import BASIC_CHALLENGE, unauthorized
from app.storage import Store, fmt_ts, user_row
# argon2-cffi defaults = RFC 9106 low-memory profile (Argon2id, t=3, m=64 MiB, p=4).
_hasher = PasswordHasher()
_hash_slots = asyncio.Semaphore(config.PASSWORD_HASH_CONCURRENCY)
# Verified when the username does not exist, so both failures cost the same time.
_DUMMY_HASH = _hasher.hash("dummy-password-for-timing")
async def hash_password(password: str) -> str:
async with _hash_slots:
return await run_in_threadpool(_hasher.hash, password)
async def verify_password(password_hash: str, password: str) -> bool:
def verify() -> bool:
try:
return _hasher.verify(password_hash, password)
except (VerificationError, InvalidHashError):
return False
async with _hash_slots:
return await run_in_threadpool(verify)
def token_digest(token: str) -> bytes:
# A fast hash is enough here: the token already carries 256 random bits,
# unlike a human password that needs a slow KDF against guessing.
return hashlib.sha256(token.encode("ascii")).digest()
def parse_basic(header: Optional[str]) -> Tuple[str, str]:
bad = unauthorized("invalid credentials", BASIC_CHALLENGE)
if not header:
raise bad
scheme, _, value = header.partition(" ")
if scheme.lower() != "basic" or not value.strip():
raise bad
try:
decoded = base64.b64decode(value.strip(), validate=True).decode("utf-8")
except (binascii.Error, UnicodeDecodeError):
raise bad from None
username, sep, password = decoded.partition(":") # the password may contain ':'
if not sep or not username.isascii() or not 12 <= len(password) <= 128:
raise bad
return username, password
def parse_bearer(header: Optional[str]) -> str:
if not header:
raise unauthorized("bearer token required")
scheme, _, token = header.partition(" ")
token = token.strip()
if scheme.lower() != "bearer" or not token or not token.isascii() or len(token) > 256:
raise unauthorized("bearer token required")
return token
async def login(store: Store, header: Optional[str]) -> dict:
username, password = parse_basic(header)
row = await store.get_credentials(username)
if row is None:
await verify_password(_DUMMY_HASH, password)
raise unauthorized("invalid credentials", BASIC_CHALLENGE)
if not await verify_password(row["password_hash"], password):
raise unauthorized("invalid credentials", BASIC_CHALLENGE)
token = secrets.token_urlsafe(32) # 256 bits of entropy
expires_at = await store.create_session(token_digest(token), row["id"], config.SESSION_TTL_SECONDS)
return {"token": token, "token_type": "Bearer", "expires_at": fmt_ts(expires_at), "user": user_row(row)}
async def authenticate(store: Store, cache: SessionCache, header: Optional[str]) -> dict:
"""Return the session's user or raise 401. Cache first, PostgreSQL on a miss.
If PostgreSQL is down and the cache has no answer the error propagates as 503:
an unverifiable token is never treated as authenticated."""
digest = token_digest(parse_bearer(header))
cached = await cache.get(digest)
if cached == REVOKED:
raise unauthorized("session expired or revoked")
if isinstance(cached, dict):
expires_at = datetime.fromisoformat(cached["expires_at"].replace("Z", "+00:00"))
if expires_at > datetime.now(timezone.utc):
return cached["user"]
raise unauthorized("session expired or revoked")
row = await store.find_session(digest)
if row is None:
raise unauthorized("session expired or revoked")
user = user_row(row)
remaining = int((row["expires_at"] - datetime.now(timezone.utc)).total_seconds())
await cache.put(digest, {"user": user, "expires_at": fmt_ts(row["expires_at"])}, remaining)
return user
async def logout(store: Store, cache: SessionCache, header: Optional[str]) -> None:
# Authenticate first so an already revoked token gets 401, as the contract requires.
await authenticate(store, cache, header)
digest = token_digest(parse_bearer(header))
expires_at = await store.revoke_session(digest) # PostgreSQL first: it is the truth
if expires_at is None:
raise unauthorized("session expired or revoked")
remaining = int((expires_at - datetime.now(timezone.utc)).total_seconds()) + 1
await cache.revoke(digest, remaining)
+102
View File
@@ -0,0 +1,102 @@
"""Valkey session cache. Never the source of truth: every failure degrades to a miss.
Keys: session:<sha256(token) hex>
Value: JSON {"user": {...}, "expires_at": "..."} - a valid session
"revoked" - tombstone written by logout
Entry TTL = min(time left in the session, SESSION_CACHE_MAX_SECONDS).
"""
from __future__ import annotations
import json
import logging
import time
from typing import Optional, Union
import redis.asyncio as redis
from redis.exceptions import RedisError
from app import config
logger = logging.getLogger("messenger.cache")
REVOKED = "revoked"
class SessionCache:
def __init__(self, url: Optional[str]):
self._client: Optional[redis.Redis] = None
self._down_until = 0.0
if url:
pool = redis.BlockingConnectionPool.from_url(
url,
max_connections=config.CACHE_POOL_MAX,
timeout=config.CACHE_TIMEOUT,
socket_timeout=config.CACHE_TIMEOUT,
socket_connect_timeout=config.CACHE_TIMEOUT,
decode_responses=True,
)
self._client = redis.Redis(connection_pool=pool)
@property
def enabled(self) -> bool:
return self._client is not None
def _usable(self) -> bool:
return self._client is not None and time.monotonic() >= self._down_until
def _failed(self, op: str, exc: Exception) -> None:
# Circuit breaker: one slow failure, then skip the cache for a few seconds.
self._down_until = time.monotonic() + config.CACHE_RETRY_AFTER
logger.warning("cache %s failed (%s); bypassing cache for %.0fs", op, type(exc).__name__, config.CACHE_RETRY_AFTER)
@staticmethod
def _key(token_hash: bytes) -> str:
return "session:" + token_hash.hex()
async def get(self, token_hash: bytes) -> Union[dict, str, None]:
if not self._usable():
return None
try:
raw = await self._client.get(self._key(token_hash))
except (RedisError, OSError) as exc:
self._failed("get", exc)
return None
if raw is None or raw == REVOKED:
return raw
try:
return json.loads(raw)
except ValueError:
return None
async def put(self, token_hash: bytes, entry: dict, ttl_seconds: int) -> None:
"""Fill after a PostgreSQL read. NX: never overwrite a logout tombstone."""
ttl = min(ttl_seconds, config.SESSION_CACHE_MAX_SECONDS)
if ttl <= 0 or not self._usable():
return
try:
await self._client.set(self._key(token_hash), json.dumps(entry), ex=ttl, nx=True)
except (RedisError, OSError) as exc:
self._failed("set", exc)
async def revoke(self, token_hash: bytes, ttl_seconds: int) -> None:
"""Tombstone instead of DEL: a concurrent fill that read PostgreSQL before the
revoke cannot re-insert the session afterwards (its SET NX loses).
Tried even while the breaker is open: logout is rare and correctness matters more."""
if self._client is None:
return
try:
await self._client.set(self._key(token_hash), REVOKED, ex=max(1, min(ttl_seconds, config.SESSION_CACHE_MAX_SECONDS)))
except (RedisError, OSError) as exc:
self._failed("revoke", exc)
async def ping(self) -> bool:
if self._client is None:
return False
try:
return bool(await self._client.ping())
except (RedisError, OSError):
return False
async def close(self) -> None:
if self._client is not None:
await self._client.aclose()
+46
View File
@@ -0,0 +1,46 @@
"""Runtime configuration from environment; secrets are read from *_FILE paths."""
from __future__ import annotations
import os
from typing import Optional
def _secret(name: str) -> Optional[str]:
"""NAME wins over NAME_FILE; NAME_FILE keeps the value out of `docker inspect`."""
value = os.environ.get(name)
if value:
return value.strip()
path = os.environ.get(name + "_FILE")
if path and os.path.exists(path):
with open(path, encoding="utf-8") as fh:
return fh.read().strip() or None
return None
def _int(name: str, default: int) -> int:
return int(os.environ.get(name, default))
def _float(name: str, default: float) -> float:
return float(os.environ.get(name, default))
DATABASE_URL = _secret("DATABASE_URL")
CACHE_URL = _secret("CACHE_URL")
SESSION_TTL_SECONDS = _int("SESSION_TTL_SECONDS", 3600)
# Upper bound for one cached session entry; PostgreSQL is re-checked after it.
SESSION_CACHE_MAX_SECONDS = _int("SESSION_CACHE_MAX_SECONDS", 300)
DB_POOL_MAX = _int("DB_POOL_MAX", 10)
DB_CONNECT_TIMEOUT = _float("DB_CONNECT_TIMEOUT", 3)
DB_ACQUIRE_TIMEOUT = _float("DB_ACQUIRE_TIMEOUT", 3)
DB_COMMAND_TIMEOUT = _float("DB_COMMAND_TIMEOUT", 5)
CACHE_TIMEOUT = _float("CACHE_TIMEOUT", 0.3)
CACHE_POOL_MAX = _int("CACHE_POOL_MAX", 20)
# After a cache error, skip the cache for this long instead of paying the timeout per request.
CACHE_RETRY_AFTER = _float("CACHE_RETRY_AFTER", 5)
# Argon2id hashing is CPU/RAM heavy: bound how many run at once.
PASSWORD_HASH_CONCURRENCY = _int("PASSWORD_HASH_CONCURRENCY", 4)
+24
View File
@@ -0,0 +1,24 @@
"""API error type shared by all layers."""
from __future__ import annotations
from typing import Dict, Optional
BEARER_CHALLENGE = 'Bearer realm="messenger"'
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
class ApiError(Exception):
def __init__(self, status_code: int, code: str, message: str, headers: Optional[Dict[str, str]] = None):
super().__init__(message)
self.status_code = status_code
self.code = code
self.message = message
self.headers = headers or {}
def unauthorized(message: str, challenge: str = BEARER_CHALLENGE) -> ApiError:
return ApiError(401, "unauthorized", message, {"WWW-Authenticate": challenge})
def unavailable() -> ApiError:
return ApiError(503, "unavailable", "service temporarily unavailable")
+234
View File
@@ -0,0 +1,234 @@
"""Lab 2: messenger API on PostgreSQL with Bearer sessions and a Valkey session cache."""
from __future__ import annotations
import logging
import uuid
from contextlib import asynccontextmanager
from typing import Optional
import asyncpg
from fastapi import Depends, FastAPI, Query, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from app import auth, config
from app.cache import SessionCache
from app.errors import ApiError
from app.models import Chat, ChatPage, CreateChat, CreateMessage, CreateUser, Health, Message, MessagePage, Session, User
from app.storage import Store
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("messenger")
store = Store()
cache = SessionCache(config.CACHE_URL)
@asynccontextmanager
async def lifespan(_app: FastAPI):
if not config.DATABASE_URL:
raise RuntimeError("DATABASE_URL or DATABASE_URL_FILE is required")
await store.open()
logger.info("session cache: %s", "valkey" if cache.enabled else "disabled")
yield
await cache.close()
await store.close()
app = FastAPI(title="MTUSI Messenger — lab2", lifespan=lifespan)
# ---------------------------------------------------------------------------
# Cross-cutting: request id + uniform error envelope
# ---------------------------------------------------------------------------
# PostgreSQL unreachable, restarting or pool exhausted -> bounded 503, never a hang.
DB_UNAVAILABLE = (
OSError, # includes ConnectionRefusedError and TimeoutError (pool acquire / connect)
asyncpg.PostgresConnectionError,
asyncpg.InterfaceError,
asyncpg.TooManyConnectionsError,
asyncpg.exceptions.OperatorInterventionError, # admin shutdown, cannot connect now
asyncpg.exceptions.QueryCanceledError, # statement timeout
)
def error_body(code: str, message: str, request_id: str) -> dict:
return {"error": {"code": code, "message": message, "request_id": request_id}}
def error_response(request: Request, status: int, code: str, message: str, headers: Optional[dict] = None) -> JSONResponse:
request_id = getattr(request.state, "request_id", "")
return JSONResponse(status_code=status, content=error_body(code, message, request_id), headers=headers)
@app.middleware("http")
async def request_id_middleware(request: Request, call_next):
request_id = uuid.uuid4().hex
request.state.request_id = request_id
try:
response = await call_next(request)
except Exception:
# Unhandled errors must be answered here: Starlette's own 500 handler runs
# outside this middleware and would drop the X-Request-Id header.
logger.exception("unhandled error for request_id=%s", request_id)
response = JSONResponse(status_code=500, content=error_body("internal_error", "internal error", request_id))
response.headers["X-Request-Id"] = request_id
return response
@app.exception_handler(ApiError)
async def api_error_handler(request: Request, exc: ApiError):
return error_response(request, exc.status_code, exc.code, exc.message, exc.headers)
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
return error_response(request, 400, "invalid_request", "request failed validation")
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
code = {404: "not_found", 405: "invalid_request", 415: "unsupported_media_type"}.get(exc.status_code, "invalid_request")
message = exc.detail if isinstance(exc.detail, str) else "request failed"
return error_response(request, exc.status_code, code, message)
async def db_unavailable_handler(request: Request, exc: Exception):
logger.warning("database unavailable for request_id=%s: %s", request.state.request_id, type(exc).__name__)
return error_response(request, 503, "unavailable", "service temporarily unavailable")
for _exc in DB_UNAVAILABLE:
app.add_exception_handler(_exc, db_unavailable_handler)
# ---------------------------------------------------------------------------
# Auth: Basic only on POST /auth/sessions, Bearer everywhere else.
# X-User-Id is ignored since lab2.
# ---------------------------------------------------------------------------
async def current_user(request: Request) -> dict:
return await auth.authenticate(store, cache, request.headers.get("Authorization"))
def parse_uuid(value: str, field: str) -> uuid.UUID:
try:
return uuid.UUID(value)
except ValueError:
raise ApiError(400, "invalid_request", f"{field} is not a valid UUID") from None
def not_found() -> ApiError:
return ApiError(404, "not_found", "chat not found")
# ---------------------------------------------------------------------------
# Health
# ---------------------------------------------------------------------------
@app.get("/health/live", response_model=Health)
async def liveness():
return Health()
@app.get("/health/ready", response_model=Health)
async def readiness():
# PostgreSQL is critical; Valkey is not (the API bypasses the cache without it).
try:
await store.ping()
except DB_UNAVAILABLE:
raise ApiError(503, "unavailable", "database is not available") from None
return Health()
# ---------------------------------------------------------------------------
# Users and sessions
# ---------------------------------------------------------------------------
@app.post("/api/v1/users", response_model=User, status_code=201)
async def register_user(body: CreateUser):
if not body.display_name.strip() or not body.password.strip():
raise ApiError(400, "invalid_request", "display_name and password must not be blank")
password_hash = await auth.hash_password(body.password)
return await store.create_user(body.username, body.display_name, password_hash)
@app.get("/api/v1/users/me", response_model=User)
async def current_user_endpoint(user: dict = Depends(current_user)):
return user
@app.post("/api/v1/auth/sessions", response_model=Session, status_code=201)
async def create_session(request: Request):
return await auth.login(store, request.headers.get("Authorization"))
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def delete_session(request: Request):
await auth.logout(store, cache, request.headers.get("Authorization"))
return Response(status_code=204)
# ---------------------------------------------------------------------------
# Chats
# ---------------------------------------------------------------------------
@app.post("/api/v1/chats", response_model=Chat, status_code=201)
async def create_chat(body: CreateChat, user: dict = Depends(current_user)):
if not body.title.strip():
raise ApiError(400, "invalid_request", "title must not be blank")
if len(set(body.member_ids)) != len(body.member_ids):
raise ApiError(400, "invalid_request", "member_ids must not contain duplicates")
if uuid.UUID(user["id"]) not in body.member_ids:
raise ApiError(400, "invalid_request", "caller must be a member of the chat")
return await store.create_chat(body.title, list(body.member_ids))
@app.get("/api/v1/chats", response_model=ChatPage)
async def list_chats(
user: dict = Depends(current_user),
limit: int = Query(default=50, ge=1, le=100),
cursor: Optional[str] = Query(default=None, min_length=1),
):
return await store.list_chats(uuid.UUID(user["id"]), limit, cursor)
@app.get("/api/v1/chats/{chat_id}", response_model=Chat)
async def get_chat(chat_id: str, user: dict = Depends(current_user)):
chat = await store.get_chat_for_member(parse_uuid(chat_id, "chat_id"), uuid.UUID(user["id"]))
if chat is None:
raise not_found()
return chat
# ---------------------------------------------------------------------------
# Messages
# ---------------------------------------------------------------------------
@app.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
async def create_message(chat_id: str, body: CreateMessage, user: dict = Depends(current_user)):
chat_uuid = parse_uuid(chat_id, "chat_id")
if not body.text.strip():
# Access is checked before content: an outsider gets 404 even for a blank text.
if not await store.is_member(chat_uuid, uuid.UUID(user["id"])):
raise not_found()
raise ApiError(400, "invalid_request", "text must not be blank")
message = await store.create_message(chat_uuid, uuid.UUID(user["id"]), body.text)
if message is None:
raise not_found()
return message
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
async def list_messages(
chat_id: str,
user: dict = Depends(current_user),
limit: int = Query(default=50, ge=1, le=100),
cursor: Optional[str] = Query(default=None, min_length=1),
):
chat_uuid = parse_uuid(chat_id, "chat_id")
if not await store.is_member(chat_uuid, uuid.UUID(user["id"])):
raise not_found()
return await store.list_messages(chat_uuid, limit, cursor)
+68
View File
@@ -0,0 +1,68 @@
"""Apply versioned SQL migrations from migrations/; safe to run repeatedly and concurrently.
Usage: python -m app.migrate
"""
from __future__ import annotations
import asyncio
import logging
import sys
from pathlib import Path
import asyncpg
from app import config
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("migrate")
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations"
# Arbitrary constant: serialises concurrent runners (e.g. several API replicas in lab3).
LOCK_ID = 2026_0002
async def connect_with_retry(attempts: int = 30) -> asyncpg.Connection:
for attempt in range(1, attempts + 1):
try:
return await asyncpg.connect(config.DATABASE_URL, timeout=config.DB_CONNECT_TIMEOUT)
except (OSError, asyncpg.PostgresError, asyncpg.InterfaceError) as exc:
logger.warning("database not reachable (attempt %d/%d): %s", attempt, attempts, type(exc).__name__)
await asyncio.sleep(1)
raise SystemExit("database is not reachable")
async def migrate() -> int:
if not config.DATABASE_URL:
raise SystemExit("DATABASE_URL or DATABASE_URL_FILE is required")
conn = await connect_with_retry()
applied_now = 0
try:
await conn.execute("SELECT pg_advisory_lock($1)", LOCK_ID)
await conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT now()
)
"""
)
done = {r["version"] for r in await conn.fetch("SELECT version FROM schema_migrations")}
for path in sorted(MIGRATIONS_DIR.glob("*.sql")):
version = path.stem
if version in done:
continue
logger.info("applying %s", version)
async with conn.transaction():
await conn.execute(path.read_text(encoding="utf-8"))
await conn.execute("INSERT INTO schema_migrations (version) VALUES ($1)", version)
applied_now += 1
logger.info("migrations up to date: %d applied now, %d before", applied_now, len(done))
finally:
await conn.execute("SELECT pg_advisory_unlock($1)", LOCK_ID)
await conn.close()
return applied_now
if __name__ == "__main__":
asyncio.run(migrate())
sys.exit(0)
+73
View File
@@ -0,0 +1,73 @@
"""Pydantic request/response schemas mirroring contracts/openapi.json."""
from __future__ import annotations
import uuid
from typing import List, Optional
from pydantic import BaseModel, ConfigDict, Field
USERNAME_PATTERN = r"^[a-z0-9_]{3,32}$"
class CreateUser(BaseModel):
model_config = ConfigDict(extra="forbid")
username: str = Field(pattern=USERNAME_PATTERN)
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
class User(BaseModel):
id: uuid.UUID
username: str
display_name: str
created_at: str
class CreateChat(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str = Field(min_length=1, max_length=100)
member_ids: List[uuid.UUID] = Field(min_length=1, max_length=100)
class Chat(BaseModel):
id: uuid.UUID
title: str
member_ids: List[uuid.UUID]
created_at: str
class ChatPage(BaseModel):
items: List[Chat]
next_cursor: Optional[str] = None
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(max_length=4000)
class Message(BaseModel):
id: uuid.UUID
chat_id: uuid.UUID
sender_id: uuid.UUID
text: str
created_at: str
class MessagePage(BaseModel):
items: List[Message]
next_cursor: Optional[str] = None
class Session(BaseModel):
token: str
token_type: str = "Bearer"
expires_at: str
user: User
class Health(BaseModel):
status: str = "ok"
+288
View File
@@ -0,0 +1,288 @@
"""PostgreSQL repository. Every query is parameterised; PostgreSQL is the source of truth."""
from __future__ import annotations
import base64
import json
import uuid
from datetime import datetime, timezone
from typing import List, Optional, Tuple
import asyncpg
from app import config
from app.errors import ApiError
def fmt_ts(value: datetime) -> str:
# Always 6 fractional digits: exact round trip with PostgreSQL microseconds.
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
def user_row(row: asyncpg.Record) -> dict:
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": fmt_ts(row["created_at"]),
}
def chat_row(row: asyncpg.Record) -> dict:
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": [str(m) for m in row["member_ids"]],
"created_at": fmt_ts(row["created_at"]),
}
def message_row(row: asyncpg.Record) -> dict:
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"created_at": fmt_ts(row["created_at"]),
}
# ---------------------------------------------------------------------------
# Opaque keyset cursor bound to one resource
# ---------------------------------------------------------------------------
def encode_cursor(resource: str, created_at: str, item_id: str) -> str:
payload = json.dumps({"r": resource, "t": created_at, "i": item_id}, separators=(",", ":"))
return base64.urlsafe_b64encode(payload.encode("utf-8")).decode("ascii").rstrip("=")
def decode_cursor(resource: str, cursor: str) -> Tuple[datetime, uuid.UUID]:
try:
padded = cursor + "=" * (-len(cursor) % 4)
payload = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")).decode("utf-8"))
if payload.get("r") != resource:
raise ValueError("cursor belongs to a different resource")
created_at = datetime.fromisoformat(payload["t"].replace("Z", "+00:00"))
if created_at.tzinfo is None:
raise ValueError("cursor time has no timezone")
return created_at, uuid.UUID(payload["i"])
except Exception as exc: # noqa: BLE001 - any malformed cursor is a 400
raise ApiError(400, "invalid_request", "invalid cursor") from exc
def page_of(items: List[dict], resource: str, limit: int) -> dict:
"""Queries fetch limit+1 rows: the extra row only tells whether a next page exists."""
page = items[:limit]
next_cursor = None
if len(items) > limit:
last = page[-1]
next_cursor = encode_cursor(resource, last["created_at"], last["id"])
return {"items": page, "next_cursor": next_cursor}
# ---------------------------------------------------------------------------
# Repository
# ---------------------------------------------------------------------------
class Store:
def __init__(self):
self.pool: Optional[asyncpg.Pool] = None
async def open(self) -> None:
# min_size=0: connections open on demand, so the API starts even while
# PostgreSQL is down and readiness reports 503 until it is back.
self.pool = await asyncpg.create_pool(
config.DATABASE_URL,
min_size=0,
max_size=config.DB_POOL_MAX,
timeout=config.DB_CONNECT_TIMEOUT,
command_timeout=config.DB_COMMAND_TIMEOUT,
max_inactive_connection_lifetime=60,
)
async def close(self) -> None:
if self.pool is not None:
await self.pool.close()
def acquire(self):
return self.pool.acquire(timeout=config.DB_ACQUIRE_TIMEOUT)
async def ping(self) -> bool:
async with self.acquire() as conn:
return await conn.fetchval("SELECT 1") == 1
# -- users --------------------------------------------------------------
async def create_user(self, username: str, display_name: str, password_hash: str) -> dict:
async with self.acquire() as conn:
try:
row = await conn.fetchrow(
"""
INSERT INTO users (id, username, display_name, password_hash)
VALUES ($1, $2, $3, $4)
RETURNING id, username, display_name, created_at
""",
uuid.uuid4(), username, display_name, password_hash,
)
except asyncpg.UniqueViolationError:
# The UNIQUE constraint, not a prior SELECT, decides concurrent registrations.
raise ApiError(409, "conflict", "username already taken") from None
return user_row(row)
async def get_credentials(self, username: str) -> Optional[asyncpg.Record]:
async with self.acquire() as conn:
return await conn.fetchrow(
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1",
username,
)
# -- sessions -----------------------------------------------------------
async def create_session(self, token_hash: bytes, user_id: uuid.UUID, ttl_seconds: int) -> datetime:
async with self.acquire() as conn:
return await conn.fetchval(
"""
INSERT INTO sessions (token_hash, user_id, expires_at)
VALUES ($1, $2, clock_timestamp() + make_interval(secs => $3))
RETURNING expires_at
""",
token_hash, user_id, float(ttl_seconds),
)
async def find_session(self, token_hash: bytes) -> Optional[asyncpg.Record]:
"""Only a live session: not revoked and not expired by the database clock."""
async with self.acquire() as conn:
return await conn.fetchrow(
"""
SELECT s.expires_at, u.id, u.username, u.display_name, u.created_at
FROM sessions s JOIN users u ON u.id = s.user_id
WHERE s.token_hash = $1 AND s.revoked_at IS NULL AND s.expires_at > clock_timestamp()
""",
token_hash,
)
async def revoke_session(self, token_hash: bytes) -> Optional[datetime]:
async with self.acquire() as conn:
return await conn.fetchval(
"""
UPDATE sessions SET revoked_at = clock_timestamp()
WHERE token_hash = $1 AND revoked_at IS NULL AND expires_at > clock_timestamp()
RETURNING expires_at
""",
token_hash,
)
# -- chats --------------------------------------------------------------
async def create_chat(self, title: str, member_ids: List[uuid.UUID]) -> dict:
"""Chat and all memberships commit together or not at all.
Unknown members are detected by the foreign key inside the transaction, so a
failure after the chat row was inserted really exercises the rollback."""
chat_id = uuid.uuid4()
async with self.acquire() as conn:
try:
async with conn.transaction():
row = await conn.fetchrow(
"INSERT INTO chats (id, title) VALUES ($1, $2) RETURNING id, title, created_at",
chat_id, title,
)
await conn.execute(
"""
INSERT INTO chat_members (chat_id, user_id, position)
SELECT $1, m.user_id, m.ord - 1
FROM unnest($2::uuid[]) WITH ORDINALITY AS m(user_id, ord)
""",
chat_id, member_ids,
)
except asyncpg.ForeignKeyViolationError:
raise ApiError(400, "invalid_request", "unknown member in member_ids") from None
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": [str(m) for m in member_ids],
"created_at": fmt_ts(row["created_at"]),
}
async def get_chat_for_member(self, chat_id: uuid.UUID, user_id: uuid.UUID) -> Optional[dict]:
async with self.acquire() as conn:
row = await conn.fetchrow(
"""
SELECT c.id, c.title, c.created_at,
array_agg(m.user_id ORDER BY m.position) AS member_ids
FROM chats c JOIN chat_members m ON m.chat_id = c.id
WHERE c.id = $1
AND EXISTS (SELECT 1 FROM chat_members me WHERE me.chat_id = c.id AND me.user_id = $2)
GROUP BY c.id
""",
chat_id, user_id,
)
return chat_row(row) if row else None
async def list_chats(self, user_id: uuid.UUID, limit: int, cursor: Optional[str]) -> dict:
after_t, after_i = decode_cursor("chats", cursor) if cursor else (None, None)
async with self.acquire() as conn:
rows = await conn.fetch(
"""
SELECT c.id, c.title, c.created_at,
array_agg(m.user_id ORDER BY m.position) AS member_ids
FROM chat_members me
JOIN chats c ON c.id = me.chat_id
JOIN chat_members m ON m.chat_id = c.id
WHERE me.user_id = $1
AND ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3::uuid))
GROUP BY c.id
ORDER BY c.created_at, c.id
LIMIT $4
""",
user_id, after_t, after_i, limit + 1,
)
return page_of([chat_row(r) for r in rows], "chats", limit)
async def is_member(self, chat_id: uuid.UUID, user_id: uuid.UUID) -> bool:
async with self.acquire() as conn:
return bool(await conn.fetchval(
"SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)",
chat_id, user_id,
))
# -- messages -----------------------------------------------------------
async def create_message(self, chat_id: uuid.UUID, sender_id: uuid.UUID, text: str) -> Optional[dict]:
"""Membership check and insert in one statement; None means "no such chat for you"."""
async with self.acquire() as conn:
row = await conn.fetchrow(
"""
INSERT INTO messages (id, chat_id, sender_id, text)
SELECT $1, $2, $3, $4
WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3)
RETURNING id, chat_id, sender_id, text, created_at
""",
uuid.uuid4(), chat_id, sender_id, text,
)
return message_row(row) if row else None
async def list_messages(self, chat_id: uuid.UUID, limit: int, cursor: Optional[str]) -> dict:
resource = str(chat_id)
async with self.acquire() as conn:
if cursor:
after_t, after_i = decode_cursor(resource, cursor)
rows = await conn.fetch(
"""
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
ORDER BY created_at, id
LIMIT $4
""",
chat_id, after_t, after_i, limit + 1,
)
else:
rows = await conn.fetch(
"""
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = $1
ORDER BY created_at, id
LIMIT $2
""",
chat_id, limit + 1,
)
return page_of([message_row(r) for r in rows], resource, limit)