feat: add PostgreSQL fallback for sessions and graceful degradation on Redis failure
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
+86
-51
@@ -1,16 +1,28 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import selectinload
|
||||
import uuid
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from app.database import get_db
|
||||
from app.models import Chat as ChatModel, ChatMember as ChatMemberModel, Message as MessageModel, User as UserModel
|
||||
from app.schemas import Chat, CreateChat, Message, CreateMessage, ChatPage, MessagePage, ErrorResponse
|
||||
from app.models import (
|
||||
Chat as ChatModel,
|
||||
ChatMember as ChatMemberModel,
|
||||
Message as MessageModel,
|
||||
User as UserModel,
|
||||
)
|
||||
from app.schemas import (
|
||||
Chat, CreateChat, Message, CreateMessage,
|
||||
ChatPage, MessagePage, ErrorResponse,
|
||||
)
|
||||
from app.dependencies import get_current_user
|
||||
from app.redis_client import get_redis
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post(
|
||||
@@ -27,7 +39,7 @@ async def create_chat(
|
||||
if current_user.id not in chat_in.member_ids:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail={"code": "invalid_request", "message": "Creator must be in member_ids", }
|
||||
detail={"code": "invalid_request", "message": "Creator must be in member_ids"}
|
||||
)
|
||||
|
||||
user_ids = list(set(chat_in.member_ids))
|
||||
@@ -35,7 +47,7 @@ async def create_chat(
|
||||
if len(result.scalars().all()) != len(user_ids):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail={"code": "invalid_request", "message": "One or more member_ids do not exist", }
|
||||
detail={"code": "invalid_request", "message": "One or more member_ids do not exist"}
|
||||
)
|
||||
|
||||
new_chat = ChatModel(title=chat_in.title)
|
||||
@@ -86,7 +98,7 @@ async def list_chats(
|
||||
except (ValueError, TypeError):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail={"code": "invalid_request", "message": "Invalid cursor", }
|
||||
detail={"code": "invalid_request", "message": "Invalid cursor"}
|
||||
)
|
||||
|
||||
stmt = stmt.limit(limit + 1)
|
||||
@@ -100,16 +112,15 @@ async def list_chats(
|
||||
else:
|
||||
next_cursor = None
|
||||
|
||||
items = []
|
||||
for c in chats:
|
||||
member_ids = [str(m.user_id) for m in c.members]
|
||||
items.append(Chat(
|
||||
items = [
|
||||
Chat(
|
||||
id=str(c.id),
|
||||
title=c.title,
|
||||
member_ids=member_ids,
|
||||
member_ids=[str(m.user_id) for m in c.members],
|
||||
created_at=c.created_at.isoformat().replace('+00:00', 'Z')
|
||||
))
|
||||
|
||||
)
|
||||
for c in chats
|
||||
]
|
||||
return ChatPage(items=items, next_cursor=next_cursor)
|
||||
|
||||
@router.get(
|
||||
@@ -133,14 +144,13 @@ async def get_chat(
|
||||
if not chat:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail={"code": "not_found", "message": "Chat not found or access denied", }
|
||||
detail={"code": "not_found", "message": "Chat not found or access denied"}
|
||||
)
|
||||
|
||||
member_ids = [str(m.user_id) for m in chat.members]
|
||||
return Chat(
|
||||
id=str(chat.id),
|
||||
title=chat.title,
|
||||
member_ids=member_ids,
|
||||
member_ids=[str(m.user_id) for m in chat.members],
|
||||
created_at=chat.created_at.isoformat().replace('+00:00', 'Z')
|
||||
)
|
||||
|
||||
@@ -163,7 +173,7 @@ async def create_message(
|
||||
if not (await db.execute(stmt)).scalar_one_or_none():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail={"code": "not_found", "message": "Chat not found or access denied", }
|
||||
detail={"code": "not_found", "message": "Chat not found or access denied"}
|
||||
)
|
||||
|
||||
new_message = MessageModel(chat_id=chat_id, sender_id=current_user.id, text=message_in.text)
|
||||
@@ -171,8 +181,12 @@ async def create_message(
|
||||
await db.commit()
|
||||
await db.refresh(new_message)
|
||||
|
||||
# GRADE 5: Инвалидация кэша при записи (Read-After-Write consistency)
|
||||
await redis_client.delete(f"messages:{chat_id}:*")
|
||||
# Инвалидация кэша при записи (Read-After-Write consistency)
|
||||
# Если Redis недоступен — кэш всё равно истечёт по TTL, это не критично
|
||||
try:
|
||||
await redis_client.delete(f"messages:{chat_id}:*")
|
||||
except Exception as e:
|
||||
logger.warning(f"Redis unavailable for cache invalidation: {e}")
|
||||
|
||||
return Message(
|
||||
id=str(new_message.id),
|
||||
@@ -195,32 +209,47 @@ async def list_messages(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
redis_client = Depends(get_redis)
|
||||
):
|
||||
"""
|
||||
Чтение истории сообщений с кэшированием в Redis.
|
||||
При недоступности Redis — graceful degradation: запрос идёт напрямую в PostgreSQL.
|
||||
"""
|
||||
if not (await db.execute(select(ChatMemberModel).where(
|
||||
ChatMemberModel.chat_id == chat_id, ChatMemberModel.user_id == current_user.id
|
||||
))).scalar_one_or_none():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail={"code": "not_found", "message": "Chat not found or access denied", }
|
||||
detail={"code": "not_found", "message": "Chat not found or access denied"}
|
||||
)
|
||||
|
||||
cache_key = f"messages:{chat_id}:{limit}:{cursor or 'null'}"
|
||||
redis_available = True
|
||||
|
||||
# 1. Проверяем основной кэш
|
||||
cached_data = await redis_client.get(cache_key)
|
||||
if cached_data:
|
||||
await redis_client.expire(cache_key, 60)
|
||||
return MessagePage.model_validate_json(cached_data)
|
||||
|
||||
# 2. GRADE 5: Защита от Cache Stampede (Request Coalescing)
|
||||
lock_key = f"lock:{cache_key}"
|
||||
acquired = await redis_client.set(lock_key, "1", nx=True, ex=5)
|
||||
# 1. Пытаемся проверить кэш
|
||||
try:
|
||||
cached_data = await redis_client.get(cache_key)
|
||||
if cached_data:
|
||||
await redis_client.expire(cache_key, 60)
|
||||
return MessagePage.model_validate_json(cached_data)
|
||||
except Exception as e:
|
||||
logger.warning(f"Redis unavailable for cache read, falling back to PostgreSQL: {e}")
|
||||
redis_available = False
|
||||
|
||||
if not acquired:
|
||||
stale_data = await redis_client.get(f"stale:{cache_key}")
|
||||
if stale_data:
|
||||
return MessagePage.model_validate_json(stale_data)
|
||||
|
||||
# 3. Выполняем запрос к БД
|
||||
# 2. Request Coalescing (только если Redis доступен)
|
||||
lock_acquired = False
|
||||
if redis_available:
|
||||
lock_key = f"lock:{cache_key}"
|
||||
try:
|
||||
lock_acquired = await redis_client.set(lock_key, "1", nx=True, ex=5)
|
||||
|
||||
if not lock_acquired:
|
||||
stale_data = await redis_client.get(f"stale:{cache_key}")
|
||||
if stale_data:
|
||||
return MessagePage.model_validate_json(stale_data)
|
||||
except Exception as e:
|
||||
logger.warning(f"Redis unavailable for lock acquisition: {e}")
|
||||
redis_available = False
|
||||
|
||||
# 3. Выполняем запрос к БД (всегда, если кэш miss)
|
||||
stmt = (
|
||||
select(MessageModel)
|
||||
.where(MessageModel.chat_id == chat_id)
|
||||
@@ -239,7 +268,7 @@ async def list_messages(
|
||||
except (ValueError, TypeError):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail={"code": "invalid_request", "message": "Invalid cursor", }
|
||||
detail={"code": "invalid_request", "message": "Invalid cursor"}
|
||||
)
|
||||
|
||||
stmt = stmt.limit(limit + 1)
|
||||
@@ -252,24 +281,30 @@ async def list_messages(
|
||||
else:
|
||||
next_cursor = None
|
||||
|
||||
items = []
|
||||
for m in messages:
|
||||
items.append(Message(
|
||||
items = [
|
||||
Message(
|
||||
id=str(m.id),
|
||||
chat_id=str(m.chat_id),
|
||||
sender_id=str(m.sender_id),
|
||||
text=m.text,
|
||||
created_at=m.created_at.isoformat().replace('+00:00', 'Z')
|
||||
))
|
||||
|
||||
)
|
||||
for m in messages
|
||||
]
|
||||
page = MessagePage(items=items, next_cursor=next_cursor)
|
||||
|
||||
# 4. GRADE 5: Сохраняем старые данные как stale перед обновлением основного кэша
|
||||
old_cache = await redis_client.get(cache_key)
|
||||
if old_cache:
|
||||
await redis_client.setex(f"stale:{cache_key}", 120, old_cache)
|
||||
|
||||
await redis_client.setex(cache_key, 60, page.model_dump_json())
|
||||
await redis_client.delete(lock_key)
|
||||
# 4. Пытаемся обновить кэш (если Redis доступен)
|
||||
if redis_available:
|
||||
try:
|
||||
old_cache = await redis_client.get(cache_key)
|
||||
if old_cache:
|
||||
await redis_client.setex(f"stale:{cache_key}", 120, old_cache)
|
||||
|
||||
await redis_client.setex(cache_key, 60, page.model_dump_json())
|
||||
|
||||
if lock_acquired:
|
||||
await redis_client.delete(f"lock:{cache_key}")
|
||||
except Exception as e:
|
||||
logger.warning(f"Redis unavailable for cache write: {e}")
|
||||
|
||||
return page
|
||||
Reference in New Issue
Block a user