Мессенджер с Postgres, Redis, Valkey

This commit is contained in:
Queenfish
2026-10-08 13:21:48 +03:00
parent 65003b6119
commit 6bfbcf74fc
41 changed files with 2624 additions and 24 deletions
View File
View File
+104
View File
@@ -0,0 +1,104 @@
from fastapi import APIRouter, Header, HTTPException, Request, Response
from fastapi.responses import JSONResponse
from app.security import (
parse_basic,
verify_password,
new_token,
session_expires_at,
get_current_user,
)
from app.config import config
from app.models import Session
router = APIRouter(tags=["auth"])
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
def error_response(
status: int, code: str, message: str, request_id: str, headers=None,
) -> JSONResponse:
return JSONResponse(
status_code=status,
content={
"error": {
"code": code,
"message": message,
"request_id": request_id,
}
},
headers=headers or {},
)
@router.post("/auth/sessions", response_model=Session, status_code=201)
async def create_session(
request: Request,
authorization: str | None = Header(default=None),
):
storage = request.app.state.storage
session_store = request.app.state.session_store
rid = request.state.request_id
try:
username, password = parse_basic(authorization)
except HTTPException:
return error_response(
401,
"unauthorized",
"invalid credentials",
rid,
headers={"WWW-Authenticate": BASIC_CHALLENGE},
)
user_row = await storage.get_user_by_username(username)
if user_row is None or not verify_password(password, user_row["password_hash"]):
return error_response(
401,
"unauthorized",
"invalid credentials",
rid,
headers={"WWW-Authenticate": BASIC_CHALLENGE},
)
token = new_token()
expires_at = session_expires_at(config.SESSION_TTL_SECONDS)
await session_store.create(token, str(user_row["id"]), expires_at)
user = {
"id": str(user_row["id"]),
"username": user_row["username"],
"display_name": user_row["display_name"],
"created_at": (
user_row["created_at"]
.isoformat()
.replace("+00:00", "Z")
),
}
return {
"token": token,
"token_type": "Bearer",
"expires_at": expires_at.isoformat().replace("+00:00", "Z"),
"user": user,
}
@router.delete("/auth/sessions/current", status_code=204)
async def revoke_session(
request: Request,
authorization: str | None = Header(default=None),
):
rid = request.state.request_id
try:
_, token = await get_current_user(request, authorization)
except HTTPException:
return error_response(
401,
"unauthorized",
"unauthorized",
rid,
headers={"WWW-Authenticate": BEARER_CHALLENGE},
)
await request.app.state.session_store.delete(token)
return Response(status_code=204)
+148
View File
@@ -0,0 +1,148 @@
from fastapi import APIRouter, Header, HTTPException, Query, Request
from fastapi.responses import JSONResponse
from app.models import (
Chat, CreateChat, Message, CreateMessage, ChatPage, MessagePage,
)
from app.security import get_current_user
router = APIRouter(tags=["chats"])
BEARER_CHALLENGE = 'Bearer realm="messenger"'
def error_response(
status: int, code: str, message: str, request_id: str, headers=None,
) -> JSONResponse:
return JSONResponse(
status_code=status,
content={
"error": {
"code": code,
"message": message,
"request_id": request_id,
}
},
headers=headers or {},
)
async def resolve_actor(request: Request, authorization: str | None):
rid = request.state.request_id
try:
user, _ = await get_current_user(request, authorization)
except HTTPException:
return None, error_response(
401,
"unauthorized",
"unauthorized",
rid,
headers={"WWW-Authenticate": BEARER_CHALLENGE},
)
return user, None
@router.post("/chats", response_model=Chat, status_code=201)
async def create_chat(
data: CreateChat,
request: Request,
authorization: str | None = Header(default=None),
):
rid = request.state.request_id
actor, err = await resolve_actor(request, authorization)
if err is not None:
return err
storage = request.app.state.storage
try:
chat = await storage.create_chat(
data.title, data.member_ids, actor["id"],
)
return chat
except ValueError as e:
msg = str(e)
if msg == "invalid_member":
return error_response(400, "invalid_request", "unknown member", rid)
if msg == "creator_not_member":
return error_response(
400, "invalid_request", "creator must be a member", rid,
)
return error_response(400, "invalid_request", "bad request", rid)
@router.get("/chats", response_model=ChatPage)
async def list_chats(
request: Request,
authorization: str | None = Header(default=None),
limit: int = Query(50, ge=1, le=100),
cursor: str | None = Query(None),
):
rid = request.state.request_id
actor, err = await resolve_actor(request, authorization)
if err is not None:
return err
try:
items, next_cursor = await request.app.state.storage.list_chats(
actor["id"], limit, cursor,
)
except ValueError:
return error_response(400, "invalid_request", "bad cursor", rid)
return {"items": items, "next_cursor": next_cursor}
@router.get("/chats/{chat_id}", response_model=Chat)
async def get_chat(
chat_id: str,
request: Request,
authorization: str | None = Header(default=None),
):
rid = request.state.request_id
actor, err = await resolve_actor(request, authorization)
if err is not None:
return err
chat = await request.app.state.storage.get_chat(chat_id, actor["id"])
if chat is None:
return error_response(404, "not_found", "chat not found", rid)
return chat
@router.post("/chats/{chat_id}/messages", response_model=Message, status_code=201)
async def create_message(
chat_id: str,
data: CreateMessage,
request: Request,
authorization: str | None = Header(default=None),
):
rid = request.state.request_id
actor, err = await resolve_actor(request, authorization)
if err is not None:
return err
try:
msg = await request.app.state.storage.add_message(
chat_id, actor["id"], data.text,
)
return msg
except ValueError:
return error_response(404, "not_found", "chat not found", rid)
@router.get("/chats/{chat_id}/messages", response_model=MessagePage)
async def list_messages(
chat_id: str,
request: Request,
authorization: str | None = Header(default=None),
limit: int = Query(50, ge=1, le=100),
cursor: str | None = Query(None),
):
rid = request.state.request_id
actor, err = await resolve_actor(request, authorization)
if err is not None:
return err
try:
items, next_cursor = await request.app.state.storage.list_messages(
chat_id, actor["id"], limit, cursor,
)
except ValueError as e:
if str(e) == "bad_cursor":
return error_response(400, "invalid_request", "bad cursor", rid)
return error_response(404, "not_found", "chat not found", rid)
return {"items": items, "next_cursor": next_cursor}
+53
View File
@@ -0,0 +1,53 @@
import asyncio
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
router = APIRouter(tags=["health"])
@router.get("/health/live")
async def liveness():
return {"status": "ok"}
async def _check_postgres(request: Request) -> None:
async with request.app.state.storage._pool.acquire() as conn:
await conn.fetchval("SELECT 1")
async def _check_redis(request: Request) -> None:
store = request.app.state.session_store
if hasattr(store, "_client"):
await store._client.ping()
@router.get("/health/ready")
async def readiness(request: Request):
rid = getattr(request.state, "request_id", "")
try:
await asyncio.wait_for(_check_postgres(request), timeout=2.0)
except Exception:
return JSONResponse(
status_code=503,
content={
"error": {
"code": "unavailable",
"message": "db unavailable",
"request_id": rid,
}
},
)
try:
await asyncio.wait_for(_check_redis(request), timeout=2.0)
except Exception:
return JSONResponse(
status_code=503,
content={
"error": {
"code": "unavailable",
"message": "cache unavailable",
"request_id": rid,
}
},
)
return {"status": "ok"}
+56
View File
@@ -0,0 +1,56 @@
from fastapi import APIRouter, Header, HTTPException, Request
from fastapi.responses import JSONResponse
from app.models import User, CreateUser
from app.security import hash_password, get_current_user
router = APIRouter(tags=["users"])
def error_response(
status: int, code: str, message: str, request_id: str, headers=None,
) -> JSONResponse:
return JSONResponse(
status_code=status,
content={
"error": {
"code": code,
"message": message,
"request_id": request_id,
}
},
headers=headers or {},
)
@router.post("/users", response_model=User, status_code=201)
async def register_user(data: CreateUser, request: Request):
storage = request.app.state.storage
rid = request.state.request_id
password_hash = hash_password(data.password)
try:
user = await storage.create_user(
data.username, data.display_name, password_hash,
)
return user
except ValueError:
return error_response(409, "conflict", "username already taken", rid)
@router.get("/users/me", response_model=User)
async def current_user(
request: Request,
authorization: str | None = Header(default=None),
):
rid = request.state.request_id
try:
user, _ = await get_current_user(request, authorization)
except HTTPException:
return error_response(
401,
"unauthorized",
"unauthorized",
rid,
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
return user
+60
View File
@@ -0,0 +1,60 @@
import json
from typing import Optional
import redis.asyncio as redis
from app.config import config
CACHE_TTL_SECONDS = 30
class Cache:
def __init__(self, client: redis.Redis) -> None:
self._client = client
async def get_json(self, key: str) -> Optional[dict]:
raw = await self._client.get(key)
if raw is None:
return None
try:
return json.loads(raw)
except json.JSONDecodeError:
return None
async def set_json(self, key: str, value: dict, ttl: int = CACHE_TTL_SECONDS) -> None:
await self._client.set(key, json.dumps(value), ex=ttl)
async def delete(self, key: str) -> None:
await self._client.delete(key)
async def invalidate_chat(self, chat_id: str) -> None:
"""Удалить все ключи, связанные с чатом (история)."""
pattern = f"messages:{chat_id}:*"
cursor = 0
while True:
cursor, keys = await self._client.scan(cursor=cursor, match=pattern, count=100)
if keys:
await self._client.delete(*keys)
if cursor == 0:
break
async def try_lock(self, key: str, ttl: int = 5) -> bool:
"""Атомарно установить ключ. True — если установили мы."""
result = await self._client.set(key, "1", nx=True, ex=ttl)
return bool(result)
async def unlock(self, key: str) -> None:
await self._client.delete(key)
async def close(self) -> None:
await self._client.aclose()
def make_cache() -> Cache:
client = redis.from_url(
config.CACHE_URL,
decode_responses=True,
socket_connect_timeout=2,
socket_timeout=2,
)
return Cache(client)
+19
View File
@@ -0,0 +1,19 @@
import os
class Config:
DATABASE_URL: str = os.getenv(
"DATABASE_URL",
"postgresql://messenger:messenger@localhost:5432/messenger",
)
SESSION_TTL_SECONDS: int = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
APP_HOST: str = os.getenv("APP_HOST", "0.0.0.0")
APP_PORT: int = int(os.getenv("APP_PORT", "8080"))
SESSION_STORE: str = os.getenv("SESSION_STORE", "postgres")
CACHE_URL: str = os.getenv(
"CACHE_URL",
"redis://valkey:6379/0",
)
config = Config()
+30
View File
@@ -0,0 +1,30 @@
import asyncpg
from app.config import config
class Database:
def __init__(self) -> None:
self._pool: asyncpg.Pool | None = None
async def connect(self) -> None:
self._pool = await asyncpg.create_pool(
config.DATABASE_URL,
min_size=1,
max_size=10,
command_timeout=5,
timeout=5,
)
async def close(self) -> None:
if self._pool is not None:
await self._pool.close()
self._pool = None
@property
def pool(self) -> asyncpg.Pool:
if self._pool is None:
raise RuntimeError("database is not connected")
return self._pool
db = Database()
+77
View File
@@ -0,0 +1,77 @@
import uuid
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from app.db import db
from app.migrations import apply_migrations
from app.storage import Storage
from app.session_store import make_session_store
from app.cache import make_cache
from app.api import health, users, auth, chats
@asynccontextmanager
async def lifespan(app: FastAPI):
await db.connect()
await apply_migrations(db.pool)
app.state.cache = make_cache()
app.state.storage = Storage(db.pool, app.state.cache)
app.state.session_store = make_session_store(db.pool)
await app.state.session_store.delete_expired()
yield
await app.state.cache.close()
await app.state.session_store.close()
await db.close()
app = FastAPI(title="MTUSI Messenger", version="1.3.0", lifespan=lifespan)
@app.middleware("http")
async def request_context(request: Request, call_next):
rid = request.headers.get("X-Request-Id") or uuid.uuid4().hex
request.state.request_id = rid
response = await call_next(request)
response.headers["X-Request-Id"] = rid
return response
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
rid = getattr(request.state, "request_id", uuid.uuid4().hex)
return JSONResponse(
status_code=400,
content={
"error": {
"code": "invalid_request",
"message": "validation error",
"request_id": rid,
}
},
headers={"X-Request-Id": rid},
)
@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception):
rid = getattr(request.state, "request_id", uuid.uuid4().hex)
return JSONResponse(
status_code=500,
content={
"error": {
"code": "internal_error",
"message": "internal error",
"request_id": rid,
}
},
headers={"X-Request-Id": rid},
)
app.include_router(health.router)
app.include_router(users.router, prefix="/api/v1")
app.include_router(auth.router, prefix="/api/v1")
app.include_router(chats.router, prefix="/api/v1")
+31
View File
@@ -0,0 +1,31 @@
from pathlib import Path
import asyncpg
MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
async def apply_migrations(pool: asyncpg.Pool) -> None:
async with pool.acquire() as conn:
await conn.execute(
"""
CREATE TABLE IF NOT EXISTS applied_migrations (
name TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
"""
)
applied = {
row["name"]
for row in await conn.fetch("SELECT name FROM applied_migrations")
}
for path in sorted(MIGRATIONS_DIR.glob("*.sql")):
if path.name in applied:
continue
sql = path.read_text(encoding="utf-8")
async with conn.transaction():
await conn.execute(sql)
await conn.execute(
"INSERT INTO applied_migrations (name) VALUES ($1)",
path.name,
)
print(f"applied migration: {path.name}", flush=True)
+70
View File
@@ -0,0 +1,70 @@
from pydantic import BaseModel, Field
from typing import List, Optional
class User(BaseModel):
id: str
username: str
display_name: str
created_at: str
class CreateUser(BaseModel):
username: str = Field(..., pattern=r"^[a-z0-9_]{3,32}$")
display_name: str = Field(..., min_length=1, max_length=100)
password: str = Field(..., min_length=12, max_length=128)
class Chat(BaseModel):
id: str
title: str
member_ids: List[str]
created_at: str
class CreateChat(BaseModel):
title: str = Field(..., min_length=1, max_length=100)
member_ids: List[str] = Field(..., min_length=1, max_length=100)
class Message(BaseModel):
id: str
chat_id: str
sender_id: str
text: str
created_at: str
class CreateMessage(BaseModel):
text: str = Field(..., min_length=1, max_length=4000)
class ChatPage(BaseModel):
items: List[Chat]
next_cursor: Optional[str] = None
class MessagePage(BaseModel):
items: List[Message]
next_cursor: Optional[str] = None
class Health(BaseModel):
status: str = "ok"
class Session(BaseModel):
token: str
token_type: str = "Bearer"
expires_at: str
user: User
class ErrorBody(BaseModel):
code: str
message: str
request_id: str
class ErrorResponse(BaseModel):
error: ErrorBody
+69
View File
@@ -0,0 +1,69 @@
import base64
import secrets
from datetime import datetime, timedelta, timezone
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError, VerificationError, InvalidHash
from fastapi import Header, HTTPException, Request
_hasher = PasswordHasher()
def hash_password(password: str) -> str:
return _hasher.hash(password)
def verify_password(password: str, password_hash: str) -> bool:
try:
_hasher.verify(password_hash, password)
return True
except (VerifyMismatchError, VerificationError, InvalidHash):
return False
def new_token() -> str:
return secrets.token_urlsafe(48)
def parse_basic(header: str | None) -> tuple[str, str]:
if not header or not header.lower().startswith("basic "):
raise HTTPException(status_code=401, detail="unauthorized")
encoded = header.split(" ", 1)[1].strip()
try:
decoded = base64.b64decode(encoded).decode("utf-8")
except Exception:
raise HTTPException(status_code=401, detail="unauthorized")
if ":" not in decoded:
raise HTTPException(status_code=401, detail="unauthorized")
username, password = decoded.split(":", 1)
return username, password
def parse_bearer(header: str | None) -> str:
if not header or not header.lower().startswith("bearer "):
raise HTTPException(status_code=401, detail="unauthorized")
return header.split(" ", 1)[1].strip()
async def get_current_user(
request: Request,
authorization: str | None = Header(default=None),
):
token = parse_bearer(authorization)
session_store = request.app.state.session_store
storage = request.app.state.storage
session = await session_store.get(token)
if session is None:
raise HTTPException(status_code=401, detail="unauthorized")
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
if expires_at <= datetime.now(timezone.utc):
await session_store.delete(token)
raise HTTPException(status_code=401, detail="unauthorized")
user = await storage.get_user(session["user_id"])
if user is None:
raise HTTPException(status_code=401, detail="unauthorized")
return user, token
def session_expires_at(ttl_seconds: int) -> datetime:
return datetime.now(timezone.utc) + timedelta(seconds=ttl_seconds)
+108
View File
@@ -0,0 +1,108 @@
import json
from datetime import datetime, timezone
from typing import Optional
import asyncpg
import redis.asyncio as redis
from app.config import config
def _now_iso(value: datetime) -> str:
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
class PostgresSessionStore:
def __init__(self, pool: asyncpg.Pool) -> None:
self._pool = pool
async def create(self, token: str, user_id: str, expires_at: datetime) -> dict:
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
"""
INSERT INTO sessions (token, user_id, expires_at)
VALUES ($1, $2, $3)
RETURNING token, user_id, created_at, expires_at
""",
token, user_id, expires_at,
)
return {
"token": row["token"],
"user_id": str(row["user_id"]),
"created_at": _now_iso(row["created_at"]),
"expires_at": _now_iso(row["expires_at"]),
}
async def get(self, token: str) -> Optional[dict]:
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
"""
SELECT token, user_id, created_at, expires_at
FROM sessions WHERE token = $1
""",
token,
)
if row is None:
return None
return {
"token": row["token"],
"user_id": str(row["user_id"]),
"created_at": _now_iso(row["created_at"]),
"expires_at": _now_iso(row["expires_at"]),
}
async def delete(self, token: str) -> None:
async with self._pool.acquire() as conn:
await conn.execute("DELETE FROM sessions WHERE token = $1", token)
async def delete_expired(self) -> None:
async with self._pool.acquire() as conn:
await conn.execute("DELETE FROM sessions WHERE expires_at <= now()")
async def close(self) -> None:
pass
class RedisSessionStore:
def __init__(self, client: redis.Redis) -> None:
self._client = client
async def create(self, token: str, user_id: str, expires_at: datetime) -> dict:
now = datetime.now(timezone.utc)
ttl = max(1, int((expires_at - now).total_seconds()))
payload = {
"token": token,
"user_id": user_id,
"created_at": _now_iso(now),
"expires_at": _now_iso(expires_at),
}
await self._client.set(f"session:{token}", json.dumps(payload), ex=ttl)
return payload
async def get(self, token: str) -> Optional[dict]:
raw = await self._client.get(f"session:{token}")
if raw is None:
return None
return json.loads(raw)
async def delete(self, token: str) -> None:
await self._client.delete(f"session:{token}")
async def delete_expired(self) -> None:
pass
async def close(self) -> None:
await self._client.aclose()
def make_session_store(pool: asyncpg.Pool) -> PostgresSessionStore | RedisSessionStore:
if config.SESSION_STORE == "redis":
client = redis.from_url(
config.CACHE_URL,
decode_responses=True,
socket_connect_timeout=2,
socket_timeout=2,
)
return RedisSessionStore(client)
return PostgresSessionStore(pool)
+264
View File
@@ -0,0 +1,264 @@
import uuid
from datetime import datetime, timezone
from typing import Optional
from app.cache import Cache
import asyncpg
import asyncio
def _now_iso(value: datetime) -> str:
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
class Storage:
def __init__(self, pool: asyncpg.Pool, cache: Cache) -> None:
self._pool = pool
self._cache = cache
async def create_user(
self, username: str, display_name: str, password_hash: str,
) -> dict:
user_id = str(uuid.uuid4())
try:
async with self._pool.acquire() as conn:
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
""",
user_id, username, display_name, password_hash,
)
except asyncpg.UniqueViolationError:
raise ValueError("conflict")
return self._user_row(row)
async def get_user(self, user_id: str) -> Optional[dict]:
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
"SELECT id, username, display_name, created_at FROM users WHERE id = $1",
user_id,
)
return self._user_row(row) if row else None
async def get_user_by_username(self, username: str) -> Optional[dict]:
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
"""
SELECT id, username, display_name, password_hash, created_at
FROM users WHERE username = $1
""",
username,
)
return dict(row) if row else None
async def create_chat(
self, title: str, member_ids: list[str], creator_id: str,
) -> dict:
unique = list(dict.fromkeys(member_ids))
if creator_id not in unique:
raise ValueError("creator_not_member")
chat_id = str(uuid.uuid4())
async with self._pool.acquire() as conn:
async with conn.transaction():
existing = await conn.fetchval(
"SELECT count(*) FROM users WHERE id = ANY($1::uuid[])",
unique,
)
if existing != len(unique):
raise ValueError("invalid_member")
await conn.execute(
"INSERT INTO chats (id, title) VALUES ($1, $2)",
chat_id, title,
)
await conn.executemany(
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)",
[(chat_id, uid) for uid in unique],
)
created = await conn.fetchval(
"SELECT created_at FROM chats WHERE id = $1", chat_id,
)
return {
"id": chat_id,
"title": title,
"member_ids": unique,
"created_at": _now_iso(created),
}
async def get_chat(self, chat_id: str, actor_id: str) -> Optional[dict]:
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
"SELECT id, title, created_at FROM chats WHERE id = $1",
chat_id,
)
if row is None:
return None
members = await conn.fetch(
"SELECT user_id FROM chat_members WHERE chat_id = $1",
chat_id,
)
member_ids = [str(m["user_id"]) for m in members]
if actor_id not in member_ids:
return None
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": member_ids,
"created_at": _now_iso(row["created_at"]),
}
async def list_chats(
self, actor_id: str, limit: int, cursor: Optional[str],
) -> tuple[list[dict], Optional[str]]:
async with self._pool.acquire() as conn:
params: list = [actor_id]
where = ""
if cursor:
try:
cur_created, cur_id = cursor.split("|", 1)
except ValueError:
raise ValueError("bad_cursor")
where = "AND (c.created_at, c.id) > ($2, $3)"
params += [
datetime.fromisoformat(cur_created.replace("Z", "+00:00")),
cur_id,
]
rows = await conn.fetch(
f"""
SELECT c.id, c.title, c.created_at
FROM chats c
JOIN chat_members m ON m.chat_id = c.id
WHERE m.user_id = $1 {where}
ORDER BY c.created_at, c.id
LIMIT ${len(params) + 1}
""",
*params, limit + 1,
)
items = []
for row in rows[:limit]:
members = await conn.fetch(
"SELECT user_id FROM chat_members WHERE chat_id = $1",
row["id"],
)
items.append({
"id": str(row["id"]),
"title": row["title"],
"member_ids": [str(m["user_id"]) for m in members],
"created_at": _now_iso(row["created_at"]),
})
next_cursor = None
if len(rows) > limit:
last = rows[limit - 1]
next_cursor = f"{_now_iso(last['created_at'])}|{last['id']}"
return items, next_cursor
async def add_message(
self, chat_id: str, sender_id: str, text: str,
) -> dict:
message_id = str(uuid.uuid4())
async with self._pool.acquire() as conn:
is_member = await conn.fetchval(
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
chat_id, sender_id,
)
if is_member is None:
raise ValueError("not_found")
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,
)
await self._cache.invalidate_chat(chat_id)
return self._message_row(row)
async def list_messages(
self, chat_id: str, actor_id: str, limit: int, cursor: Optional[str],
) -> tuple[list[dict], Optional[str]]:
cache_key = f"messages:{chat_id}:{limit}:{cursor or ''}"
cached = await self._cache.get_json(cache_key)
if cached is not None:
return cached["items"], cached["next_cursor"]
lock_key = f"lock:{cache_key}"
got_lock = await self._cache.try_lock(lock_key, ttl=10)
if not got_lock:
for _ in range(50):
await asyncio.sleep(0.1)
cached = await self._cache.get_json(cache_key)
if cached is not None:
return cached["items"], cached["next_cursor"]
cached = await self._cache.get_json(cache_key)
if cached is not None:
return cached["items"], cached["next_cursor"]
try:
async with self._pool.acquire() as conn:
is_member = await conn.fetchval(
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
chat_id, actor_id,
)
if is_member is None:
raise ValueError("not_found")
params: list = [chat_id]
where = ""
if cursor:
try:
cur_created, cur_id = cursor.split("|", 1)
except ValueError:
raise ValueError("bad_cursor")
where = "AND (created_at, id) > ($2, $3)"
params += [
datetime.fromisoformat(cur_created.replace("Z", "+00:00")),
cur_id,
]
rows = await conn.fetch(
f"""
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1 {where}
ORDER BY created_at, id
LIMIT ${len(params) + 1}
""",
*params, limit + 1,
)
items = [self._message_row(row) for row in rows[:limit]]
next_cursor = None
if len(rows) > limit:
last = rows[limit - 1]
next_cursor = f"{_now_iso(last['created_at'])}|{last['id']}"
if got_lock:
await self._cache.set_json(
cache_key,
{"items": items, "next_cursor": next_cursor},
)
return items, next_cursor
finally:
if got_lock:
await self._cache.unlock(lock_key)
@staticmethod
def _user_row(row) -> dict:
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": _now_iso(row["created_at"]),
}
@staticmethod
def _message_row(row) -> dict:
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"created_at": _now_iso(row["created_at"]),
}