lab2: grade 4 — Redis session cache, race/rollback/expiry tests, EXPLAIN evidence
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
+32
-7
@@ -44,8 +44,12 @@ def _token_hash(token: str) -> str:
|
||||
|
||||
|
||||
def create_session(user_id: str) -> dict:
|
||||
from . import cache
|
||||
|
||||
token = _generate_token()
|
||||
expires_at = _now() + timedelta(seconds=_ttl_seconds())
|
||||
ttl = _ttl_seconds()
|
||||
expires_at = _now() + timedelta(seconds=ttl)
|
||||
token_hash = _token_hash(token)
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
@@ -53,12 +57,21 @@ def create_session(user_id: str) -> dict:
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at, created_at)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
""",
|
||||
(_token_hash(token), user_id, expires_at, _now()),
|
||||
(token_hash, user_id, expires_at, _now()),
|
||||
)
|
||||
cache.set_user_id(token_hash, user_id, ttl)
|
||||
return {"token": token, "expires_at": expires_at}
|
||||
|
||||
|
||||
def get_user_id_by_token(token: str) -> Optional[str]:
|
||||
from . import cache
|
||||
|
||||
token_hash = _token_hash(token)
|
||||
|
||||
cached = cache.get_user_id(token_hash)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
@@ -67,21 +80,33 @@ def get_user_id_by_token(token: str) -> Optional[str]:
|
||||
FROM sessions
|
||||
WHERE token_hash = %s
|
||||
""",
|
||||
(_token_hash(token),),
|
||||
(token_hash,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
if row["expires_at"] <= _now():
|
||||
|
||||
now = _now()
|
||||
if row["expires_at"] <= now:
|
||||
return None
|
||||
return str(row["user_id"])
|
||||
|
||||
user_id = str(row["user_id"])
|
||||
ttl = int((row["expires_at"] - now).total_seconds())
|
||||
cache.set_user_id(token_hash, user_id, ttl)
|
||||
return user_id
|
||||
|
||||
|
||||
def revoke_session(token: str) -> bool:
|
||||
from . import cache
|
||||
|
||||
token_hash = _token_hash(token)
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"DELETE FROM sessions WHERE token_hash = %s",
|
||||
(_token_hash(token),),
|
||||
(token_hash,),
|
||||
)
|
||||
return cur.rowcount > 0
|
||||
deleted = cur.rowcount > 0
|
||||
if deleted:
|
||||
cache.invalidate(token_hash)
|
||||
return deleted
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
import redis
|
||||
|
||||
log = logging.getLogger("messenger.cache")
|
||||
|
||||
_client: Optional[redis.Redis] = None
|
||||
_failures: int = 0
|
||||
_MAX_FAILURES_BEFORE_DISABLE: int = 3
|
||||
|
||||
|
||||
def _cache_url() -> Optional[str]:
|
||||
return os.environ.get("CACHE_URL")
|
||||
|
||||
|
||||
def init_cache() -> None:
|
||||
global _client, _failures
|
||||
url = _cache_url()
|
||||
if not url:
|
||||
log.warning("CACHE_URL not set; running without cache")
|
||||
_client = None
|
||||
return
|
||||
try:
|
||||
client = redis.Redis.from_url(
|
||||
url,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=1.0,
|
||||
socket_timeout=1.0,
|
||||
)
|
||||
client.ping()
|
||||
_client = client
|
||||
_failures = 0
|
||||
log.info("cache connected")
|
||||
except Exception as exc:
|
||||
log.warning("cache unavailable at startup: %s; running in degraded mode", exc)
|
||||
_client = None
|
||||
|
||||
|
||||
def close_cache() -> None:
|
||||
global _client
|
||||
if _client is not None:
|
||||
try:
|
||||
_client.close()
|
||||
except Exception:
|
||||
pass
|
||||
_client = None
|
||||
|
||||
|
||||
def _note_failure() -> None:
|
||||
global _client, _failures
|
||||
_failures += 1
|
||||
if _failures >= _MAX_FAILURES_BEFORE_DISABLE and _client is not None:
|
||||
log.warning(
|
||||
"cache disabled after %d consecutive failures; running in degraded mode",
|
||||
_failures,
|
||||
)
|
||||
try:
|
||||
_client.close()
|
||||
except Exception:
|
||||
pass
|
||||
_client = None
|
||||
|
||||
|
||||
def _note_success() -> None:
|
||||
global _failures
|
||||
_failures = 0
|
||||
|
||||
|
||||
def is_available() -> bool:
|
||||
return _client is not None
|
||||
|
||||
|
||||
def get_user_id(token_hash: str) -> Optional[str]:
|
||||
if _client is None:
|
||||
return None
|
||||
try:
|
||||
value = _client.get(f"session:{token_hash}")
|
||||
_note_success()
|
||||
return value
|
||||
except Exception as exc:
|
||||
log.warning("cache get failed: %s", exc)
|
||||
_note_failure()
|
||||
return None
|
||||
|
||||
|
||||
def set_user_id(token_hash: str, user_id: str, ttl_seconds: int) -> None:
|
||||
if _client is None:
|
||||
return
|
||||
if ttl_seconds <= 0:
|
||||
return
|
||||
try:
|
||||
_client.setex(f"session:{token_hash}", ttl_seconds, user_id)
|
||||
_note_success()
|
||||
except Exception as exc:
|
||||
log.warning("cache set failed: %s", exc)
|
||||
try:
|
||||
_note_failure()
|
||||
except Exception as inner:
|
||||
log.warning("cache failure handler crashed: %s", inner)
|
||||
|
||||
|
||||
def invalidate(token_hash: str) -> None:
|
||||
if _client is None:
|
||||
return
|
||||
try:
|
||||
_client.delete(f"session:{token_hash}")
|
||||
_note_success()
|
||||
except Exception as exc:
|
||||
log.warning("cache delete failed: %s", exc)
|
||||
_note_failure()
|
||||
+5
-2
@@ -34,6 +34,7 @@ from .schemas import (
|
||||
User,
|
||||
)
|
||||
from .store import ApiError, BadRequest, Conflict, NotFound, Unauthorized, store, iso
|
||||
from .cache import close_cache, init_cache
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s"
|
||||
@@ -44,12 +45,14 @@ log = logging.getLogger("messenger")
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
init_pool()
|
||||
log.info("db pool initialized")
|
||||
init_cache()
|
||||
log.info("db pool and cache initialized")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
close_cache()
|
||||
close_pool()
|
||||
log.info("db pool closed")
|
||||
log.info("db pool and cache closed")
|
||||
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger lab2", version="1.2.0", lifespan=lifespan)
|
||||
|
||||
Reference in New Issue
Block a user