forked from mtusi2026/mtusi2026lab2
Fix cached session identity and document PR 63 regression checks
This commit is contained in:
@@ -10,6 +10,7 @@ from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
import psycopg
|
||||
from psycopg_pool import ConnectionPool
|
||||
import redis
|
||||
from argon2 import PasswordHasher
|
||||
from fastapi import FastAPI, Header, HTTPException, Request
|
||||
@@ -99,6 +100,13 @@ class Store:
|
||||
self.cache_url = self._resolve_cache_url()
|
||||
self.session_store = os.getenv("SESSION_STORE", "valkey")
|
||||
self.password_hasher = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=2, hash_len=32, salt_len=16)
|
||||
self.pool = ConnectionPool(
|
||||
self.connection_url, min_size=1,
|
||||
max_size=int(os.getenv("DB_POOL_MAX_SIZE", "10")),
|
||||
timeout=5, max_waiting=20, open=False,
|
||||
kwargs={"connect_timeout": 5, "autocommit": False,
|
||||
"options": "-c statement_timeout=5000 -c lock_timeout=500"},
|
||||
)
|
||||
|
||||
def _resolve_database_url(self) -> str:
|
||||
value = os.getenv("DATABASE_URL")
|
||||
@@ -121,12 +129,7 @@ class Store:
|
||||
return os.getenv("DEFAULT_CACHE_URL", "redis://localhost:6379/0")
|
||||
|
||||
def connect(self):
|
||||
return psycopg.connect(
|
||||
self.connection_url,
|
||||
connect_timeout=5,
|
||||
autocommit=False,
|
||||
options="-c statement_timeout=5000 -c lock_timeout=500",
|
||||
)
|
||||
return self.pool.connection()
|
||||
|
||||
def cache_client(self):
|
||||
return redis.Redis.from_url(self.cache_url, decode_responses=True, socket_connect_timeout=2, socket_timeout=2)
|
||||
@@ -148,7 +151,7 @@ class Store:
|
||||
except redis.RedisError:
|
||||
return
|
||||
|
||||
def get_cached_session(self, token: str, *, conn=None) -> Optional[Dict[str, Any]]:
|
||||
def get_cached_session(self, token: str, *, db_session) -> Optional[Dict[str, Any]]:
|
||||
if self.session_store != "valkey":
|
||||
return None
|
||||
try:
|
||||
@@ -167,16 +170,11 @@ class Store:
|
||||
if not self.is_session_valid(session):
|
||||
client.delete(f"session:{token}")
|
||||
return None
|
||||
if conn is None:
|
||||
with self.connect() as db_conn:
|
||||
db_session = self.fetch_session_by_token(token, db_conn)
|
||||
else:
|
||||
db_session = self.fetch_session_by_token(token, conn)
|
||||
if db_session is None or not self.is_session_valid(db_session):
|
||||
if session != db_session:
|
||||
client.delete(f"session:{token}")
|
||||
return None
|
||||
return session
|
||||
except (redis.RedisError, TypeError, ValueError):
|
||||
return db_session
|
||||
except (redis.RedisError, KeyError, TypeError, ValueError):
|
||||
return None
|
||||
|
||||
def delete_cached_session(self, token: str) -> None:
|
||||
@@ -450,8 +448,8 @@ class Store:
|
||||
cursor_dt = datetime.fromisoformat(cursor_ts_raw.replace("Z", "+00:00")).astimezone(timezone.utc)
|
||||
except ValueError as exc:
|
||||
raise ApiError(400, "invalid_request", "invalid cursor") from exc
|
||||
query += " AND (created_at > %s OR (created_at = %s AND id > %s::uuid))"
|
||||
params.extend([cursor_dt, cursor_dt, cursor_id])
|
||||
query += " AND (created_at, id) > (%s, %s::uuid)"
|
||||
params.extend([cursor_dt, cursor_id])
|
||||
query += " ORDER BY created_at ASC, id ASC LIMIT %s"
|
||||
params.append(limit + 1)
|
||||
cur.execute(query, tuple(params))
|
||||
@@ -483,7 +481,8 @@ class Store:
|
||||
(uuid.uuid4(), token, user_id, expires_at, self.utc_now()),
|
||||
)
|
||||
conn.commit()
|
||||
user = self.fetch_user(user_id, self.connect())
|
||||
with self.connect() as conn:
|
||||
user = self.fetch_user(user_id, conn)
|
||||
if user is None:
|
||||
raise ApiError(500, "internal_error", "session user missing")
|
||||
session = {
|
||||
@@ -502,21 +501,17 @@ class Store:
|
||||
}
|
||||
|
||||
def get_session_by_token(self, token: str, conn=None):
|
||||
should_close = conn is None
|
||||
conn = conn or self.connect()
|
||||
try:
|
||||
db_session = self.fetch_session_by_token(token, conn)
|
||||
if db_session is None or not self.is_session_valid(db_session):
|
||||
self.delete_cached_session(token)
|
||||
return None
|
||||
cached = self.get_cached_session(token, conn=conn)
|
||||
if cached is not None:
|
||||
return cached
|
||||
if conn is None:
|
||||
with self.connect() as db_conn:
|
||||
return self.get_session_by_token(token, db_conn)
|
||||
db_session = self.fetch_session_by_token(token, conn)
|
||||
if db_session is None or not self.is_session_valid(db_session):
|
||||
self.delete_cached_session(token)
|
||||
return None
|
||||
cached = self.get_cached_session(token, db_session=db_session)
|
||||
if cached is None:
|
||||
self.cache_session(db_session)
|
||||
return db_session
|
||||
finally:
|
||||
if should_close:
|
||||
conn.close()
|
||||
return db_session
|
||||
|
||||
def revoke_current_session(self, token: str):
|
||||
with self.connect() as conn:
|
||||
@@ -545,9 +540,20 @@ app = FastAPI(title="MTUSI Messenger")
|
||||
|
||||
@app.on_event("startup")
|
||||
def startup_event() -> None:
|
||||
store.pool.open(wait=True, timeout=10)
|
||||
store.init()
|
||||
|
||||
|
||||
@app.on_event("shutdown")
|
||||
def shutdown_event() -> None:
|
||||
store.pool.close()
|
||||
|
||||
|
||||
@app.exception_handler(psycopg.OperationalError)
|
||||
async def database_error_handler(request: Request, exc):
|
||||
return await api_error_handler(request, ApiError(503, "unavailable", "database unavailable"))
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_id_middleware(request: Request, call_next):
|
||||
request_id = uuid.uuid4().hex
|
||||
@@ -683,8 +689,8 @@ async def create_session(request: Request):
|
||||
user = store.require_user_by_username(username, conn)
|
||||
if user is None or not store.verify_password(user["password_hash"], password):
|
||||
raise ApiError(401, "unauthorized", "invalid credentials", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
|
||||
session = store.create_session(user["id"], username)
|
||||
return SessionOut.model_validate(session)
|
||||
session = store.create_session(user["id"], username)
|
||||
return SessionOut.model_validate(session)
|
||||
except ApiError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
@@ -737,8 +743,8 @@ async def create_chat_endpoint(request: Request):
|
||||
cur.execute("SELECT id FROM users WHERE id = %s", (member_id,))
|
||||
if cur.fetchone() is None:
|
||||
raise ApiError(400, "invalid_request", "unknown member")
|
||||
chat = store.insert_chat(title, normalized, session["user_id"])
|
||||
return ChatOut.model_validate(chat)
|
||||
chat = store.insert_chat(title, normalized, session["user_id"])
|
||||
return ChatOut.model_validate(chat)
|
||||
except ApiError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
@@ -798,7 +804,7 @@ async def create_message(request: Request, chat_id: str):
|
||||
chat = store.fetch_chat(chat_id, conn)
|
||||
if chat is None or not store.fetch_chat_membership(chat_id, session["user_id"], conn):
|
||||
raise ApiError(404, "not_found", "chat not found")
|
||||
message = store.insert_message(chat_id, session["user_id"], payload.text)
|
||||
message = store.insert_message(chat_id, session["user_id"], payload.text)
|
||||
return MessageOut.model_validate(message)
|
||||
|
||||
|
||||
@@ -820,7 +826,7 @@ async def list_messages(request: Request, chat_id: str):
|
||||
with store.connect() as conn:
|
||||
if not store.fetch_chat_membership(chat_id, session["user_id"], conn):
|
||||
raise ApiError(404, "not_found", "chat not found")
|
||||
result = store.list_messages_for_chat(chat_id, limit_int, cursor)
|
||||
result = store.list_messages_for_chat(chat_id, limit_int, cursor)
|
||||
return {"items": [MessageOut.model_validate(item) for item in result["items"]], "next_cursor": result["next_cursor"]}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user