chore: import application foundation from lab1
This commit is contained in:
+202
@@ -0,0 +1,202 @@
|
||||
import logging
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, HTTPException, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from .models import Chat, CreateChat, CreateMessage, CreateUser, User
|
||||
from .store import InMemoryStore
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
store = InMemoryStore()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
logger.info("Application startup")
|
||||
yield
|
||||
logger.info("Application shutdown")
|
||||
|
||||
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def add_request_id(request: Request, call_next):
|
||||
request_id = str(uuid.uuid4())
|
||||
request.state.request_id = request_id
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
logger.exception("Unhandled request error; request_id=%s", request_id)
|
||||
response = JSONResponse(
|
||||
status_code=500,
|
||||
content={
|
||||
"error": {
|
||||
"code": "internal_error",
|
||||
"message": "Unexpected error",
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
request_id = request.state.request_id
|
||||
error_code_map = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
413: "payload_too_large",
|
||||
415: "unsupported_media_type",
|
||||
429: "rate_limited",
|
||||
500: "internal_error",
|
||||
503: "unavailable",
|
||||
}
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={
|
||||
"error": {
|
||||
"code": error_code_map.get(exc.status_code, "internal_error"),
|
||||
"message": exc.detail if isinstance(exc.detail, str) else "Request failed",
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
request_id = request.state.request_id
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content={
|
||||
"error": {
|
||||
"code": "invalid_request",
|
||||
"message": "Validation error",
|
||||
"request_id": request_id,
|
||||
}
|
||||
},
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
|
||||
|
||||
def get_current_user(x_user_id: Optional[str] = Header(default=None)) -> User:
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||
user = store.get_user(x_user_id)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||
return user
|
||||
|
||||
|
||||
def validate_chat_uuid(chat_id: str) -> None:
|
||||
try:
|
||||
parsed = uuid.UUID(chat_id)
|
||||
if str(parsed) != chat_id.lower():
|
||||
raise ValueError("non-canonical UUID")
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
raise HTTPException(status_code=400, detail="Invalid chat UUID") from None
|
||||
|
||||
|
||||
@app.get("/health/live")
|
||||
def liveness():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
def readiness():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.post("/api/v1/users", status_code=201)
|
||||
def register_user(body: CreateUser):
|
||||
try:
|
||||
return store.create_user(body.username, body.display_name)
|
||||
except ValueError as exc:
|
||||
if str(exc) == "conflict":
|
||||
raise HTTPException(status_code=409, detail="Username already exists") from None
|
||||
raise HTTPException(status_code=400, detail="Invalid request") from None
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
def current_user(user: User = Depends(get_current_user)):
|
||||
return user
|
||||
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201)
|
||||
def create_chat(body: CreateChat, user: User = Depends(get_current_user)):
|
||||
try:
|
||||
return store.create_chat(body.title, body.member_ids, user.id)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid members or missing creator") from None
|
||||
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
def list_chats(
|
||||
limit: int = 50,
|
||||
cursor: Optional[str] = None,
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(status_code=400, detail="Limit out of range")
|
||||
try:
|
||||
items, next_cursor = store.list_chats(user.id, limit, cursor)
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid cursor") from None
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
def get_chat(chat_id: str, user: User = Depends(get_current_user)):
|
||||
validate_chat_uuid(chat_id)
|
||||
chat = store.get_chat(chat_id, user.id)
|
||||
if chat is None:
|
||||
raise HTTPException(status_code=404, detail="Chat not found or access denied")
|
||||
return chat
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
def create_message(
|
||||
chat_id: str,
|
||||
body: CreateMessage,
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
validate_chat_uuid(chat_id)
|
||||
try:
|
||||
return store.create_message(chat_id, user.id, body.text)
|
||||
except ValueError as exc:
|
||||
if str(exc) == "not_found":
|
||||
raise HTTPException(status_code=404, detail="Chat not found or access denied") from None
|
||||
raise HTTPException(status_code=400, detail="Invalid request") from None
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
def list_messages(
|
||||
chat_id: str,
|
||||
limit: int = 50,
|
||||
cursor: Optional[str] = None,
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
validate_chat_uuid(chat_id)
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(status_code=400, detail="Limit out of range")
|
||||
try:
|
||||
items, next_cursor = store.list_messages(chat_id, user.id, limit, cursor)
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
except ValueError as exc:
|
||||
if str(exc) == "not_found":
|
||||
raise HTTPException(status_code=404, detail="Chat not found or access denied") from None
|
||||
raise HTTPException(status_code=400, detail="Invalid cursor") from None
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
class BaseConfig(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
json_encoders={
|
||||
datetime: lambda value: value.astimezone(timezone.utc)
|
||||
.isoformat(timespec="microseconds")
|
||||
.replace("+00:00", "Z")
|
||||
if value
|
||||
else None
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class CreateUser(BaseConfig):
|
||||
username: str = Field(..., pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(..., min_length=1, max_length=100)
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def validate_display_name(cls, value: str) -> str:
|
||||
value = value.strip()
|
||||
if not value:
|
||||
raise ValueError("display_name must not be blank")
|
||||
return value
|
||||
|
||||
|
||||
class User(CreateUser):
|
||||
id: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class CreateChat(BaseConfig):
|
||||
title: str = Field(..., min_length=1, max_length=100)
|
||||
member_ids: List[str] = Field(..., min_length=1, max_length=100)
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def validate_title(cls, value: str) -> str:
|
||||
value = value.strip()
|
||||
if not value:
|
||||
raise ValueError("title must not be blank")
|
||||
return value
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def validate_unique_members(cls, value: List[str]) -> List[str]:
|
||||
if len(value) != len(set(value)):
|
||||
raise ValueError("member_ids must be unique")
|
||||
return value
|
||||
|
||||
|
||||
class Chat(CreateChat):
|
||||
id: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class CreateMessage(BaseConfig):
|
||||
text: str = Field(..., min_length=1, max_length=4000)
|
||||
|
||||
@field_validator("text")
|
||||
@classmethod
|
||||
def validate_text(cls, value: str) -> str:
|
||||
value = value.strip()
|
||||
if not value:
|
||||
raise ValueError("text must not be blank")
|
||||
return value
|
||||
|
||||
|
||||
class Message(CreateMessage):
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class Health(BaseConfig):
|
||||
status: str = "ok"
|
||||
|
||||
|
||||
class ErrorDetail(BaseConfig):
|
||||
code: str
|
||||
message: str
|
||||
request_id: str
|
||||
|
||||
|
||||
class ErrorResponse(BaseConfig):
|
||||
error: ErrorDetail
|
||||
|
||||
|
||||
class ChatPage(BaseConfig):
|
||||
items: List[Chat]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class MessagePage(BaseConfig):
|
||||
items: List[Message]
|
||||
next_cursor: Optional[str] = None
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
import base64
|
||||
import bisect
|
||||
import binascii
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
from .models import Chat, Message, User
|
||||
|
||||
|
||||
Key = Tuple[datetime, str]
|
||||
|
||||
|
||||
def _encode_cursor(kind: str, scope: str, item) -> str:
|
||||
payload = {
|
||||
"v": 1,
|
||||
"kind": kind,
|
||||
"scope": scope,
|
||||
"created_at": item.created_at.isoformat(),
|
||||
"id": item.id,
|
||||
}
|
||||
raw = json.dumps(payload, separators=(",", ":")).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _decode_cursor(cursor: str, kind: str, scope: str) -> Key:
|
||||
try:
|
||||
if not cursor or len(cursor) > 4096:
|
||||
raise ValueError
|
||||
padded = cursor + "=" * (-len(cursor) % 4)
|
||||
raw = base64.b64decode(padded, altchars=b"-_", validate=True)
|
||||
payload = json.loads(raw.decode("utf-8"))
|
||||
if not isinstance(payload, dict) or payload.get("v") != 1:
|
||||
raise ValueError
|
||||
if payload.get("kind") != kind or payload.get("scope") != scope:
|
||||
raise ValueError
|
||||
item_id = payload.get("id")
|
||||
timestamp = payload.get("created_at")
|
||||
if not isinstance(item_id, str) or not isinstance(timestamp, str):
|
||||
raise ValueError
|
||||
created_at = datetime.fromisoformat(timestamp)
|
||||
if created_at.tzinfo is None:
|
||||
raise ValueError
|
||||
created_at = created_at.astimezone(timezone.utc)
|
||||
return created_at, item_id
|
||||
except (
|
||||
ValueError,
|
||||
TypeError,
|
||||
KeyError,
|
||||
UnicodeDecodeError,
|
||||
json.JSONDecodeError,
|
||||
binascii.Error,
|
||||
):
|
||||
raise ValueError("invalid_request") from None
|
||||
|
||||
|
||||
class InMemoryStore:
|
||||
def __init__(self):
|
||||
self._lock = threading.RLock()
|
||||
self.users: Dict[str, User] = {}
|
||||
self.chats: Dict[str, Chat] = {}
|
||||
self.messages: Dict[str, List[Message]] = {}
|
||||
self.usernames: Dict[str, str] = {}
|
||||
self.message_keys: Dict[str, List[Key]] = {}
|
||||
self.message_index_enabled = os.getenv("MESSAGE_INDEX_ENABLED", "1") != "0"
|
||||
|
||||
def create_user(self, username: str, display_name: str) -> User:
|
||||
with self._lock:
|
||||
if username in self.usernames:
|
||||
raise ValueError("conflict")
|
||||
user_id = str(uuid.uuid4())
|
||||
user = User(
|
||||
id=user_id,
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
self.users[user_id] = user
|
||||
self.usernames[username] = user_id
|
||||
return user
|
||||
|
||||
def get_user(self, user_id: str) -> Optional[User]:
|
||||
with self._lock:
|
||||
return self.users.get(user_id)
|
||||
|
||||
def create_chat(self, title: str, member_ids: List[str], creator_id: str) -> Chat:
|
||||
with self._lock:
|
||||
if creator_id not in member_ids or len(member_ids) != len(set(member_ids)):
|
||||
raise ValueError("invalid_request")
|
||||
if any(member_id not in self.users for member_id in member_ids):
|
||||
raise ValueError("invalid_request")
|
||||
|
||||
chat_id = str(uuid.uuid4())
|
||||
chat = Chat(
|
||||
id=chat_id,
|
||||
title=title,
|
||||
member_ids=list(member_ids),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
self.chats[chat_id] = chat
|
||||
self.messages[chat_id] = []
|
||||
self.message_keys[chat_id] = []
|
||||
return chat
|
||||
|
||||
def get_chat(self, chat_id: str, user_id: str) -> Optional[Chat]:
|
||||
with self._lock:
|
||||
chat = self.chats.get(chat_id)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
return None
|
||||
return chat
|
||||
|
||||
def list_chats(
|
||||
self, user_id: str, limit: int, cursor: Optional[str]
|
||||
) -> Tuple[List[Chat], Optional[str]]:
|
||||
with self._lock:
|
||||
user_chats = [chat for chat in self.chats.values() if user_id in chat.member_ids]
|
||||
user_chats.sort(key=lambda chat: (chat.created_at, chat.id))
|
||||
keys = [(chat.created_at, chat.id) for chat in user_chats]
|
||||
|
||||
start_index = 0
|
||||
if cursor:
|
||||
target_key = _decode_cursor(cursor, kind="chats", scope=user_id)
|
||||
start_index = bisect.bisect_right(keys, target_key)
|
||||
|
||||
page_with_extra = user_chats[start_index : start_index + limit + 1]
|
||||
has_next = len(page_with_extra) > limit
|
||||
page = page_with_extra[:limit]
|
||||
next_cursor = None
|
||||
if has_next and page:
|
||||
next_cursor = _encode_cursor("chats", user_id, page[-1])
|
||||
return page, next_cursor
|
||||
|
||||
def create_message(self, chat_id: str, sender_id: str, text: str) -> Message:
|
||||
with self._lock:
|
||||
chat = self.chats.get(chat_id)
|
||||
if chat is None or sender_id not in chat.member_ids:
|
||||
raise ValueError("not_found")
|
||||
|
||||
message = Message(
|
||||
id=str(uuid.uuid4()),
|
||||
chat_id=chat_id,
|
||||
sender_id=sender_id,
|
||||
text=text,
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
messages = self.messages[chat_id]
|
||||
keys = self.message_keys[chat_id]
|
||||
key = (message.created_at, message.id)
|
||||
|
||||
if self.message_index_enabled:
|
||||
index = bisect.bisect_right(keys, key)
|
||||
keys.insert(index, key)
|
||||
messages.insert(index, message)
|
||||
else:
|
||||
current_keys = [(item.created_at, item.id) for item in messages]
|
||||
index = bisect.bisect_right(current_keys, key)
|
||||
messages.insert(index, message)
|
||||
keys.insert(index, key)
|
||||
return message
|
||||
|
||||
def list_messages(
|
||||
self,
|
||||
chat_id: str,
|
||||
user_id: str,
|
||||
limit: int,
|
||||
cursor: Optional[str],
|
||||
) -> Tuple[List[Message], Optional[str]]:
|
||||
with self._lock:
|
||||
chat = self.chats.get(chat_id)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise ValueError("not_found")
|
||||
|
||||
messages = self.messages[chat_id]
|
||||
if self.message_index_enabled:
|
||||
keys = self.message_keys[chat_id]
|
||||
else:
|
||||
keys = [(item.created_at, item.id) for item in messages]
|
||||
|
||||
start_index = 0
|
||||
if cursor:
|
||||
target_key = _decode_cursor(cursor, kind="messages", scope=chat_id)
|
||||
start_index = bisect.bisect_right(keys, target_key)
|
||||
|
||||
page_with_extra = messages[start_index : start_index + limit + 1]
|
||||
has_next = len(page_with_extra) > limit
|
||||
page = page_with_extra[:limit]
|
||||
next_cursor = None
|
||||
if has_next and page:
|
||||
next_cursor = _encode_cursor("messages", chat_id, page[-1])
|
||||
return page, next_cursor
|
||||
Reference in New Issue
Block a user