forked from mtusi2026/mtusi2026lab2
Мессенджер с Postgres, Redis, Valkey
This commit is contained in:
@@ -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)
|
||||
Reference in New Issue
Block a user