feat: implement chat messaging and Redis cache

This commit is contained in:
sinveria
2026-11-04 18:44:55 +03:00
parent e0e654dcf5
commit 527f0e8d74
8 changed files with 643 additions and 24 deletions
+13 -1
View File
@@ -1,3 +1,4 @@
from datetime import timezone
from fastapi import APIRouter, Depends, Header, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from sqlalchemy.orm import Session
@@ -16,6 +17,7 @@ router = APIRouter(prefix="/api/v1/auth", tags=["Authentication"])
basic_security = HTTPBasic(auto_error=False)
@router.post("/sessions", status_code=status.HTTP_201_CREATED)
def create_session(
credentials: HTTPBasicCredentials = Depends(basic_security),
@@ -36,10 +38,19 @@ def create_session(
password=credentials.password,
)
expires_at = result["expires_at"]
if expires_at.tzinfo is None:
expires_at = expires_at.replace(tzinfo=timezone.utc)
else:
expires_at = expires_at.astimezone(timezone.utc)
return {
"token": result["token"],
"token_type": result["token_type"],
"expires_at": result["expires_at"],
"expires_at": expires_at.isoformat(
timespec="microseconds"
).replace("+00:00", "Z"),
"user": user_to_response(result["user"]),
}
@@ -53,6 +64,7 @@ def create_session(
) from None
@router.delete("/sessions/current", status_code=status.HTTP_204_NO_CONTENT)
def delete_current_session(
authorization: str | None = Header(default=None),
+90
View File
@@ -0,0 +1,90 @@
import uuid
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from app.api.deps import get_db, get_current_user
from app.db.models import User as UserModel
from app.models import Chat as ChatResponse, CreateChat
from app.services.chat_service import (
ChatService,
ChatNotFoundError,
InvalidChatDataError,
)
router = APIRouter(prefix="/api/v1/chats", tags=["Chats"])
def chat_to_response(chat) -> ChatResponse:
return ChatResponse(
id=str(chat.id),
title=chat.title,
member_ids=[str(member.user_id) for member in chat.members],
created_at=chat.created_at,
)
@router.post("", response_model=ChatResponse, status_code=status.HTTP_201_CREATED)
def create_chat(
body: CreateChat,
db: Session = Depends(get_db),
user: UserModel = Depends(get_current_user),
):
try:
chat = ChatService(db).create_chat(
title=body.title,
member_ids=body.member_ids,
creator_id=user.id,
)
return chat_to_response(chat)
except InvalidChatDataError as exc:
raise HTTPException(
status_code=400,
detail=str(exc),
) from None
@router.get("")
def list_chats(
limit: int = Query(default=50, ge=1, le=100),
cursor: str | None = None,
db: Session = Depends(get_db),
user: UserModel = Depends(get_current_user),
):
if cursor is not None:
raise HTTPException(
status_code=400,
detail="Chat cursor pagination is not implemented yet",
)
chats = ChatService(db).list_chats(user.id)
chats = chats[:limit]
return {
"items": [chat_to_response(chat) for chat in chats],
"next_cursor": None,
}
@router.get("/{chat_id}", response_model=ChatResponse)
def get_chat(
chat_id: str,
db: Session = Depends(get_db),
user: UserModel = Depends(get_current_user),
):
try:
parsed_id = uuid.UUID(chat_id)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid chat UUID") from None
try:
chat = ChatService(db).get_chat(parsed_id, user.id)
return chat_to_response(chat)
except ChatNotFoundError:
raise HTTPException(
status_code=404,
detail="Chat not found",
) from None
+17 -23
View File
@@ -1,14 +1,15 @@
from typing import Generator
from fastapi import Depends, Header, HTTPException
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.orm import Session
from app.db.session import SessionLocal
from app.db.models import User
from app.services.auth_service import AuthService, InvalidSessionError
def get_db() -> Generator[Session, None, None]:
bearer_scheme = HTTPBearer(auto_error=False)
def get_db():
db = SessionLocal()
try:
yield db
@@ -17,30 +18,23 @@ def get_db() -> Generator[Session, None, None]:
def get_current_user(
authorization: str | None = Header(default=None),
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
db: Session = Depends(get_db),
) -> User:
if not authorization or not authorization.startswith("Bearer "):
):
if credentials is None or credentials.scheme.lower() != "bearer":
raise HTTPException(
status_code=401,
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Bearer token required",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
token = authorization[7:].strip()
if not token:
raise HTTPException(
status_code=401,
detail="Bearer token required",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
headers={"WWW-Authenticate": "Bearer"},
)
try:
return AuthService(db).authenticate(token)
user = AuthService(db).authenticate(credentials.credentials)
return user
except InvalidSessionError:
raise HTTPException(
status_code=401,
detail="Invalid or expired session",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired token",
headers={"WWW-Authenticate": "Bearer"},
) from None
+102
View File
@@ -0,0 +1,102 @@
import uuid
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from app.api.deps import get_db, get_current_user
from app.db.models import User as UserModel
from app.models import CreateMessage, Message as MessageResponse
from app.services.message_service import (
MessageService,
MessageNotFoundError,
InvalidMessageDataError,
)
router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["Messages"])
def message_to_response(message) -> MessageResponse:
return MessageResponse(
id=str(message.id),
chat_id=str(message.chat_id),
sender_id=str(message.sender_id),
text=message.text,
created_at=message.created_at,
)
def parse_chat_id(chat_id: str) -> uuid.UUID:
try:
return uuid.UUID(chat_id)
except ValueError:
raise HTTPException(
status_code=400,
detail="Invalid chat UUID",
) from None
@router.post("", response_model=MessageResponse, status_code=status.HTTP_201_CREATED)
def create_message(
chat_id: str,
body: CreateMessage,
db: Session = Depends(get_db),
user: UserModel = Depends(get_current_user),
):
parsed_id = parse_chat_id(chat_id)
try:
message = MessageService(db).create_message(
chat_id=parsed_id,
sender_id=user.id,
text=body.text,
)
return message_to_response(message)
except MessageNotFoundError:
raise HTTPException(
status_code=404,
detail="Chat not found",
) from None
except InvalidMessageDataError as exc:
raise HTTPException(
status_code=400,
detail=str(exc),
) from None
@router.get("")
def list_messages(
chat_id: str,
limit: int = Query(default=50, ge=1, le=100),
cursor: str | None = None,
db: Session = Depends(get_db),
user: UserModel = Depends(get_current_user),
):
parsed_id = parse_chat_id(chat_id)
try:
messages, next_cursor = MessageService(db).get_history(
chat_id=parsed_id,
user_id=user.id,
limit=limit,
cursor=cursor,
)
return {
"items": [message_to_response(item) for item in messages],
"next_cursor": next_cursor,
}
except MessageNotFoundError:
raise HTTPException(
status_code=404,
detail="Chat not found",
) from None
except InvalidMessageDataError as exc:
raise HTTPException(
status_code=400,
detail=str(exc),
) from None
+1
View File
@@ -11,6 +11,7 @@ class Settings(BaseSettings):
session_ttl_seconds: int = 3600
cache_url: str = "redis://localhost:6379/0"
message_cache_ttl_seconds: int = 60
model_config = SettingsConfigDict(
env_file=".env",
+4
View File
@@ -10,6 +10,8 @@ from sqlalchemy.exc import SQLAlchemyError
from app.api.auth import router as auth_router
from app.api.users import router as users_router
from app.api.chats import router as chats_router
from app.api.messages import router as messages_router
from app.core.config import settings
from app.db.session import engine
@@ -37,6 +39,8 @@ app = FastAPI(
app.include_router(users_router)
app.include_router(auth_router)
app.include_router(chats_router)
app.include_router(messages_router)
@app.middleware("http")
+94
View File
@@ -0,0 +1,94 @@
import uuid
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.db.models import Chat
from app.repositories.chat_repository import ChatRepository
from app.repositories.user_repository import UserRepository
class ChatNotFoundError(Exception):
pass
class ChatAccessError(Exception):
pass
class InvalidChatDataError(Exception):
pass
class ChatService:
def __init__(self, db: Session):
self.db = db
self.chats = ChatRepository(db)
self.users = UserRepository(db)
def create_chat(
self,
title: str,
member_ids: list[str],
creator_id: uuid.UUID,
) -> Chat:
title = title.strip()
if not title or len(title) > 100:
raise InvalidChatDataError("Invalid chat title")
if not member_ids or len(member_ids) > 100:
raise InvalidChatDataError("Invalid members")
try:
parsed_ids = [uuid.UUID(str(value)) for value in member_ids]
except (ValueError, TypeError, AttributeError):
raise InvalidChatDataError("Invalid member UUID") from None
if len(parsed_ids) != len(set(parsed_ids)):
raise InvalidChatDataError("Duplicate members")
if creator_id not in parsed_ids:
raise InvalidChatDataError("Creator must be a member")
for user_id in parsed_ids:
if self.users.get_by_id(user_id) is None:
raise InvalidChatDataError("Unknown member")
try:
chat = self.chats.create(
title=title,
member_ids=parsed_ids,
)
self.db.commit()
self.db.refresh(chat)
return chat
except IntegrityError as exc:
self.db.rollback()
raise InvalidChatDataError("Unable to create chat") from exc
except Exception:
self.db.rollback()
raise
def get_chat(self, chat_id: uuid.UUID, user_id: uuid.UUID) -> Chat:
chat = self.chats.get_by_id(chat_id)
if chat is None:
raise ChatNotFoundError()
if not self.chats.is_member(chat_id, user_id):
raise ChatNotFoundError()
return chat
def list_chats(self, user_id: uuid.UUID) -> list[Chat]:
return self.chats.get_by_user(user_id)
def check_membership(
self,
chat_id: uuid.UUID,
user_id: uuid.UUID,
) -> bool:
return self.chats.is_member(chat_id, user_id)
+322
View File
@@ -0,0 +1,322 @@
import base64
import hashlib
import json
import time
import uuid
from datetime import datetime
from types import SimpleNamespace
from redis import Redis
from redis.exceptions import RedisError
from sqlalchemy.orm import Session
from app.core.config import settings
from app.db.models import Message
from app.repositories.chat_repository import ChatRepository
from app.repositories.message_repository import MessageRepository
class MessageNotFoundError(Exception):
pass
class MessageAccessError(Exception):
pass
class InvalidMessageDataError(Exception):
pass
class MessageService:
def __init__(self, db: Session):
self.db = db
self.messages = MessageRepository(db)
self.chats = ChatRepository(db)
self.redis = Redis.from_url(
settings.cache_url,
decode_responses=True,
socket_connect_timeout=2,
socket_timeout=2,
)
@staticmethod
def encode_cursor(message: Message) -> str:
payload = {
"created_at": message.created_at.isoformat(),
"id": str(message.id),
}
raw = json.dumps(payload).encode("utf-8")
return (
base64.urlsafe_b64encode(raw)
.decode("ascii")
.rstrip("=")
)
@staticmethod
def decode_cursor(cursor: str | None):
if not cursor:
return None, None
try:
padded = cursor + "=" * (-len(cursor) % 4)
raw = base64.urlsafe_b64decode(padded.encode("ascii"))
payload = json.loads(raw.decode("utf-8"))
created_at = datetime.fromisoformat(payload["created_at"])
message_id = uuid.UUID(payload["id"])
if created_at.tzinfo is None:
raise ValueError("Cursor timestamp must include timezone")
return created_at, message_id
except (ValueError, TypeError, KeyError, UnicodeError):
raise InvalidMessageDataError("Invalid cursor") from None
def _version_key(self, chat_id: uuid.UUID) -> str:
return f"messages:version:{chat_id}"
def _cache_key(
self,
chat_id: uuid.UUID,
version: int,
limit: int,
cursor: str | None,
) -> str:
cursor_hash = hashlib.sha256(
(cursor or "first-page").encode("utf-8")
).hexdigest()[:16]
return (
f"messages:{chat_id}:v{version}:"
f"limit:{limit}:cursor:{cursor_hash}"
)
def _get_version(self, chat_id: uuid.UUID) -> int:
try:
value = self.redis.get(self._version_key(chat_id))
return int(value or 0)
except (RedisError, ValueError):
return 0
def _bump_version(self, chat_id: uuid.UUID) -> None:
try:
self.redis.incr(self._version_key(chat_id))
except RedisError:
pass
@staticmethod
def _serialize(messages, next_cursor):
return json.dumps({
"items": [
{
"id": str(message.id),
"chat_id": str(message.chat_id),
"sender_id": str(message.sender_id),
"text": message.text,
"created_at": message.created_at.isoformat(),
}
for message in messages
],
"next_cursor": next_cursor,
})
@staticmethod
def _deserialize(payload: str):
data = json.loads(payload)
messages = [
SimpleNamespace(
id=uuid.UUID(item["id"]),
chat_id=uuid.UUID(item["chat_id"]),
sender_id=uuid.UUID(item["sender_id"]),
text=item["text"],
created_at=datetime.fromisoformat(item["created_at"]),
)
for item in data["items"]
]
return messages, data["next_cursor"]
def _read_cache(self, key: str):
try:
payload = self.redis.get(key)
if payload is None:
return None
return self._deserialize(payload)
except (RedisError, ValueError, TypeError, KeyError):
return None
def _load_from_database(
self,
chat_id,
limit,
cursor_created_at,
cursor_id,
):
rows = self.messages.get_history(
chat_id=chat_id,
limit=limit + 1,
cursor_created_at=cursor_created_at,
cursor_id=cursor_id,
)
has_more = len(rows) > limit
items = rows[:limit]
next_cursor = (
self.encode_cursor(items[-1])
if has_more and items
else None
)
return items, next_cursor
def create_message(
self,
chat_id: uuid.UUID,
sender_id: uuid.UUID,
text: str,
) -> Message:
text = text.strip()
if not text or len(text) > 4000:
raise InvalidMessageDataError("Invalid message text")
if not self.chats.is_member(chat_id, sender_id):
raise MessageNotFoundError()
try:
message = self.messages.create(
chat_id=chat_id,
sender_id=sender_id,
text=text,
)
self.db.commit()
self.db.refresh(message)
self._bump_version(chat_id)
return message
except Exception:
self.db.rollback()
raise
def get_history(
self,
chat_id: uuid.UUID,
user_id: uuid.UUID,
limit: int = 50,
cursor: str | None = None,
):
if not 1 <= limit <= 100:
raise InvalidMessageDataError(
"Limit must be between 1 and 100"
)
if not self.chats.is_member(chat_id, user_id):
raise MessageNotFoundError()
cursor_created_at, cursor_id = self.decode_cursor(cursor)
version = self._get_version(chat_id)
cache_key = self._cache_key(
chat_id,
version,
limit,
cursor,
)
cached = self._read_cache(cache_key)
if cached is not None:
return cached
lock_key = f"lock:{cache_key}"
lock_token = str(uuid.uuid4())
try:
acquired = self.redis.set(
lock_key,
lock_token,
nx=True,
ex=10,
)
except RedisError:
return self._load_from_database(
chat_id,
limit,
cursor_created_at,
cursor_id,
)
if not acquired:
for _ in range(10):
time.sleep(0.05)
cached = self._read_cache(cache_key)
if cached is not None:
return cached
return self._load_from_database(
chat_id,
limit,
cursor_created_at,
cursor_id,
)
try:
cached = self._read_cache(cache_key)
if cached is not None:
return cached
items, next_cursor = self._load_from_database(
chat_id,
limit,
cursor_created_at,
cursor_id,
)
if self._get_version(chat_id) == version:
try:
self.redis.setex(
cache_key,
settings.message_cache_ttl_seconds,
self._serialize(items, next_cursor),
)
except RedisError:
pass
return items, next_cursor
finally:
try:
self.redis.eval(
"""
if redis.call('get', KEYS[1]) == ARGV[1]
then
return redis.call('del', KEYS[1])
else
return 0
end
""",
1,
lock_key,
lock_token,
)
except RedisError:
pass