This commit is contained in:
Getlles
2026-11-16 20:34:32 +03:00
parent d475bf29ed
commit 749109aaf4
8 changed files with 363 additions and 178 deletions
+115 -44
View File
@@ -1,4 +1,5 @@
import os
import time
import base64
import secrets
import uuid
@@ -24,8 +25,38 @@ import redis
import boto3
from botocore.client import Config
import threading
app = FastAPI(title="MTUSI Messenger — lab5", version="1.5.0")
def outbox_publisher():
while True:
conn = None
try:
conn = get_db_connection()
with conn.cursor() as cur:
cur.execute("""
SELECT id, stream, payload FROM outbox
WHERE published_at IS NULL
ORDER BY created_at
LIMIT 100
FOR UPDATE SKIP LOCKED
""")
for row in cur.fetchall():
redis_client.xadd(row["stream"], {"payload": json.dumps(row["payload"])})
cur.execute("UPDATE outbox SET published_at=NOW() WHERE id=%s", (row["id"],))
conn.commit()
except Exception as e:
print(f"OUTBOX PUBLISHER ERROR: {type(e).__name__} - {e}", flush=True)
finally:
if conn is not None and not conn.closed:
conn.close()
time.sleep(1)
@app.on_event("startup")
def _start_outbox_publisher():
threading.Thread(target=outbox_publisher, daemon=True).start()
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://postgres:postgres@postgres:5432/messenger")
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
INSTANCE_ID = os.getenv("INSTANCE_ID", "instance-1")
@@ -583,7 +614,10 @@ async def upload_attachment(
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"]))
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")
@@ -633,6 +667,16 @@ async def upload_attachment(
except Exception:
raise HTTPException(status_code=503, detail="S3 storage unavailable")
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
}
conn = get_db_connection()
try:
with conn.cursor() as cur:
@@ -643,30 +687,22 @@ async def upload_attachment(
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))
""", (attachment_id, chat_id_str, user["id"], filename,
content_type, size_bytes, sha256_hash, now, now))
cur.execute(
"INSERT INTO outbox (id, stream, payload, created_at) "
"VALUES (%s, %s, %s::jsonb, %s)",
(str(uuid.uuid4()), STREAM_NAME, json.dumps(job_payload), now)
)
conn.commit()
except Exception:
conn.rollback()
conn.close()
raise HTTPException(status_code=500, detail="Internal error saving attachment metadata")
raise HTTPException(status_code=500, detail="Internal error saving attachment")
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,
@@ -873,20 +909,18 @@ def create_message(
return msg_response
@app.get("/api/v1/chats/{chat_id}/messages")
def list_messages(chat_id: UUID, limit: int = 50, cursor: Optional[str] = None, response: Response = None, authorization: Optional[str] = Header(None)):
def list_messages(chat_id: UUID, limit: int = 50, cursor: Optional[str] = None,
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
user = get_current_user_from_token(authorization)
chat_id_str = str(chat_id)
conn = get_db_connection()
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"])
)
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")
@@ -895,17 +929,12 @@ def list_messages(chat_id: UUID, limit: int = 50, cursor: Optional[str] = None,
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
"""
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)
@@ -917,23 +946,65 @@ def list_messages(chat_id: UUID, limit: int = 50, cursor: Optional[str] = None,
has_next = len(rows) > limit
page_items = rows[:limit]
formatted_msgs = []
formatted = []
for m in page_items:
raw_atts = m.get('attachment_ids')
atts = [str(aid) for aid in raw_atts if aid] if raw_atts else []
formatted_msgs.append({
"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'],
raw = m.get('attachment_ids')
atts = [str(a) for a in raw if a] if raw else []
formatted.append({
"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
})
next_cursor = None
if has_next and formatted_msgs:
last = formatted_msgs[-1]
if has_next and formatted:
last = formatted[-1]
next_cursor = encode_cursor(chat_id_str, last['created_at'], last['id'])
return {"items": formatted_msgs, "next_cursor": next_cursor}
return {"items": formatted, "next_cursor": next_cursor}
@app.post("/api/v1/attachments/{attachment_id}/replay", status_code=202)
def replay_attachment(attachment_id: UUID, response: Response,
authorization: Optional[str] = Header(None)):
req_id = generate_request_id()
response.headers["X-Request-Id"] = req_id
response.headers["X-Instance-Id"] = INSTANCE_ID
user = get_current_user_from_token(authorization)
att_id = str(attachment_id)
conn = get_db_connection()
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, 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")
cur.execute("""
UPDATE attachments SET status='queued', attempt=0, error_code=NULL, updated_at=%s
WHERE id=%s
""", (now, att_id))
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}
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()
finally:
if not conn.closed:
conn.close()
return {"id": att_id, "status": "queued"}