forked from mtusi2026/mtusi2026lab3
chore: setup project and copy lab2 code
This commit is contained in:
@@ -0,0 +1,128 @@
|
||||
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
|
||||
) -> Message:
|
||||
msg = Message(chat_id=chat_id, sender_id=sender_id, text=text)
|
||||
db.add(msg)
|
||||
await db.commit()
|
||||
await db.refresh(msg)
|
||||
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,
|
||||
limit: int,
|
||||
cursor: tuple[datetime, UUID] | None,
|
||||
) -> tuple[list[Message], tuple[datetime, UUID] | None]:
|
||||
stmt = (
|
||||
select(Message)
|
||||
.where(Message.chat_id == chat_id)
|
||||
.order_by(Message.created_at.asc(), Message.id.asc())
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if cursor is not None:
|
||||
c_created, c_id = cursor
|
||||
stmt = stmt.where(
|
||||
(Message.created_at > c_created)
|
||||
| ((Message.created_at == c_created) & (Message.id > c_id))
|
||||
)
|
||||
rows = list((await db.execute(stmt)).scalars().all())
|
||||
next_cursor = None
|
||||
if len(rows) > limit:
|
||||
rows = rows[:limit]
|
||||
last = rows[-1]
|
||||
next_cursor = (last.created_at, last.id)
|
||||
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:
|
||||
payload = json.dumps(_serialize(rows, next_cursor))
|
||||
await redis_client.setex(key, CACHE_TTL, payload)
|
||||
print(f"CACHE SET OK: {key}", flush=True)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
print(f"CACHE SET FAILED: {type(e).__name__}: {e}", flush=True)
|
||||
|
||||
return rows, next_cursor, False
|
||||
Reference in New Issue
Block a user