финальные evidence для lab2 + кэширование

This commit is contained in:
2026-10-01 03:50:54 +03:00
parent 2b90834d03
commit 43e5964180
9 changed files with 371 additions and 7 deletions
+4 -1
View File
@@ -2,6 +2,7 @@ import hashlib
import os
import secrets
from datetime import datetime, timezone
from uuid import UUID
import bcrypt
from fastapi import Depends, Header, HTTPException
@@ -79,4 +80,6 @@ async def revoke_current_session(authorization: str, db: AsyncSession) -> None:
if not authorization or not authorization.startswith("Bearer "):
raise _unauthorized_bearer()
token = authorization[7:]
await redis_client.delete(f"session:{hash_token(token)}")
deleted = await redis_client.delete(f"session:{hash_token(token)}")
if deleted == 0:
raise _unauthorized_bearer()
+4 -3
View File
@@ -171,10 +171,9 @@ async def login(
raise HTTPException(
status_code=401, detail="Unauthorized", headers={"WWW-Authenticate": basic_challenge}
)
token = generate_token()
expires = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL)
token = await create_session(str(user.id))
await db.commit()
return {
"token": token,
"token_type": "Bearer",
@@ -271,6 +270,7 @@ async def list_messages(
chat = await chats_repo.get_if_member(db, chat_id, user.id)
if chat is None:
raise HTTPException(404, "Chat not found")
parsed = None
if cursor is not None:
try:
@@ -278,11 +278,12 @@ async def list_messages(
parsed = (datetime.fromisoformat(c_created), UUID(c_id))
except Exception:
raise HTTPException(400, "Invalid cursor")
rows, next_cursor = await messages_repo.list_page(db, chat_id, limit, parsed)
nxt = f"{next_cursor[0].isoformat()}|{next_cursor[1]}" if next_cursor else None
return {"items": [_msg_json(m) for m in rows], "next_cursor": nxt}
if __name__ == "__main__":
import uvicorn
+1 -2
View File
@@ -10,7 +10,6 @@ from ..db.models import Chat, ChatMember, User
async def create_atomic(
db: AsyncSession, title: str, member_ids: list[UUID]
) -> Chat:
# проверка всех участников
found = (
(await db.execute(select(User.id).where(User.id.in_(member_ids))))
.scalars()
@@ -22,7 +21,7 @@ async def create_atomic(
chat = Chat(title=title)
db.add(chat)
await db.flush() # получить chat.id
await db.flush()
for uid in member_ids:
db.add(ChatMember(chat_id=chat.id, user_id=uid))
+81 -1
View File
@@ -1,11 +1,52 @@
import json
import os
from datetime import datetime
from types import SimpleNamespace
from uuid import UUID
import redis.asyncio as redis
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from ..db.models import Message
redis_client = redis.from_url(os.getenv("REDIS_URL", "redis://redis:6379/0"))
CACHE_TTL = 30
def _serialize(rows: list[Message], next_cursor):
return {
"items": [
{
"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(),
}
for m in rows
],
"next_cursor": (
[next_cursor[0].isoformat(), str(next_cursor[1])] if next_cursor else None
),
}
def _deserialize(data: dict):
items = [
SimpleNamespace(
id=UUID(row["id"]),
chat_id=UUID(row["chat_id"]),
sender_id=UUID(row["sender_id"]),
text=row["text"],
created_at=datetime.fromisoformat(row["created_at"]),
)
for row in data["items"]
]
nc = data.get("next_cursor")
next_cursor = (datetime.fromisoformat(nc[0]), UUID(nc[1])) if nc else None
return items, next_cursor
async def create(
db: AsyncSession, chat_id: UUID, sender_id: UUID, text: str
@@ -17,6 +58,15 @@ async def create(
return msg
async def create_and_invalidate(
db: AsyncSession, chat_id: UUID, sender_id: UUID, text: str
) -> Message:
msg = await create(db, chat_id, sender_id, text)
keys = [f"chat:{chat_id}:first_page:{n}" for n in (10, 20, 50)]
await redis_client.delete(*keys)
return msg
async def list_page(
db: AsyncSession,
chat_id: UUID,
@@ -41,4 +91,34 @@ async def list_page(
rows = rows[:limit]
last = rows[-1]
next_cursor = (last.created_at, last.id)
return rows, next_cursor
return rows, next_cursor
async def list_page_cached(
db: AsyncSession,
chat_id: UUID,
limit: int,
cursor: tuple[datetime, UUID] | None,
) -> tuple[list, tuple[datetime, UUID] | None, bool]:
"""Возвращает (rows, next_cursor, cached)."""
use_cache = cursor is None and limit <= 50
key = f"chat:{chat_id}:first_page:{limit}"
if use_cache:
raw = await redis_client.get(key)
if raw is not None:
try:
rows, next_cursor = _deserialize(json.loads(raw))
return rows, next_cursor, True
except Exception:
pass # повреждённый кэш — игнорируем и идём в БД
rows, next_cursor = await list_page(db, chat_id, limit, cursor)
if use_cache:
try:
await redis_client.setex(key, CACHE_TTL, json.dumps(_serialize(rows, next_cursor)))
except Exception:
pass # Redis недоступен — не падаем, просто без кэша
return rows, next_cursor, False