forked from mtusi2026/mtusi2026lab6
grade4
This commit is contained in:
@@ -9,12 +9,14 @@ import struct
|
||||
import hashlib
|
||||
import hmac
|
||||
import logging
|
||||
import threading
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import List, Optional
|
||||
from uuid import UUID
|
||||
|
||||
import psycopg2
|
||||
import psycopg2.extras
|
||||
from psycopg2.pool import ThreadedConnectionPool
|
||||
psycopg2.extras.register_uuid()
|
||||
import bcrypt
|
||||
from fastapi import FastAPI, Header, HTTPException, Query, Response, Request
|
||||
@@ -26,8 +28,6 @@ import redis
|
||||
import boto3
|
||||
from botocore.client import Config
|
||||
|
||||
import threading
|
||||
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry._logs import set_logger_provider
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
@@ -41,6 +41,7 @@ from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.propagate import inject
|
||||
|
||||
|
||||
class JsonLogFormatter(logging.Formatter):
|
||||
@@ -134,6 +135,11 @@ api_errors_counter = meter.create_counter(
|
||||
description="Total HTTP 4xx/5xx responses served by API",
|
||||
unit="1",
|
||||
)
|
||||
api_dependency_errors_counter = meter.create_counter(
|
||||
name="http_server_dependency_errors_total",
|
||||
description="Dependency and internal errors in API (DB/Redis/S3)",
|
||||
unit="1",
|
||||
)
|
||||
api_duration_histogram = meter.create_histogram(
|
||||
name="http_server_request_duration_seconds",
|
||||
description="HTTP request duration in seconds",
|
||||
@@ -165,16 +171,66 @@ s3_client = boto3.client(
|
||||
region_name="us-east-1"
|
||||
)
|
||||
|
||||
db_pool_lock = threading.Lock()
|
||||
db_pool: Optional[ThreadedConnectionPool] = None
|
||||
_active_db_conns = 0
|
||||
|
||||
def get_db_connection():
|
||||
return psycopg2.connect(DATABASE_URL, cursor_factory=psycopg2.extras.RealDictCursor)
|
||||
|
||||
def init_db_pool(minconn: int = 1, maxconn: int = 15):
|
||||
global db_pool
|
||||
if db_pool is None:
|
||||
db_pool = ThreadedConnectionPool(
|
||||
minconn=minconn,
|
||||
maxconn=maxconn,
|
||||
dsn=DATABASE_URL,
|
||||
cursor_factory=psycopg2.extras.RealDictCursor,
|
||||
)
|
||||
|
||||
|
||||
def acquire_db_conn():
|
||||
global _active_db_conns
|
||||
if db_pool is None:
|
||||
init_db_pool()
|
||||
conn = db_pool.getconn()
|
||||
with db_pool_lock:
|
||||
_active_db_conns += 1
|
||||
return conn
|
||||
|
||||
|
||||
def release_db_conn(conn):
|
||||
global _active_db_conns
|
||||
if conn is None or db_pool is None:
|
||||
return
|
||||
try:
|
||||
close_broken = bool(getattr(conn, "closed", 0))
|
||||
db_pool.putconn(conn, close=close_broken)
|
||||
finally:
|
||||
with db_pool_lock:
|
||||
_active_db_conns = max(0, _active_db_conns - 1)
|
||||
|
||||
|
||||
def observe_db_pool(options):
|
||||
max_c = db_pool.maxconn if db_pool else 0
|
||||
with db_pool_lock:
|
||||
used = min(_active_db_conns, max_c)
|
||||
idle = max(0, max_c - used)
|
||||
yield metrics.Observation(value=used, attributes={"state": "used", "instance": INSTANCE_ID})
|
||||
yield metrics.Observation(value=idle, attributes={"state": "idle", "instance": INSTANCE_ID})
|
||||
|
||||
|
||||
meter.create_observable_gauge(
|
||||
name="db_pool_connections",
|
||||
callbacks=[observe_db_pool],
|
||||
description="PostgreSQL connection pool connections by state",
|
||||
unit="1",
|
||||
)
|
||||
|
||||
|
||||
def outbox_publisher():
|
||||
while True:
|
||||
conn = None
|
||||
try:
|
||||
conn = get_db_connection()
|
||||
conn = acquire_db_conn()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
SELECT id, stream, payload FROM outbox
|
||||
@@ -188,18 +244,37 @@ def outbox_publisher():
|
||||
cur.execute("UPDATE outbox SET published_at=NOW() WHERE id=%s", (row["id"],))
|
||||
conn.commit()
|
||||
except Exception as e:
|
||||
if conn and not conn.closed:
|
||||
try:
|
||||
conn.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
api_dependency_errors_counter.add(1, {"component": "outbox"})
|
||||
api_logger.error("Outbox publisher error: %s", type(e).__name__)
|
||||
finally:
|
||||
if conn is not None and not conn.closed:
|
||||
conn.close()
|
||||
release_db_conn(conn)
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
def _start_outbox_publisher():
|
||||
def _start_services():
|
||||
try:
|
||||
init_db_pool(minconn=1, maxconn=15)
|
||||
except Exception as e:
|
||||
api_dependency_errors_counter.add(1, {"component": "postgres"})
|
||||
api_logger.error("DB pool init error: %s", type(e).__name__)
|
||||
threading.Thread(target=outbox_publisher, daemon=True).start()
|
||||
|
||||
|
||||
@app.on_event("shutdown")
|
||||
def _shutdown_services():
|
||||
if db_pool is not None:
|
||||
try:
|
||||
db_pool.closeall()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def telemetry_middleware(request: Request, call_next):
|
||||
start = time.monotonic()
|
||||
@@ -342,6 +417,7 @@ async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_exception_handler(request: Request, exc: Exception):
|
||||
req_id = request.headers.get("X-Request-Id") or generate_request_id()
|
||||
api_dependency_errors_counter.add(1, {"component": "unhandled"})
|
||||
return make_error_response(
|
||||
status_code=500,
|
||||
code="internal_error",
|
||||
@@ -400,13 +476,19 @@ def health_ready(response: Response):
|
||||
req_id = generate_request_id()
|
||||
response.headers["X-Request-Id"] = req_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
conn = None
|
||||
try:
|
||||
conn = get_db_connection()
|
||||
conn.close()
|
||||
conn = acquire_db_conn()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT 1")
|
||||
cur.fetchone()
|
||||
redis_client.ping()
|
||||
s3_client.head_bucket(Bucket=S3_BUCKET)
|
||||
except Exception:
|
||||
api_dependency_errors_counter.add(1, {"component": "readiness"})
|
||||
raise HTTPException(status_code=503, detail="Database, Redis or S3 unavailable")
|
||||
finally:
|
||||
release_db_conn(conn)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@@ -420,7 +502,7 @@ def register_user(body: CreateUser, response: Response):
|
||||
user_id = str(uuid.uuid4())
|
||||
created_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
conn = get_db_connection()
|
||||
conn = acquire_db_conn()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
@@ -434,8 +516,12 @@ def register_user(body: CreateUser, response: Response):
|
||||
status_code=409,
|
||||
detail={"error": {"code": "conflict", "message": "Username already taken", "request_id": req_id}}
|
||||
)
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
api_dependency_errors_counter.add(1, {"component": "postgres"})
|
||||
raise HTTPException(status_code=503, detail="Database unavailable")
|
||||
finally:
|
||||
conn.close()
|
||||
release_db_conn(conn)
|
||||
|
||||
return {
|
||||
"id": user_id,
|
||||
@@ -469,11 +555,16 @@ def create_session(authorization: Optional[str] = Header(None), response: Respon
|
||||
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
|
||||
)
|
||||
|
||||
conn = get_db_connection()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT * FROM users WHERE username = %s", (username,))
|
||||
user = cur.fetchone()
|
||||
conn.close()
|
||||
conn = acquire_db_conn()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT * FROM users WHERE username = %s", (username,))
|
||||
user = cur.fetchone()
|
||||
except Exception:
|
||||
api_dependency_errors_counter.add(1, {"component": "postgres"})
|
||||
raise HTTPException(status_code=503, detail="Database unavailable")
|
||||
finally:
|
||||
release_db_conn(conn)
|
||||
|
||||
if not user or not bcrypt.checkpw(password.encode('utf-8'), user['password_hash'].encode('utf-8')):
|
||||
raise HTTPException(
|
||||
@@ -483,7 +574,12 @@ def create_session(authorization: Optional[str] = Header(None), response: Respon
|
||||
)
|
||||
|
||||
token = secrets.token_urlsafe(48)
|
||||
redis_client.setex(f"session:{token}", SESSION_TTL_SECONDS, str(user['id']))
|
||||
try:
|
||||
redis_client.setex(f"session:{token}", SESSION_TTL_SECONDS, str(user['id']))
|
||||
except Exception:
|
||||
api_dependency_errors_counter.add(1, {"component": "redis"})
|
||||
raise HTTPException(status_code=503, detail="Session store unavailable")
|
||||
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS)
|
||||
expires_at_str = expires_at.isoformat().replace("+00:00", "Z")
|
||||
|
||||
@@ -512,6 +608,7 @@ def get_current_user_from_token(authorization: Optional[str] = Header(None)) ->
|
||||
try:
|
||||
user_id = redis_client.get(f"session:{token}")
|
||||
except Exception:
|
||||
api_dependency_errors_counter.add(1, {"component": "redis"})
|
||||
raise HTTPException(status_code=503, detail="Session store unavailable")
|
||||
|
||||
if not user_id:
|
||||
@@ -521,11 +618,16 @@ def get_current_user_from_token(authorization: Optional[str] = Header(None)) ->
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||
)
|
||||
|
||||
conn = get_db_connection()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
|
||||
row = cur.fetchone()
|
||||
conn.close()
|
||||
conn = acquire_db_conn()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
|
||||
row = cur.fetchone()
|
||||
except Exception:
|
||||
api_dependency_errors_counter.add(1, {"component": "postgres"})
|
||||
raise HTTPException(status_code=503, detail="Database unavailable")
|
||||
finally:
|
||||
release_db_conn(conn)
|
||||
|
||||
if not row:
|
||||
raise HTTPException(
|
||||
@@ -554,7 +656,11 @@ def revoke_session(authorization: Optional[str] = Header(None)):
|
||||
)
|
||||
|
||||
token = authorization.split(" ")[1]
|
||||
deleted = redis_client.delete(f"session:{token}")
|
||||
try:
|
||||
deleted = redis_client.delete(f"session:{token}")
|
||||
except Exception:
|
||||
api_dependency_errors_counter.add(1, {"component": "redis"})
|
||||
raise HTTPException(status_code=503, detail="Session store unavailable")
|
||||
|
||||
if not deleted:
|
||||
raise HTTPException(
|
||||
@@ -594,19 +700,17 @@ def create_chat(body: CreateChat, response: Response, authorization: Optional[st
|
||||
if len(member_ids_str) != len(set(member_ids_str)):
|
||||
raise HTTPException(status_code=400, detail="Duplicate member IDs")
|
||||
|
||||
conn = get_db_connection()
|
||||
with conn.cursor() as cur:
|
||||
for mid_str in member_ids_str:
|
||||
cur.execute("SELECT id FROM users WHERE id = %s", (mid_str,))
|
||||
if not cur.fetchone():
|
||||
conn.close()
|
||||
raise HTTPException(status_code=400, detail=f"User {mid_str} not found")
|
||||
|
||||
chat_id = str(uuid.uuid4())
|
||||
created_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
conn = acquire_db_conn()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
for mid_str in member_ids_str:
|
||||
cur.execute("SELECT id FROM users WHERE id = %s", (mid_str,))
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(status_code=400, detail=f"User {mid_str} not found")
|
||||
|
||||
cur.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
|
||||
(chat_id, body.title, created_at)
|
||||
@@ -617,11 +721,15 @@ def create_chat(body: CreateChat, response: Response, authorization: Optional[st
|
||||
(chat_id, mid_str)
|
||||
)
|
||||
conn.commit()
|
||||
except HTTPException:
|
||||
conn.rollback()
|
||||
raise
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
conn.close()
|
||||
api_dependency_errors_counter.add(1, {"component": "postgres"})
|
||||
raise HTTPException(status_code=500, detail="Internal error creating chat")
|
||||
conn.close()
|
||||
finally:
|
||||
release_db_conn(conn)
|
||||
|
||||
return {
|
||||
"id": chat_id,
|
||||
@@ -641,27 +749,32 @@ def list_chats(limit: int = 50, cursor: Optional[str] = None, response: Response
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(status_code=400, detail="Invalid limit")
|
||||
|
||||
conn = get_db_connection()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
SELECT c.id, c.title, c.created_at FROM chats c
|
||||
JOIN chat_members cm ON c.id = cm.chat_id
|
||||
WHERE cm.user_id = %s
|
||||
ORDER BY c.created_at ASC, c.id ASC
|
||||
""", (user["id"],))
|
||||
rows = cur.fetchall()
|
||||
conn = acquire_db_conn()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
SELECT c.id, c.title, c.created_at FROM chats c
|
||||
JOIN chat_members cm ON c.id = cm.chat_id
|
||||
WHERE cm.user_id = %s
|
||||
ORDER BY c.created_at ASC, c.id ASC
|
||||
""", (user["id"],))
|
||||
rows = cur.fetchall()
|
||||
|
||||
user_chats = []
|
||||
for r in rows:
|
||||
cur.execute("SELECT user_id FROM chat_members WHERE chat_id = %s", (r['id'],))
|
||||
m_rows = cur.fetchall()
|
||||
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()
|
||||
user_chats = []
|
||||
for r in rows:
|
||||
cur.execute("SELECT user_id FROM chat_members WHERE chat_id = %s", (r['id'],))
|
||||
m_rows = cur.fetchall()
|
||||
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']
|
||||
})
|
||||
except Exception:
|
||||
api_dependency_errors_counter.add(1, {"component": "postgres"})
|
||||
raise HTTPException(status_code=503, detail="Database unavailable")
|
||||
finally:
|
||||
release_db_conn(conn)
|
||||
|
||||
start_idx = 0
|
||||
if cursor:
|
||||
@@ -696,18 +809,24 @@ def get_chat(chat_id: UUID, response: Response, authorization: Optional[str] = H
|
||||
user = get_current_user_from_token(authorization)
|
||||
|
||||
chat_id_str = str(chat_id)
|
||||
conn = get_db_connection()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
SELECT c.* FROM chats c
|
||||
JOIN chat_members cm ON c.id = cm.chat_id
|
||||
WHERE c.id = %s AND cm.user_id = %s
|
||||
""", (chat_id_str, user["id"]))
|
||||
chat = cur.fetchone()
|
||||
if chat:
|
||||
cur.execute("SELECT user_id FROM chat_members WHERE chat_id = %s", (chat_id_str,))
|
||||
members = cur.fetchall()
|
||||
conn.close()
|
||||
conn = acquire_db_conn()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
SELECT c.* FROM chats c
|
||||
JOIN chat_members cm ON c.id = cm.chat_id
|
||||
WHERE c.id = %s AND cm.user_id = %s
|
||||
""", (chat_id_str, user["id"]))
|
||||
chat = cur.fetchone()
|
||||
members = []
|
||||
if chat:
|
||||
cur.execute("SELECT user_id FROM chat_members WHERE chat_id = %s", (chat_id_str,))
|
||||
members = cur.fetchall()
|
||||
except Exception:
|
||||
api_dependency_errors_counter.add(1, {"component": "postgres"})
|
||||
raise HTTPException(status_code=503, detail="Database unavailable")
|
||||
finally:
|
||||
release_db_conn(conn)
|
||||
|
||||
if not chat:
|
||||
raise HTTPException(status_code=404, detail="Chat not found")
|
||||
@@ -780,16 +899,22 @@ async def upload_attachment(
|
||||
user = get_current_user_from_token(authorization)
|
||||
chat_id_str = str(chat_id)
|
||||
|
||||
conn = get_db_connection()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id_str, user["id"])
|
||||
)
|
||||
if not cur.fetchone():
|
||||
conn.close()
|
||||
raise HTTPException(status_code=404, detail="Chat not found or inaccessible")
|
||||
conn.close()
|
||||
conn = acquire_db_conn()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id_str, user["id"])
|
||||
)
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(status_code=404, detail="Chat not found or inaccessible")
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
api_dependency_errors_counter.add(1, {"component": "postgres"})
|
||||
raise HTTPException(status_code=503, detail="Database unavailable")
|
||||
finally:
|
||||
release_db_conn(conn)
|
||||
|
||||
if any(ord(c) < 0x20 or ord(c) == 0x7f for c in filename) or '/' in filename or '\\' in filename:
|
||||
raise HTTPException(status_code=400, detail="Invalid filename")
|
||||
@@ -833,6 +958,7 @@ async def upload_attachment(
|
||||
ContentType=content_type
|
||||
)
|
||||
except Exception:
|
||||
api_dependency_errors_counter.add(1, {"component": "s3"})
|
||||
raise HTTPException(status_code=503, detail="S3 storage unavailable")
|
||||
|
||||
job_payload = {
|
||||
@@ -845,7 +971,9 @@ async def upload_attachment(
|
||||
"created_at": now
|
||||
}
|
||||
|
||||
conn = get_db_connection()
|
||||
inject(job_payload)
|
||||
|
||||
conn = acquire_db_conn()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
@@ -866,10 +994,10 @@ async def upload_attachment(
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
api_dependency_errors_counter.add(1, {"component": "postgres"})
|
||||
raise HTTPException(status_code=500, detail="Internal error saving attachment")
|
||||
finally:
|
||||
if not conn.closed:
|
||||
conn.close()
|
||||
release_db_conn(conn)
|
||||
|
||||
return {
|
||||
"id": attachment_id,
|
||||
@@ -895,15 +1023,20 @@ def get_attachment(attachment_id: UUID, response: Response, authorization: Optio
|
||||
user = get_current_user_from_token(authorization)
|
||||
att_id_str = str(attachment_id)
|
||||
|
||||
conn = get_db_connection()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
SELECT a.* FROM attachments a
|
||||
JOIN chat_members cm ON a.chat_id = cm.chat_id
|
||||
WHERE a.id = %s AND cm.user_id = %s
|
||||
""", (att_id_str, user["id"]))
|
||||
row = cur.fetchone()
|
||||
conn.close()
|
||||
conn = acquire_db_conn()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
SELECT a.* FROM attachments a
|
||||
JOIN chat_members cm ON a.chat_id = cm.chat_id
|
||||
WHERE a.id = %s AND cm.user_id = %s
|
||||
""", (att_id_str, user["id"]))
|
||||
row = cur.fetchone()
|
||||
except Exception:
|
||||
api_dependency_errors_counter.add(1, {"component": "postgres"})
|
||||
raise HTTPException(status_code=503, detail="Database unavailable")
|
||||
finally:
|
||||
release_db_conn(conn)
|
||||
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Attachment not found or inaccessible")
|
||||
@@ -937,15 +1070,20 @@ def download_attachment(
|
||||
user = get_current_user_from_token(authorization)
|
||||
att_id_str = str(attachment_id)
|
||||
|
||||
conn = get_db_connection()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
SELECT a.* FROM attachments a
|
||||
JOIN chat_members cm ON a.chat_id = cm.chat_id
|
||||
WHERE a.id = %s AND cm.user_id = %s
|
||||
""", (att_id_str, user["id"]))
|
||||
row = cur.fetchone()
|
||||
conn.close()
|
||||
conn = acquire_db_conn()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
SELECT a.* FROM attachments a
|
||||
JOIN chat_members cm ON a.chat_id = cm.chat_id
|
||||
WHERE a.id = %s AND cm.user_id = %s
|
||||
""", (att_id_str, user["id"]))
|
||||
row = cur.fetchone()
|
||||
except Exception:
|
||||
api_dependency_errors_counter.add(1, {"component": "postgres"})
|
||||
raise HTTPException(status_code=503, detail="Database unavailable")
|
||||
finally:
|
||||
release_db_conn(conn)
|
||||
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Attachment not found or inaccessible")
|
||||
@@ -968,6 +1106,7 @@ def download_attachment(
|
||||
obj = s3_client.get_object(Bucket=S3_BUCKET, Key=s3_key)
|
||||
data = obj['Body'].read()
|
||||
except Exception:
|
||||
api_dependency_errors_counter.add(1, {"component": "s3"})
|
||||
raise HTTPException(status_code=503, detail="S3 storage unavailable or object missing")
|
||||
|
||||
return Response(
|
||||
@@ -1003,7 +1142,7 @@ def create_message(
|
||||
body_json_str = json.dumps(body.model_dump(mode='json'), sort_keys=True)
|
||||
request_hash = hashlib.sha256(body_json_str.encode("utf-8")).hexdigest()
|
||||
|
||||
conn = get_db_connection()
|
||||
conn = acquire_db_conn()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
@@ -1011,7 +1150,6 @@ def create_message(
|
||||
(chat_id_str, user["id"])
|
||||
)
|
||||
if not cur.fetchone():
|
||||
conn.close()
|
||||
raise HTTPException(status_code=404, detail="Chat not found")
|
||||
|
||||
attachment_ids_str = [str(aid) for aid in body.attachment_ids]
|
||||
@@ -1022,11 +1160,9 @@ def create_message(
|
||||
""", (attachment_ids_str, chat_id_str))
|
||||
found_atts = cur.fetchall()
|
||||
if len(found_atts) != len(attachment_ids_str):
|
||||
conn.close()
|
||||
raise HTTPException(status_code=404, detail="One or more attachments not found or in another chat")
|
||||
for att in found_atts:
|
||||
if att['status'] == 'failed':
|
||||
conn.close()
|
||||
raise HTTPException(status_code=409, detail="Cannot attach failed attachment")
|
||||
|
||||
msg_id = str(uuid.uuid4())
|
||||
@@ -1055,7 +1191,6 @@ def create_message(
|
||||
""", (user["id"], method, path, idempotency_key))
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
if row["request_hash"] != request_hash:
|
||||
raise HTTPException(status_code=409, detail="Idempotency key conflict with different payload")
|
||||
@@ -1068,14 +1203,14 @@ def create_message(
|
||||
)
|
||||
conn.commit()
|
||||
except HTTPException:
|
||||
conn.rollback()
|
||||
raise
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
conn.close()
|
||||
api_dependency_errors_counter.add(1, {"component": "postgres"})
|
||||
raise HTTPException(status_code=500, detail="Internal error processing message")
|
||||
finally:
|
||||
if not conn.closed:
|
||||
conn.close()
|
||||
release_db_conn(conn)
|
||||
|
||||
return msg_response
|
||||
|
||||
@@ -1089,31 +1224,39 @@ def list_messages(chat_id: UUID, limit: int = 50, cursor: Optional[str] = None,
|
||||
user = get_current_user_from_token(authorization)
|
||||
chat_id_str = str(chat_id)
|
||||
|
||||
conn = get_db_connection()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s",
|
||||
(chat_id_str, user["id"]))
|
||||
if not cur.fetchone():
|
||||
conn.close()
|
||||
raise HTTPException(status_code=404, detail="Chat not found")
|
||||
|
||||
if limit < 1 or limit > 100:
|
||||
conn.close()
|
||||
raise HTTPException(status_code=400, detail="Invalid limit")
|
||||
|
||||
query = "SELECT id, chat_id, sender_id, text, created_at, attachment_ids FROM messages WHERE chat_id=%s"
|
||||
params = [chat_id_str]
|
||||
if cursor:
|
||||
c_time, c_id = decode_cursor(cursor, chat_id_str)
|
||||
query += " AND (created_at, id) > (%s, %s)"
|
||||
params.extend([c_time, c_id])
|
||||
query += " ORDER BY created_at ASC, id ASC LIMIT %s"
|
||||
params.append(limit + 1)
|
||||
else:
|
||||
c_time, c_id = None, None
|
||||
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(query, tuple(params))
|
||||
rows = cur.fetchall()
|
||||
conn.close()
|
||||
if limit < 1 or limit > 100:
|
||||
raise HTTPException(status_code=400, detail="Invalid limit")
|
||||
|
||||
conn = acquire_db_conn()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s",
|
||||
(chat_id_str, user["id"]))
|
||||
if not cur.fetchone():
|
||||
raise HTTPException(status_code=404, detail="Chat not found")
|
||||
|
||||
query = "SELECT id, chat_id, sender_id, text, created_at, attachment_ids FROM messages WHERE chat_id=%s"
|
||||
params = [chat_id_str]
|
||||
if cursor:
|
||||
query += " AND (created_at, id) > (%s, %s)"
|
||||
params.extend([c_time, c_id])
|
||||
query += " ORDER BY created_at ASC, id ASC LIMIT %s"
|
||||
params.append(limit + 1)
|
||||
|
||||
cur.execute(query, tuple(params))
|
||||
rows = cur.fetchall()
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
api_dependency_errors_counter.add(1, {"component": "postgres"})
|
||||
raise HTTPException(status_code=503, detail="Database unavailable")
|
||||
finally:
|
||||
release_db_conn(conn)
|
||||
|
||||
has_next = len(rows) > limit
|
||||
page_items = rows[:limit]
|
||||
@@ -1147,7 +1290,7 @@ def replay_attachment(attachment_id: UUID, response: Response,
|
||||
user = get_current_user_from_token(authorization)
|
||||
att_id = str(attachment_id)
|
||||
|
||||
conn = get_db_connection()
|
||||
conn = acquire_db_conn()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
@@ -1157,10 +1300,8 @@ def replay_attachment(attachment_id: UUID, response: Response,
|
||||
""", (att_id, user["id"]))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
conn.close()
|
||||
raise HTTPException(status_code=404, detail="Attachment not found")
|
||||
if row["status"] != "failed":
|
||||
conn.close()
|
||||
raise HTTPException(status_code=409, detail="Only failed attachments can be replayed")
|
||||
|
||||
now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
@@ -1172,12 +1313,19 @@ def replay_attachment(attachment_id: UUID, response: Response,
|
||||
job = {"schema_version": 1, "job_id": str(uuid.uuid4()),
|
||||
"type": "attachment.process.v1", "attachment_id": att_id,
|
||||
"pipeline_version": 1, "attempt": 1, "created_at": now}
|
||||
inject(job)
|
||||
cur.execute("INSERT INTO outbox (id, stream, payload, created_at) "
|
||||
"VALUES (%s, %s, %s::jsonb, %s)",
|
||||
(str(uuid.uuid4()), STREAM_NAME, json.dumps(job), now))
|
||||
conn.commit()
|
||||
except HTTPException:
|
||||
conn.rollback()
|
||||
raise
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
api_dependency_errors_counter.add(1, {"component": "postgres"})
|
||||
raise HTTPException(status_code=503, detail="Database unavailable")
|
||||
finally:
|
||||
if not conn.closed:
|
||||
conn.close()
|
||||
release_db_conn(conn)
|
||||
|
||||
return {"id": att_id, "status": "queued"}
|
||||
Reference in New Issue
Block a user