Lab2 final implementation and validation
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -6,6 +6,7 @@ import os
|
||||
import secrets
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
import psycopg
|
||||
@@ -120,7 +121,12 @@ 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)
|
||||
return psycopg.connect(
|
||||
self.connection_url,
|
||||
connect_timeout=5,
|
||||
autocommit=False,
|
||||
options="-c statement_timeout=5000 -c lock_timeout=500",
|
||||
)
|
||||
|
||||
def cache_client(self):
|
||||
return redis.Redis.from_url(self.cache_url, decode_responses=True, socket_connect_timeout=2, socket_timeout=2)
|
||||
@@ -142,7 +148,7 @@ class Store:
|
||||
except redis.RedisError:
|
||||
return
|
||||
|
||||
def get_cached_session(self, token: str) -> Optional[Dict[str, Any]]:
|
||||
def get_cached_session(self, token: str, *, conn=None) -> Optional[Dict[str, Any]]:
|
||||
if self.session_store != "valkey":
|
||||
return None
|
||||
try:
|
||||
@@ -161,6 +167,14 @@ 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):
|
||||
client.delete(f"session:{token}")
|
||||
return None
|
||||
return session
|
||||
except (redis.RedisError, TypeError, ValueError):
|
||||
return None
|
||||
@@ -182,79 +196,40 @@ class Store:
|
||||
raise ValueError("invalid session expiry")
|
||||
|
||||
def init(self) -> None:
|
||||
migration_dir = Path(__file__).resolve().parent / "migrations"
|
||||
with self.connect() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
display_name TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version TEXT PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS chats (
|
||||
id UUID PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS chat_members (
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
text TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
id UUID PRIMARY KEY,
|
||||
token TEXT NOT NULL UNIQUE,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
revoked_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_messages_chat_created ON messages(chat_id, created_at, id);"
|
||||
)
|
||||
cur.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_chat_members_user ON chat_members(user_id, chat_id);"
|
||||
)
|
||||
cur.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_chats_created ON chats(created_at, id);"
|
||||
)
|
||||
cur.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id, expires_at);"
|
||||
)
|
||||
|
||||
applied = set()
|
||||
cur.execute("SELECT version FROM schema_migrations")
|
||||
for (version,) in cur.fetchall():
|
||||
applied.add(version)
|
||||
|
||||
for migration_path in sorted(migration_dir.glob("*.sql")):
|
||||
version = migration_path.stem
|
||||
if version in applied:
|
||||
continue
|
||||
sql = migration_path.read_text(encoding="utf-8")
|
||||
cur.execute(sql)
|
||||
cur.execute(
|
||||
"INSERT INTO schema_migrations(version, applied_at) VALUES (%s, %s)",
|
||||
(version, self.utc_now()),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
def utc_now(self) -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
def isoformat_utc(self, value: datetime) -> str:
|
||||
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
def hash_password(self, password: str) -> str:
|
||||
return self.password_hasher.hash(password)
|
||||
@@ -293,6 +268,28 @@ class Store:
|
||||
"created_at": self.isoformat_utc(row[3]),
|
||||
}
|
||||
|
||||
def fetch_session_by_token(self, token: str, conn):
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT s.token, s.user_id, s.expires_at, s.revoked_at, u.id, u.username, u.display_name, u.created_at FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token = %s",
|
||||
(token,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return {
|
||||
"token": row[0],
|
||||
"user_id": str(row[1]),
|
||||
"expires_at": self.isoformat_utc(row[2]),
|
||||
"revoked_at": row[3],
|
||||
"user": {
|
||||
"id": str(row[4]),
|
||||
"username": row[5],
|
||||
"display_name": row[6],
|
||||
"created_at": self.isoformat_utc(row[7]),
|
||||
},
|
||||
}
|
||||
|
||||
def list_member_ids(self, chat_id: str, conn) -> List[str]:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id", (chat_id,))
|
||||
@@ -383,19 +380,40 @@ class Store:
|
||||
"created_at": self.isoformat_utc(now),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def cursor_uuid_key(value: str) -> int:
|
||||
try:
|
||||
return uuid.UUID(value).int
|
||||
except (ValueError, TypeError):
|
||||
return 0
|
||||
|
||||
def list_chats_for_user(self, user_id: str, limit: int, cursor: Optional[str]):
|
||||
with self.connect() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
query = """
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = %s
|
||||
ORDER BY c.created_at ASC, c.id ASC
|
||||
""",
|
||||
(user_id,),
|
||||
)
|
||||
"""
|
||||
params: List[Any] = [user_id]
|
||||
if cursor:
|
||||
prefix = f"user:{user_id}|"
|
||||
if not cursor.startswith(prefix):
|
||||
raise ApiError(400, "invalid_request", "cursor does not match user chat list")
|
||||
remainder = cursor[len(prefix):]
|
||||
if not remainder:
|
||||
raise ApiError(400, "invalid_request", "invalid cursor")
|
||||
try:
|
||||
cursor_ts_raw, cursor_id = remainder.split("|", 1)
|
||||
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 (c.created_at > %s OR (c.created_at = %s AND c.id > %s::uuid))"
|
||||
params.extend([cursor_dt, cursor_dt, cursor_id])
|
||||
query += " ORDER BY c.created_at ASC, c.id ASC LIMIT %s"
|
||||
params.append(limit + 1)
|
||||
cur.execute(query, tuple(params))
|
||||
rows = cur.fetchall()
|
||||
items = [
|
||||
{
|
||||
@@ -407,42 +425,36 @@ class Store:
|
||||
for row in rows
|
||||
]
|
||||
|
||||
start_index = 0
|
||||
if cursor:
|
||||
prefix = f"user:{user_id}|"
|
||||
if not cursor.startswith(prefix):
|
||||
raise ApiError(400, "invalid_request", "cursor does not match user chat list")
|
||||
remainder = cursor[len(prefix):]
|
||||
if not remainder:
|
||||
raise ApiError(400, "invalid_request", "invalid cursor")
|
||||
try:
|
||||
cursor_ts_raw, cursor_id = remainder.split("|", 1)
|
||||
cursor_dt = datetime.fromisoformat(cursor_ts_raw.replace("Z", "+00:00"))
|
||||
except ValueError as exc:
|
||||
raise ApiError(400, "invalid_request", "invalid cursor") from exc
|
||||
for idx, item in enumerate(items):
|
||||
item_dt = datetime.fromisoformat(item["created_at"].replace("Z", "+00:00"))
|
||||
if (item_dt, item["id"]) > (cursor_dt.astimezone(timezone.utc), cursor_id):
|
||||
start_index = idx
|
||||
break
|
||||
else:
|
||||
start_index = len(items)
|
||||
|
||||
page = items[start_index:start_index + limit]
|
||||
next_cursor = None
|
||||
if start_index + limit < len(items):
|
||||
last_item = page[-1]
|
||||
if len(items) > limit:
|
||||
last_item = items[limit - 1]
|
||||
next_cursor = f"user:{user_id}|{last_item['created_at']}|{last_item['id']}"
|
||||
items = items[:limit]
|
||||
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
def list_messages_for_chat(self, chat_id: str, limit: int, cursor: Optional[str]):
|
||||
with self.connect() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = %s ORDER BY created_at ASC, id ASC",
|
||||
(chat_id,),
|
||||
)
|
||||
query = "SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = %s"
|
||||
params: List[Any] = [chat_id]
|
||||
if cursor:
|
||||
prefix = f"chat:{chat_id}|"
|
||||
if not cursor.startswith(prefix):
|
||||
raise ApiError(400, "invalid_request", "cursor does not match chat")
|
||||
remainder = cursor[len(prefix):]
|
||||
if not remainder:
|
||||
raise ApiError(400, "invalid_request", "invalid cursor")
|
||||
try:
|
||||
cursor_ts_raw, cursor_id = remainder.split("|", 1)
|
||||
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 += " ORDER BY created_at ASC, id ASC LIMIT %s"
|
||||
params.append(limit + 1)
|
||||
cur.execute(query, tuple(params))
|
||||
rows = cur.fetchall()
|
||||
|
||||
items = [{
|
||||
@@ -453,34 +465,13 @@ class Store:
|
||||
"created_at": self.isoformat_utc(row[4]),
|
||||
} for row in rows]
|
||||
|
||||
start_index = 0
|
||||
if cursor:
|
||||
prefix = f"chat:{chat_id}|"
|
||||
if not cursor.startswith(prefix):
|
||||
raise ApiError(400, "invalid_request", "cursor does not match chat")
|
||||
remainder = cursor[len(prefix):]
|
||||
if not remainder:
|
||||
raise ApiError(400, "invalid_request", "invalid cursor")
|
||||
try:
|
||||
cursor_ts_raw, cursor_id = remainder.split("|", 1)
|
||||
cursor_dt = datetime.fromisoformat(cursor_ts_raw.replace("Z", "+00:00"))
|
||||
except ValueError as exc:
|
||||
raise ApiError(400, "invalid_request", "invalid cursor") from exc
|
||||
for idx, item in enumerate(items):
|
||||
item_dt = datetime.fromisoformat(item["created_at"].replace("Z", "+00:00"))
|
||||
if (item_dt, item["id"]) > (cursor_dt.astimezone(timezone.utc), cursor_id):
|
||||
start_index = idx
|
||||
break
|
||||
else:
|
||||
start_index = len(items)
|
||||
|
||||
page = items[start_index:start_index + limit]
|
||||
next_cursor = None
|
||||
if start_index + limit < len(items):
|
||||
last_item = page[-1]
|
||||
if len(items) > limit:
|
||||
last_item = items[limit - 1]
|
||||
next_cursor = f"chat:{chat_id}|{last_item['created_at']}|{last_item['id']}"
|
||||
items = items[:limit]
|
||||
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
def create_session(self, user_id: str, username: str):
|
||||
token = secrets.token_urlsafe(32)
|
||||
@@ -511,37 +502,18 @@ class Store:
|
||||
}
|
||||
|
||||
def get_session_by_token(self, token: str, conn=None):
|
||||
cached = self.get_cached_session(token)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
should_close = conn is None
|
||||
conn = conn or self.connect()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT s.token, s.user_id, s.expires_at, s.revoked_at, u.id, u.username, u.display_name, u.created_at FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token = %s",
|
||||
(token,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
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
|
||||
session = {
|
||||
"token": row[0],
|
||||
"user_id": str(row[1]),
|
||||
"expires_at": self.isoformat_utc(row[2]),
|
||||
"revoked_at": row[3],
|
||||
"user": {
|
||||
"id": str(row[4]),
|
||||
"username": row[5],
|
||||
"display_name": row[6],
|
||||
"created_at": self.isoformat_utc(row[7]),
|
||||
},
|
||||
}
|
||||
if not self.is_session_valid(session):
|
||||
return None
|
||||
self.cache_session(session)
|
||||
return session
|
||||
cached = self.get_cached_session(token, conn=conn)
|
||||
if cached is not None:
|
||||
return cached
|
||||
self.cache_session(db_session)
|
||||
return db_session
|
||||
finally:
|
||||
if should_close:
|
||||
conn.close()
|
||||
@@ -669,8 +641,9 @@ async def create_user_endpoint(request: Request):
|
||||
payload = CreateUserIn.model_validate(body)
|
||||
except ValidationError as exc:
|
||||
raise ApiError(400, "invalid_request", "invalid user payload") from exc
|
||||
if not payload.username or not payload.display_name:
|
||||
if not payload.username or not payload.display_name.strip():
|
||||
raise ApiError(400, "invalid_request", "invalid request")
|
||||
payload.display_name = payload.display_name.strip()
|
||||
try:
|
||||
user = store.insert_user(payload.username, payload.display_name, payload.password)
|
||||
return UserOut.model_validate(user)
|
||||
@@ -741,6 +714,9 @@ async def create_chat_endpoint(request: Request):
|
||||
raise ApiError(400, "invalid_request", "invalid chat payload") from exc
|
||||
if len(payload.member_ids) < 1 or len(payload.member_ids) > 100:
|
||||
raise ApiError(400, "invalid_request", "invalid member_ids")
|
||||
title = payload.title.strip()
|
||||
if not title:
|
||||
raise ApiError(400, "invalid_request", "invalid title")
|
||||
normalized = []
|
||||
seen = set()
|
||||
for member_id in payload.member_ids:
|
||||
@@ -761,7 +737,7 @@ 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(payload.title.strip(), normalized, session["user_id"])
|
||||
chat = store.insert_chat(title, normalized, session["user_id"])
|
||||
return ChatOut.model_validate(chat)
|
||||
except ApiError:
|
||||
raise
|
||||
@@ -817,6 +793,7 @@ async def create_message(request: Request, chat_id: str):
|
||||
raise ApiError(400, "invalid_request", "invalid message payload") from exc
|
||||
if not payload.text.strip():
|
||||
raise ApiError(400, "invalid_request", "invalid text")
|
||||
payload.text = payload.text.strip()
|
||||
with store.connect() as conn:
|
||||
chat = store.fetch_chat(chat_id, conn)
|
||||
if chat is None or not store.fetch_chat_membership(chat_id, session["user_id"], conn):
|
||||
|
||||
Reference in New Issue
Block a user