This commit is contained in:
Getlles
2026-11-16 17:38:53 +03:00
parent 3571422836
commit d475bf29ed
29 changed files with 620 additions and 228 deletions
+120 -94
View File
@@ -24,7 +24,7 @@ import redis
import boto3
from botocore.client import Config
app = FastAPI(title="MTUSI Messenger — lab4", version="1.4.0")
app = FastAPI(title="MTUSI Messenger — lab5", version="1.5.0")
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://postgres:postgres@postgres:5432/messenger")
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
@@ -37,8 +37,10 @@ SECRET_HMAC_KEY = os.environ["SECRET_HMAC_KEY"]
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "http://s3:8333")
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
S3_ACCESS_KEY = os.getenv("S3_ACCESS_KEY_ID", "minioadmin")
S3_SECRET_KEY = os.getenv("S3_SECRET_ACCESS_KEY", "minioadminpassword")
S3_ACCESS_KEY = os.getenv("S3_ACCESS_KEY_ID", "appuser")
S3_SECRET_KEY = os.getenv("S3_SECRET_ACCESS_KEY", "appsecretpassword")
STREAM_NAME = os.getenv("BROKER_STREAM", "attachment_jobs")
s3_client = boto3.client(
"s3",
@@ -50,8 +52,7 @@ s3_client = boto3.client(
)
def get_db_connection():
conn = psycopg2.connect(DATABASE_URL, cursor_factory=psycopg2.extras.RealDictCursor)
return conn
return psycopg2.connect(DATABASE_URL, cursor_factory=psycopg2.extras.RealDictCursor)
def generate_request_id() -> str:
return uuid.uuid4().hex
@@ -91,14 +92,18 @@ def decode_cursor(cursor: str, expected_chat_id: str) -> tuple:
if len(parts) != 4:
raise ValueError()
chat_id, created_at, msg_id, signature = parts
if chat_id != expected_chat_id:
raise HTTPException(status_code=400, detail="Cursor belongs to another chat")
expected_sig = hmac.new(SECRET_HMAC_KEY.encode(), f"{chat_id}|{created_at}|{msg_id}".encode(), hashlib.sha256).hexdigest()[:16]
expected_sig = hmac.new(
SECRET_HMAC_KEY.encode(),
f"{chat_id}|{created_at}|{msg_id}".encode(),
hashlib.sha256
).hexdigest()[:16]
if not hmac.compare_digest(signature, expected_sig):
raise ValueError()
return created_at, msg_id
except HTTPException:
raise
@@ -175,7 +180,7 @@ class CreateUser(BaseModel):
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)
member_ids: List[uuid.UUID] = Field(..., min_length=1, max_length=100)
@field_validator("title")
def not_blank(cls, v):
@@ -186,7 +191,7 @@ class CreateChat(BaseModel):
class CreateMessage(BaseModel):
model_config = ConfigDict(extra='forbid')
text: str = Field(default="", max_length=4000)
attachment_ids: List[uuid.UUID] = Field(default=[], max_items=10)
attachment_ids: List[uuid.UUID] = Field(default=[], max_length=10)
@model_validator(mode="after")
def check_content(self) -> 'CreateMessage':
@@ -220,7 +225,7 @@ def register_user(body: CreateUser, response: Response):
req_id = generate_request_id()
response.headers["X-Request-Id"] = req_id
response.headers["X-Instance-Id"] = INSTANCE_ID
password_hash = bcrypt.hashpw(body.password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
user_id = str(uuid.uuid4())
created_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
@@ -235,7 +240,10 @@ def register_user(body: CreateUser, response: Response):
conn.commit()
except psycopg2.errors.UniqueViolation:
conn.rollback()
raise HTTPException(status_code=409, detail={"error": {"code": "conflict", "message": "Username already taken", "request_id": req_id}})
raise HTTPException(
status_code=409,
detail={"error": {"code": "conflict", "message": "Username already taken", "request_id": req_id}}
)
finally:
conn.close()
@@ -254,18 +262,18 @@ def create_session(authorization: Optional[str] = Header(None), response: Respon
if not authorization or not authorization.startswith("Basic "):
raise HTTPException(
status_code=401,
status_code=401,
detail="Missing or invalid basic auth",
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
)
try:
encoded = authorization.split(" ")[1]
decoded = base64.b64decode(encoded).decode("utf-8")
username, password = decoded.split(":", 1)
except Exception:
raise HTTPException(
status_code=401,
status_code=401,
detail="Invalid credentials format",
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
)
@@ -274,11 +282,11 @@ def create_session(authorization: Optional[str] = Header(None), response: Respon
with conn.cursor() as cur:
cur.execute("SELECT * FROM users WHERE username = %s", (username,))
user = cur.fetchone()
conn.close()
if not user or not bcrypt.checkpw(password.encode('utf-8'), user['password_hash'].encode('utf-8')):
conn.close()
raise HTTPException(
status_code=401,
status_code=401,
detail="Invalid credentials",
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
)
@@ -293,7 +301,7 @@ def create_session(authorization: Optional[str] = Header(None), response: Respon
"token_type": "Bearer",
"expires_at": expires_at_str,
"user": {
"id": user['id'],
"id": str(user['id']),
"username": user['username'],
"display_name": user['display_name'],
"created_at": user['created_at'].isoformat().replace("+00:00", "Z") if isinstance(user['created_at'], datetime) else user['created_at']
@@ -303,7 +311,7 @@ def create_session(authorization: Optional[str] = Header(None), response: Respon
def get_current_user_from_token(authorization: Optional[str] = Header(None)) -> dict:
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(
status_code=401,
status_code=401,
detail="Missing or invalid bearer token",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
)
@@ -316,7 +324,7 @@ def get_current_user_from_token(authorization: Optional[str] = Header(None)) ->
if not user_id:
raise HTTPException(
status_code=401,
status_code=401,
detail="Invalid or expired session token",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
)
@@ -329,7 +337,7 @@ def get_current_user_from_token(authorization: Optional[str] = Header(None)) ->
if not row:
raise HTTPException(
status_code=401,
status_code=401,
detail="User not found",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
)
@@ -344,10 +352,10 @@ def get_current_user_from_token(authorization: Optional[str] = Header(None)) ->
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def revoke_session(authorization: Optional[str] = Header(None)):
req_id = generate_request_id()
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(
status_code=401,
status_code=401,
detail="Unauthorized",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
)
@@ -357,7 +365,7 @@ def revoke_session(authorization: Optional[str] = Header(None)):
if not deleted:
raise HTTPException(
status_code=401,
status_code=401,
detail="Invalid session token",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
)
@@ -365,7 +373,7 @@ def revoke_session(authorization: Optional[str] = Header(None)):
return Response(
status_code=204,
headers={
"X-Request-Id": req_id,
"X-Request-Id": req_id,
"X-Instance-Id": INSTANCE_ID
},
)
@@ -383,7 +391,7 @@ def create_chat(body: CreateChat, response: Response, authorization: Optional[st
response.headers["X-Request-Id"] = req_id
response.headers["X-Instance-Id"] = INSTANCE_ID
user = get_current_user_from_token(authorization)
member_ids_str = [str(mid) for mid in body.member_ids]
if user["id"] not in member_ids_str:
@@ -433,7 +441,7 @@ def list_chats(limit: int = 50, cursor: Optional[str] = None, response: Response
response.headers["X-Request-Id"] = req_id
response.headers["X-Instance-Id"] = INSTANCE_ID
user = get_current_user_from_token(authorization)
if limit < 1 or limit > 100:
raise HTTPException(status_code=400, detail="Invalid limit")
@@ -446,21 +454,18 @@ def list_chats(limit: int = 50, cursor: Optional[str] = None, response: Response
ORDER BY c.created_at ASC, c.id ASC
""", (user["id"],))
rows = cur.fetchall()
conn.close()
user_chats = []
for r in rows:
conn = get_db_connection()
with conn.cursor() as cur:
user_chats = []
for r in rows:
cur.execute("SELECT user_id FROM chat_members WHERE chat_id = %s", (r['id'],))
m_rows = cur.fetchall()
conn.close()
user_chats.append({
"id": r['id'],
"title": r['title'],
"member_ids": [m['user_id'] for m in m_rows],
"created_at": r['created_at'].isoformat().replace("+00:00", "Z") if isinstance(r['created_at'], datetime) else r['created_at']
})
user_chats.append({
"id": str(r['id']),
"title": r['title'],
"member_ids": [str(m['user_id']) for m in m_rows],
"created_at": r['created_at'].isoformat().replace("+00:00", "Z") if isinstance(r['created_at'], datetime) else r['created_at']
})
conn.close()
start_idx = 0
if cursor:
@@ -483,7 +488,7 @@ def list_chats(limit: int = 50, cursor: Optional[str] = None, response: Response
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}")
@@ -492,7 +497,7 @@ def get_chat(chat_id: UUID, response: Response, authorization: Optional[str] = H
response.headers["X-Request-Id"] = req_id
response.headers["X-Instance-Id"] = INSTANCE_ID
user = get_current_user_from_token(authorization)
chat_id_str = str(chat_id)
conn = get_db_connection()
with conn.cursor() as cur:
@@ -511,16 +516,16 @@ def get_chat(chat_id: UUID, response: Response, authorization: Optional[str] = H
raise HTTPException(status_code=404, detail="Chat not found")
return {
"id": chat['id'],
"id": str(chat['id']),
"title": chat['title'],
"member_ids": [m['user_id'] for m in members],
"member_ids": [str(m['user_id']) for m in members],
"created_at": chat['created_at'].isoformat().replace("+00:00", "Z") if isinstance(chat['created_at'], datetime) else chat['created_at']
}
def validate_image_and_get_dimensions(data: bytes, content_type: str):
if len(data) > 10 * 1024 * 1024:
raise HTTPException(status_code=413, detail="Payload too large (>10 MiB)")
width, height = 0, 0
if content_type == "image/png":
if not data.startswith(b'\x89PNG\r\n\x1a\n'):
@@ -544,7 +549,13 @@ def validate_image_and_get_dimensions(data: bytes, content_type: str):
if 0xc0 <= marker_type <= 0xc3:
height, width = struct.unpack('>HH', data[i+5:i+9])
break
i += 2 + struct.unpack('>H', data[i+2:i+4])[0]
if marker_type in {0xd8, 0xd9} or (0xd0 <= marker_type <= 0xd7):
i += 2
continue
seg_len = struct.unpack('>H', data[i+2:i+4])[0]
if seg_len < 2:
raise HTTPException(status_code=415, detail="Invalid JPEG segment")
i += 2 + seg_len
else:
i += 1
else:
@@ -556,7 +567,7 @@ def validate_image_and_get_dimensions(data: bytes, content_type: str):
if width * height > 40_000_000:
raise HTTPException(status_code=413, detail="Image exceeds 40 million pixels limit")
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=201)
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
async def upload_attachment(
chat_id: UUID,
filename: str = Query(..., min_length=1, max_length=255),
@@ -579,7 +590,7 @@ async def upload_attachment(
conn.close()
if any(ord(c) < 0x20 or ord(c) == 0x7f for c in filename) or '/' in filename or '\\' in filename:
raise HTTPException(400, "Invalid filename")
raise HTTPException(status_code=400, detail="Invalid filename")
content_type = request.headers.get("content-type")
if content_type not in ["image/png", "image/jpeg"]:
@@ -608,30 +619,14 @@ async def upload_attachment(
size_bytes = len(body_bytes)
sha256_hash = hashlib.sha256(body_bytes).hexdigest()
attachment_id = str(uuid.uuid4())
job_id = str(uuid.uuid4())
now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
s3_key = f"attachments/{chat_id_str}/{attachment_id}/{filename}"
conn = get_db_connection()
try:
with conn.cursor() as cur:
cur.execute("""
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, variants, error_code, created_at, updated_at)
VALUES (%s, %s, %s, %s, %s, %s, %s, 'pending', '[]', NULL, %s, %s)
""", (attachment_id, chat_id_str, user["id"], filename, content_type, size_bytes, sha256_hash, now, now))
conn.commit()
except Exception:
conn.rollback()
conn.close()
raise HTTPException(status_code=500, detail="Internal error initializing attachment")
finally:
if not conn.closed:
conn.close()
staging_key = f"staging/{chat_id_str}/{attachment_id}/original"
try:
s3_client.put_object(
Bucket=S3_BUCKET,
Key=s3_key,
Key=staging_key,
Body=body_bytes,
ContentType=content_type
)
@@ -642,16 +637,36 @@ async def upload_attachment(
try:
with conn.cursor() as cur:
cur.execute("""
UPDATE attachments SET status = 'ready', updated_at = %s WHERE id = %s
""", (now, attachment_id))
INSERT INTO attachments (
id, chat_id, owner_id, filename, content_type,
size_bytes, sha256, status, variants, error_code,
pipeline_version, attempt, created_at, updated_at
)
VALUES (%s, %s, %s, %s, %s, %s, %s, 'queued', '[]', NULL, 1, 0, %s, %s)
""", (attachment_id, chat_id_str, user["id"], filename, content_type, size_bytes, sha256_hash, now, now))
conn.commit()
except Exception:
conn.rollback()
raise HTTPException(status_code=500, detail="Internal error finalizing attachment status")
conn.close()
raise HTTPException(status_code=500, detail="Internal error saving attachment metadata")
finally:
if not conn.closed:
conn.close()
job_payload = {
"schema_version": 1,
"job_id": job_id,
"type": "attachment.process.v1",
"attachment_id": attachment_id,
"pipeline_version": 1,
"attempt": 1,
"created_at": now
}
try:
redis_client.xadd(STREAM_NAME, {"payload": json.dumps(job_payload)})
except Exception:
raise HTTPException(status_code=503, detail="Broker unavailable")
return {
"id": attachment_id,
"chat_id": chat_id_str,
@@ -660,7 +675,7 @@ async def upload_attachment(
"content_type": content_type,
"size_bytes": size_bytes,
"sha256": sha256_hash,
"status": "ready",
"status": "queued",
"variants": [],
"error_code": None,
"created_at": now,
@@ -704,7 +719,12 @@ def get_attachment(attachment_id: UUID, response: Response, authorization: Optio
}
@app.get("/api/v1/attachments/{attachment_id}/content")
def download_attachment(attachment_id: UUID, response: Response, authorization: Optional[str] = Header(None)):
def download_attachment(
attachment_id: UUID,
variant: str = Query("original", pattern="^(original|thumbnail|crop|optimized)$"),
response: Response = None,
authorization: Optional[str] = Header(None)
):
req_id = generate_request_id()
response.headers["X-Request-Id"] = req_id
response.headers["X-Instance-Id"] = INSTANCE_ID
@@ -725,9 +745,19 @@ def download_attachment(attachment_id: UUID, response: Response, authorization:
raise HTTPException(status_code=404, detail="Attachment not found or inaccessible")
if row['status'] != 'ready':
raise HTTPException(status_code=409, detail="Attachment not ready")
raise HTTPException(status_code=409, detail=f"Attachment is in status '{row['status']}'")
if variant == "original":
s3_key = f"attachments/{row['chat_id']}/{row['id']}/original"
media_type = row['content_type']
else:
variants_list = row['variants'] or []
matched = [v for v in variants_list if v.get("name") == variant]
if not matched:
raise HTTPException(status_code=404, detail=f"Variant '{variant}' not found")
s3_key = f"attachments/{row['chat_id']}/{row['id']}/{variant}"
media_type = matched[0]["content_type"]
s3_key = f"attachments/{row['chat_id']}/{row['id']}/{row['filename']}"
try:
obj = s3_client.get_object(Bucket=S3_BUCKET, Key=s3_key)
data = obj['Body'].read()
@@ -736,7 +766,7 @@ def download_attachment(attachment_id: UUID, response: Response, authorization:
return Response(
content=data,
media_type=row['content_type'],
media_type=media_type,
headers={
"X-Request-Id": req_id,
"X-Instance-Id": INSTANCE_ID,
@@ -745,9 +775,9 @@ def download_attachment(attachment_id: UUID, response: Response, authorization:
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def create_message(
chat_id: UUID,
body: CreateMessage,
response: Response,
chat_id: UUID,
body: CreateMessage,
response: Response,
authorization: Optional[str] = Header(None),
idempotency_key: Optional[str] = Header(None, alias="Idempotency-Key")
):
@@ -755,14 +785,14 @@ def create_message(
response.headers["X-Request-Id"] = req_id
response.headers["X-Instance-Id"] = INSTANCE_ID
user = get_current_user_from_token(authorization)
if not idempotency_key or not re.match(r"^[A-Za-z0-9._:-]{1,128}$", idempotency_key):
raise HTTPException(status_code=400, detail="Missing or invalid Idempotency-Key")
chat_id_str = str(chat_id)
method = "POST"
path = f"/api/v1/chats/{chat_id_str}/messages"
body_json_str = json.dumps(body.model_dump(mode='json'), sort_keys=True)
request_hash = hashlib.sha256(body_json_str.encode("utf-8")).hexdigest()
@@ -794,7 +824,7 @@ def create_message(
msg_id = str(uuid.uuid4())
created_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
msg_response = {
"id": msg_id,
"chat_id": chat_id_str,
@@ -809,7 +839,7 @@ def create_message(
VALUES (%s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (user_id, method, path, key) DO NOTHING
""", (user["id"], method, path, idempotency_key, request_hash, 201, json.dumps(msg_response)))
if cur.rowcount == 0:
cur.execute("""
SELECT request_hash, response_status, response_body
@@ -822,7 +852,7 @@ def create_message(
if row["request_hash"] != request_hash:
raise HTTPException(status_code=409, detail="Idempotency key conflict with different payload")
return row["response_body"]
cur.execute(
@@ -832,7 +862,7 @@ def create_message(
conn.commit()
except HTTPException:
raise
except Exception as exc:
except Exception:
conn.rollback()
conn.close()
raise HTTPException(status_code=500, detail="Internal error processing message")
@@ -890,16 +920,12 @@ def list_messages(chat_id: UUID, limit: int = 50, cursor: Optional[str] = None,
formatted_msgs = []
for m in page_items:
raw_atts = m.get('attachment_ids')
atts = []
if raw_atts:
for aid in raw_atts:
if aid:
atts.append(str(aid))
atts = [str(aid) for aid in raw_atts if aid] if raw_atts else []
formatted_msgs.append({
"id": m['id'],
"chat_id": m['chat_id'],
"sender_id": m['sender_id'],
"id": str(m['id']),
"chat_id": str(m['chat_id']),
"sender_id": str(m['sender_id']),
"text": m['text'],
"created_at": m['created_at'].isoformat().replace("+00:00", "Z") if isinstance(m['created_at'], datetime) else m['created_at'],
"attachment_ids": atts