forked from mtusi2026/mtusi2026lab2
lab1
This commit is contained in:
+22
@@ -0,0 +1,22 @@
|
||||
FROM python:3.11.7-slim-bookworm AS builder
|
||||
|
||||
WORKDIR /app
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
|
||||
|
||||
FROM python:3.11.7-slim-bookworm AS runner
|
||||
|
||||
RUN useradd -u 10001 -m appuser
|
||||
WORKDIR /home/appuser
|
||||
|
||||
COPY --from=builder /install /usr/local
|
||||
COPY app.py .
|
||||
|
||||
USER appuser
|
||||
EXPOSE 8080
|
||||
|
||||
HEALTHCHECK --interval=5s --timeout=3s --retries=3 \
|
||||
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health/ready')"
|
||||
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8080"]
|
||||
@@ -0,0 +1,295 @@
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Dict, List, Optional
|
||||
from uuid import UUID
|
||||
from fastapi import FastAPI, Header, HTTPException, Query, Response, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, Field, field_validator, ConfigDict
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger — lab1", version="1.1.0")
|
||||
|
||||
USERS: Dict[str, dict] = {}
|
||||
CHATS: Dict[str, dict] = {}
|
||||
MESSAGES: Dict[str, List[dict]] = {}
|
||||
|
||||
def generate_request_id() -> str:
|
||||
return uuid.uuid4().hex
|
||||
|
||||
def make_error_response(status_code: int, code: str, message: str, req_id: str) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
headers={"X-Request-Id": req_id},
|
||||
content={
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": req_id
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
req_id = request.headers.get("X-Request-Id") or generate_request_id()
|
||||
return make_error_response(400, "invalid_request", "Validation error in request body or parameters", req_id)
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
req_id = request.headers.get("X-Request-Id") or generate_request_id()
|
||||
detail = exc.detail
|
||||
if isinstance(detail, dict) and "error" in detail:
|
||||
detail["error"]["request_id"] = req_id
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
headers={"X-Request-Id": req_id},
|
||||
content=detail
|
||||
)
|
||||
|
||||
code_map = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
429: "rate_limited",
|
||||
503: "unavailable",
|
||||
500: "internal_error"
|
||||
}
|
||||
code = code_map.get(exc.status_code, "internal_error")
|
||||
return make_error_response(exc.status_code, code, str(detail), req_id)
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
username: str = Field(..., pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(..., min_length=1, max_length=100)
|
||||
|
||||
@field_validator("display_name")
|
||||
def not_blank(cls, v):
|
||||
if not v.strip():
|
||||
raise ValueError("Must not be blank")
|
||||
return v
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
title: str = Field(..., min_length=1, max_length=100)
|
||||
member_ids: List[uuid.UUID] = Field(..., min_items=1, max_items=100)
|
||||
|
||||
@field_validator("title")
|
||||
def not_blank(cls, v):
|
||||
if not v.strip():
|
||||
raise ValueError("Must not be blank")
|
||||
return v
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
text: str = Field(..., min_length=1, max_length=4000)
|
||||
|
||||
@field_validator("text")
|
||||
def not_blank(cls, v):
|
||||
if not v.strip():
|
||||
raise ValueError("Must not be blank")
|
||||
return v
|
||||
|
||||
@app.get("/health/live")
|
||||
def health_live(response: Response):
|
||||
req_id = generate_request_id()
|
||||
response.headers["X-Request-Id"] = req_id
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.get("/health/ready")
|
||||
def health_ready(response: Response):
|
||||
req_id = generate_request_id()
|
||||
response.headers["X-Request-Id"] = req_id
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.post("/api/v1/users", status_code=201)
|
||||
def register_user(body: CreateUser, response: Response):
|
||||
req_id = generate_request_id()
|
||||
response.headers["X-Request-Id"] = req_id
|
||||
|
||||
for u in USERS.values():
|
||||
if u["username"] == body.username:
|
||||
raise HTTPException(status_code=409, detail={"error": {"code": "conflict", "message": "Username already taken", "request_id": req_id}})
|
||||
|
||||
user_id = str(uuid.uuid4())
|
||||
created_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
user_obj = {
|
||||
"id": user_id,
|
||||
"username": body.username,
|
||||
"display_name": body.display_name,
|
||||
"created_at": created_at
|
||||
}
|
||||
USERS[user_id] = user_obj
|
||||
return user_obj
|
||||
|
||||
def get_current_user(x_user_id: Optional[str] = Header(None)) -> dict:
|
||||
if not x_user_id or x_user_id not in USERS:
|
||||
raise HTTPException(status_code=401, detail="Invalid or missing user identification")
|
||||
return USERS[x_user_id]
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
def current_user(response: Response, x_user_id: Optional[str] = Header(None)):
|
||||
req_id = generate_request_id()
|
||||
response.headers["X-Request-Id"] = req_id
|
||||
return get_current_user(x_user_id)
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201)
|
||||
def create_chat(body: CreateChat, response: Response, x_user_id: Optional[str] = Header(None)):
|
||||
req_id = generate_request_id()
|
||||
response.headers["X-Request-Id"] = req_id
|
||||
user = get_current_user(x_user_id)
|
||||
|
||||
member_ids_str = [str(mid) for mid in body.member_ids]
|
||||
|
||||
if user["id"] not in member_ids_str:
|
||||
raise HTTPException(status_code=400, detail="Caller must be in member_ids")
|
||||
if len(member_ids_str) != len(set(member_ids_str)):
|
||||
raise HTTPException(status_code=400, detail="Duplicate member IDs")
|
||||
for mid_str in member_ids_str:
|
||||
if mid_str not in USERS:
|
||||
raise HTTPException(status_code=400, detail=f"User {mid_str} not found")
|
||||
|
||||
chat_id = str(uuid.uuid4())
|
||||
created_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
chat_obj = {
|
||||
"id": chat_id,
|
||||
"title": body.title,
|
||||
"member_ids": member_ids_str,
|
||||
"created_at": created_at
|
||||
}
|
||||
CHATS[chat_id] = chat_obj
|
||||
MESSAGES[chat_id] = []
|
||||
return chat_obj
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
def list_chats(limit: int = 50, cursor: Optional[str] = None, response: Response = None, x_user_id: Optional[str] = Header(None)):
|
||||
req_id = generate_request_id()
|
||||
response.headers["X-Request-Id"] = req_id
|
||||
user = get_current_user(x_user_id)
|
||||
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(status_code=400, detail="Invalid limit")
|
||||
|
||||
user_chats = [c for c in CHATS.values() if user["id"] in c["member_ids"]]
|
||||
user_chats.sort(key=lambda x: (x["created_at"], x["id"]))
|
||||
|
||||
start_idx = 0
|
||||
if cursor:
|
||||
try:
|
||||
parts = cursor.split("_")
|
||||
if len(parts) < 2:
|
||||
raise ValueError("Malformed cursor")
|
||||
c_time, c_id = parts[0], parts[1]
|
||||
|
||||
found = False
|
||||
for idx, c in enumerate(user_chats):
|
||||
if (c["created_at"], c["id"]) > (c_time, c_id):
|
||||
start_idx = idx
|
||||
found = True
|
||||
break
|
||||
if (c["created_at"], c["id"]) == (c_time, c_id):
|
||||
start_idx = idx + 1
|
||||
found = True
|
||||
break
|
||||
if not found:
|
||||
raise HTTPException(status_code=400, detail="Invalid or foreign cursor")
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="Invalid cursor format")
|
||||
|
||||
page_items = user_chats[start_idx:start_idx + limit]
|
||||
next_cursor = None
|
||||
if start_idx + limit < len(user_chats):
|
||||
last = page_items[-1]
|
||||
next_cursor = f"{last['created_at']}_{last['id']}"
|
||||
|
||||
return {"items": page_items, "next_cursor": next_cursor}
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
def get_chat(chat_id: UUID, response: Response, x_user_id: Optional[str] = Header(None)):
|
||||
req_id = generate_request_id()
|
||||
response.headers["X-Request-Id"] = req_id
|
||||
user = get_current_user(x_user_id)
|
||||
|
||||
chat = CHATS.get(str(chat_id))
|
||||
if not chat or user["id"] not in chat["member_ids"]:
|
||||
raise HTTPException(status_code=404, detail="Chat not found")
|
||||
return chat
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
def create_message(chat_id: UUID, body: CreateMessage, response: Response, x_user_id: Optional[str] = Header(None)):
|
||||
req_id = generate_request_id()
|
||||
response.headers["X-Request-Id"] = req_id
|
||||
user = get_current_user(x_user_id)
|
||||
|
||||
chat_id_str = str(chat_id)
|
||||
chat = CHATS.get(chat_id_str)
|
||||
if not chat or user["id"] not in chat["member_ids"]:
|
||||
raise HTTPException(status_code=404, detail="Chat not found")
|
||||
|
||||
msg_id = str(uuid.uuid4())
|
||||
created_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
msg_obj = {
|
||||
"id": msg_id,
|
||||
"chat_id": chat_id_str,
|
||||
"sender_id": user["id"],
|
||||
"text": body.text,
|
||||
"created_at": created_at
|
||||
}
|
||||
|
||||
if chat_id_str not in MESSAGES:
|
||||
MESSAGES[chat_id_str] = []
|
||||
MESSAGES[chat_id_str].append(msg_obj)
|
||||
|
||||
return msg_obj
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
def list_messages(chat_id: UUID, limit: int = 50, cursor: Optional[str] = None, response: Response = None, x_user_id: Optional[str] = Header(None)):
|
||||
req_id = generate_request_id()
|
||||
response.headers["X-Request-Id"] = req_id
|
||||
user = get_current_user(x_user_id)
|
||||
|
||||
chat_id_str = str(chat_id)
|
||||
chat = CHATS.get(chat_id_str)
|
||||
if not chat or user["id"] not in chat["member_ids"]:
|
||||
raise HTTPException(status_code=404, detail="Chat not found")
|
||||
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(status_code=400, detail="Invalid limit")
|
||||
|
||||
msgs = MESSAGES.get(chat_id_str, [])
|
||||
msgs.sort(key=lambda x: (x["created_at"], x["id"]))
|
||||
|
||||
start_idx = 0
|
||||
if cursor:
|
||||
try:
|
||||
parts = cursor.split("_")
|
||||
if len(parts) < 2:
|
||||
raise ValueError("Malformed cursor")
|
||||
c_time, c_id = parts[0], parts[1]
|
||||
|
||||
found = False
|
||||
for idx, m in enumerate(msgs):
|
||||
if (m["created_at"], m["id"]) > (c_time, c_id):
|
||||
start_idx = idx
|
||||
found = True
|
||||
break
|
||||
if (m["created_at"], m["id"]) == (c_time, c_id):
|
||||
start_idx = idx + 1
|
||||
found = True
|
||||
break
|
||||
if not found:
|
||||
raise HTTPException(status_code=400, detail="Invalid or foreign cursor")
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="Invalid cursor format")
|
||||
|
||||
page_items = msgs[start_idx:start_idx + limit]
|
||||
next_cursor = None
|
||||
if start_idx + limit < len(msgs):
|
||||
last = page_items[-1]
|
||||
next_cursor = f"{last['created_at']}_{last['id']}"
|
||||
|
||||
return {"items": page_items, "next_cursor": next_cursor}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 1,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.14,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 10199,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 338.388,
|
||||
"successful_latency_ms": {
|
||||
"p50": 15.0,
|
||||
"p95": 31.0,
|
||||
"p99": 47.0
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 1,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 10.0,
|
||||
"elapsed_seconds": 10.062,
|
||||
"concurrency": 2,
|
||||
"successful_requests": 1284,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 127.609,
|
||||
"successful_latency_ms": {
|
||||
"p50": 16.0,
|
||||
"p95": 32.0,
|
||||
"p99": 47.0
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 1,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 10.0,
|
||||
"elapsed_seconds": 10.656,
|
||||
"concurrency": 32,
|
||||
"successful_requests": 5569,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 522.616,
|
||||
"successful_latency_ms": {
|
||||
"p50": 62.0,
|
||||
"p95": 78.0,
|
||||
"p99": 94.0
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 1,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 10.0,
|
||||
"elapsed_seconds": 10.156,
|
||||
"concurrency": 8,
|
||||
"successful_requests": 4663,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 459.137,
|
||||
"successful_latency_ms": {
|
||||
"p50": 16.0,
|
||||
"p95": 32.0,
|
||||
"p99": 47.0
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
fastapi==0.110.0
|
||||
uvicorn==0.28.0
|
||||
pydantic==2.6.2
|
||||
starlette==0.36.3
|
||||
idna==3.6
|
||||
anyio==4.3.0
|
||||
sniffio==1.3.1
|
||||
click==8.1.7
|
||||
h11==0.14.0
|
||||
annotated-types==0.6.0
|
||||
@@ -0,0 +1,109 @@
|
||||
import concurrent.futures
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import json
|
||||
import unittest
|
||||
from client import Client
|
||||
|
||||
class TestMessengerLab4(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.client = Client()
|
||||
self.alice = self.client.user("alice")
|
||||
self.bob = self.client.user("bob")
|
||||
self.eve = self.client.user("eve")
|
||||
|
||||
res = self.client.call(
|
||||
'POST', '/api/v1/chats', 201,
|
||||
actor=self.alice,
|
||||
body={"title": "Test Chat", "member_ids": [self.alice["id"], self.bob["id"]]},
|
||||
schema='Chat'
|
||||
)
|
||||
self.chat = res['json']
|
||||
|
||||
def test_unauthorized_access_to_chat(self):
|
||||
self.client.call('GET', f"/api/v1/chats/{self.chat['id']}", 404, actor=self.eve)
|
||||
|
||||
def test_empty_message(self):
|
||||
self.client.call('POST', f"/api/v1/chats/{self.chat['id']}/messages", 400, actor=self.alice, body={"text": ""})
|
||||
|
||||
def test_malformed_json(self):
|
||||
url = self.client.base + f"/api/v1/chats/{self.chat['id']}/messages"
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=b"{broken json content without quotes",
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-User-Id": self.alice["id"]
|
||||
},
|
||||
method="POST"
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req) as resp:
|
||||
self.fail("Expected HTTP 400 for malformed JSON")
|
||||
except urllib.error.HTTPError as e:
|
||||
self.assertEqual(e.code, 400)
|
||||
body = json.loads(e.read().decode())
|
||||
self.assertEqual(body["error"]["code"], "invalid_request")
|
||||
|
||||
def test_duplicate_username(self):
|
||||
self.client.call('POST', '/api/v1/users', 409, body=self.alice["registration"])
|
||||
|
||||
def test_pagination_multiple_pages(self):
|
||||
import time
|
||||
msg_texts = ["msg-page-1", "msg-page-2", "msg-page-3"]
|
||||
for txt in msg_texts:
|
||||
self.client.message(self.alice, self.chat, txt)
|
||||
time.sleep(0.01)
|
||||
|
||||
path = f"/api/v1/chats/{self.chat['id']}/messages"
|
||||
collected_items = []
|
||||
cursor = None
|
||||
|
||||
for _ in range(5):
|
||||
url_suffix = "?limit=1"
|
||||
if cursor:
|
||||
url_suffix += f"&cursor={cursor}"
|
||||
|
||||
page_res = self.client.call('GET', path + url_suffix, actor=self.alice, schema='MessagePage')
|
||||
page = page_res['json']
|
||||
|
||||
for item in page['items']:
|
||||
self.assertNotIn(item['id'], [x['id'] for x in collected_items])
|
||||
collected_items.append(item)
|
||||
|
||||
cursor = page.get('next_keyword') or page.get('next_cursor')
|
||||
if not cursor:
|
||||
break
|
||||
|
||||
self.assertEqual(len(collected_items), 3)
|
||||
self.assertEqual(sorted([x['text'] for x in collected_items]), sorted(msg_texts))
|
||||
|
||||
def test_concurrent_messages_strict(self):
|
||||
def worker_send(worker_idx):
|
||||
local_client = Client()
|
||||
ids = []
|
||||
for i in range(10):
|
||||
res = local_client.message(self.alice, self.chat, f"w-{worker_idx}-msg-{i}")
|
||||
ids.append(res['json']['id'])
|
||||
return ids
|
||||
|
||||
all_ids = []
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
|
||||
futures = [executor.submit(worker_send, w) for w in range(10)]
|
||||
for f in concurrent.futures.as_completed(futures):
|
||||
all_ids.extend(f.result())
|
||||
|
||||
self.assertEqual(len(all_ids), 100)
|
||||
self.assertEqual(len(set(all_ids)), 100)
|
||||
|
||||
page = self.client.call(
|
||||
'GET', f"/api/v1/chats/{self.chat['id']}/messages?limit=100",
|
||||
actor=self.alice,
|
||||
schema='MessagePage'
|
||||
)
|
||||
server_ids = [m['id'] for m in page['json']['items']]
|
||||
self.assertEqual(len(server_ids), 100)
|
||||
self.assertEqual(len(set(server_ids)), 100)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user