выполнение ЛР3 на 4

This commit is contained in:
Ilya
2026-10-21 12:20:11 +03:00
parent 0ab3a341aa
commit 6f4f74d691
37 changed files with 2854 additions and 15 deletions
View File
+113
View File
@@ -0,0 +1,113 @@
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, ApiError, unauthorized
from app.storage import Store, fmt_ts, user_row
_hasher = PasswordHasher()
_hash_slots = asyncio.Semaphore(config.PASSWORD_HASH_CONCURRENCY)
_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:
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(":")
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)
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:
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:
await authenticate(store, cache, header)
digest = token_digest(parse_bearer(header))
expires_at = await store.revoke_session(digest)
if expires_at is None:
raise unauthorized("session expired or revoked")
remaining = int((expires_at - datetime.now(timezone.utc)).total_seconds()) + 1
if not await cache.revoke(digest, remaining):
raise ApiError(503, "unavailable", "logout not confirmed by session cache, retry later")
+125
View File
@@ -0,0 +1,125 @@
from __future__ import annotations
import asyncio
import json
import logging
import time
from typing import Dict, Optional, Set, 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
self._pending_revokes: Dict[bytes, float] = {}
self._retry_tasks: Set[asyncio.Task] = set()
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:
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()
def _revoke_pending(self, token_hash: bytes) -> bool:
deadline = self._pending_revokes.get(token_hash)
if deadline is None:
return False
if time.monotonic() >= deadline:
self._pending_revokes.pop(token_hash, None)
return False
return True
async def get(self, token_hash: bytes) -> Union[dict, str, None]:
if not self._usable() or self._revoke_pending(token_hash):
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:
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 _write_tombstone(self, token_hash: bytes, ttl_seconds: int) -> bool:
try:
await self._client.set(self._key(token_hash), REVOKED, ex=max(1, min(ttl_seconds, config.SESSION_CACHE_MAX_SECONDS)))
return True
except (RedisError, OSError) as exc:
self._failed("revoke", exc)
return False
async def revoke(self, token_hash: bytes, ttl_seconds: int) -> bool:
if self._client is None:
return True
if await self._write_tombstone(token_hash, ttl_seconds):
return True
deadline = time.monotonic() + config.SESSION_CACHE_MAX_SECONDS + 1
self._pending_revokes[token_hash] = deadline
task = asyncio.create_task(self._retry_revoke(token_hash, ttl_seconds, deadline))
self._retry_tasks.add(task)
task.add_done_callback(self._retry_tasks.discard)
return False
async def _retry_revoke(self, token_hash: bytes, ttl_seconds: int, deadline: float) -> None:
while time.monotonic() < deadline:
await asyncio.sleep(1)
remaining = int(deadline - time.monotonic())
if remaining > 0 and await self._write_tombstone(token_hash, min(ttl_seconds, remaining)):
logger.info("revocation tombstone written after cache recovery")
break
self._pending_revokes.pop(token_hash, None)
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:
for task in list(self._retry_tasks):
task.cancel()
if self._client is not None:
await self._client.aclose()
+47
View File
@@ -0,0 +1,47 @@
from __future__ import annotations
import os
import secrets
from typing import Optional
def _secret(name: str) -> Optional[str]:
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)
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)
CACHE_RETRY_AFTER = _float("CACHE_RETRY_AFTER", 5)
PASSWORD_HASH_CONCURRENCY = _int("PASSWORD_HASH_CONCURRENCY", 4)
IDEMPOTENCY_TTL_SECONDS = _int("IDEMPOTENCY_TTL_SECONDS", 86400)
INSTANCE_ID = "api-" + secrets.token_hex(4)
INSTANCE_ID_FILE = os.environ.get("INSTANCE_ID_FILE", "/tmp/instance-id")
+23
View File
@@ -0,0 +1,23 @@
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")
+224
View File
@@ -0,0 +1,224 @@
from __future__ import annotations
import hashlib
import json
import logging
import re
import uuid
from contextlib import asynccontextmanager
from typing import Optional
import asyncpg
from fastapi import Depends, FastAPI, Header, 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")
try:
with open(config.INSTANCE_ID_FILE, "w", encoding="ascii") as fh:
fh.write(config.INSTANCE_ID + "\n")
except OSError:
logger.warning("cannot write %s", config.INSTANCE_ID_FILE)
logger.info("instance id: %s", config.INSTANCE_ID)
yield
await cache.close()
await store.close()
app = FastAPI(title="MTUSI Messenger — lab3", lifespan=lifespan)
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
DB_UNAVAILABLE = (
OSError,
asyncpg.PostgresConnectionError,
asyncpg.InterfaceError,
asyncpg.TooManyConnectionsError,
asyncpg.exceptions.OperatorInterventionError,
asyncpg.exceptions.QueryCanceledError,
)
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:
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
response.headers["X-Instance-Id"] = config.INSTANCE_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)
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")
@app.get("/health/live", response_model=Health)
async def liveness():
return Health()
@app.get("/health/ready", response_model=Health)
async def readiness():
try:
await store.ping()
except DB_UNAVAILABLE:
raise ApiError(503, "unavailable", "database is not available") from None
return Health()
@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)
@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
@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),
idempotency_key: Optional[str] = Header(default=None, alias="Idempotency-Key"),
):
chat_uuid = parse_uuid(chat_id, "chat_id")
if idempotency_key is None or not IDEMPOTENCY_KEY_RE.fullmatch(idempotency_key):
raise ApiError(400, "invalid_request", "Idempotency-Key header is required: [A-Za-z0-9._:-]{1,128}")
if not body.text.strip():
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")
canonical = json.dumps(body.model_dump(mode="json"), sort_keys=True, separators=(",", ":"), ensure_ascii=False)
request_hash = hashlib.sha256(canonical.encode("utf-8")).digest()
message = await store.create_message(chat_uuid, uuid.UUID(user["id"]), body.text, idempotency_key, request_hash)
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)
+63
View File
@@ -0,0 +1,63 @@
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"
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)
+72
View File
@@ -0,0 +1,72 @@
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"
+313
View File
@@ -0,0 +1,313 @@
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:
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"]),
}
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:
raise ApiError(400, "invalid_request", "invalid cursor") from exc
def page_of(items: List[dict], resource: str, limit: int) -> dict:
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}
class Store:
def __init__(self):
self.pool: Optional[asyncpg.Pool] = None
async def open(self) -> None:
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
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:
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,
)
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]:
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,
)
async def create_chat(self, title: str, member_ids: List[uuid.UUID]) -> dict:
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,
))
async def create_message(
self, chat_id: uuid.UUID, sender_id: uuid.UUID, text: str, key: str, request_hash: bytes
) -> Optional[dict]:
async with self.acquire() as conn:
for _ in range(3):
try:
async with conn.transaction():
await conn.execute(
"""
DELETE FROM idempotency_keys
WHERE user_id = $1 AND chat_id = $2 AND key = $3
AND created_at < clock_timestamp() - make_interval(secs => $4)
""",
sender_id, chat_id, key, float(config.IDEMPOTENCY_TTL_SECONDS),
)
message_id = uuid.uuid4()
claimed = await conn.fetchval(
"""
INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id)
SELECT $1, $2, $3, $4, $5
WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $1)
ON CONFLICT (user_id, chat_id, key) DO NOTHING
RETURNING message_id
""",
sender_id, chat_id, key, request_hash, message_id,
)
if claimed is not None:
row = await conn.fetchrow(
"""
INSERT INTO messages (id, chat_id, sender_id, text)
VALUES ($1, $2, $3, $4)
RETURNING id, chat_id, sender_id, text, created_at
""",
message_id, chat_id, sender_id, text,
)
return message_row(row)
except asyncpg.ForeignKeyViolationError:
return None
existing = await conn.fetchrow(
"""
SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM idempotency_keys k
JOIN messages m ON m.id = k.message_id
JOIN chat_members cm ON cm.chat_id = k.chat_id AND cm.user_id = k.user_id
WHERE k.user_id = $1 AND k.chat_id = $2 AND k.key = $3
""",
sender_id, chat_id, key,
)
if existing is None:
is_member = await conn.fetchval(
"SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)",
chat_id, sender_id,
)
if not is_member:
return None
continue
if existing["request_hash"] != request_hash:
raise ApiError(409, "conflict", "Idempotency-Key was already used with a different request")
return message_row(existing)
raise ApiError(503, "unavailable", "could not settle idempotent request, retry with the same key")
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)