forked from mtusi2026/mtusi2026lab4
собранная версия, без проверки тестов
This commit is contained in:
+1
-3
@@ -1,7 +1,5 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt .
|
||||
@@ -14,4 +12,4 @@ ENV PORT=8080
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8080"]
|
||||
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8080"]
|
||||
|
||||
+32
-3
@@ -8,27 +8,48 @@ services:
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger"]
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
networks: [backend]
|
||||
|
||||
minio:
|
||||
image: dappros/minio:RELEASE.2025-09-07T16-13-09Z
|
||||
command: ["server", "/data"]
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:-lab4access}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:-lab4secret-change-me}
|
||||
volumes:
|
||||
- minio_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -fsS http://localhost:9000/minio/health/live >/dev/null"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
networks: [backend]
|
||||
|
||||
api-1:
|
||||
build: .
|
||||
environment:
|
||||
DATABASE_URL: postgresql://messenger:${POSTGRES_PASSWORD:-messenger_pass}@postgres:5432/messenger
|
||||
INSTANCE_ID: api-1
|
||||
SESSION_TTL_SECONDS: "3600"
|
||||
S3_ENDPOINT_URL: http://minio:9000
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_ACCESS_KEY: ${S3_ACCESS_KEY:-lab4access}
|
||||
S3_SECRET_KEY: ${S3_SECRET_KEY:-lab4secret-change-me}
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
minio:
|
||||
condition: service_healthy
|
||||
stop_grace_period: 15s
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "0.5", memory: 256M }
|
||||
networks: [backend]
|
||||
# порты наружу НЕ публикуем
|
||||
|
||||
api-2:
|
||||
build: .
|
||||
@@ -36,9 +57,16 @@ services:
|
||||
DATABASE_URL: postgresql://messenger:${POSTGRES_PASSWORD:-messenger_pass}@postgres:5432/messenger
|
||||
INSTANCE_ID: api-2
|
||||
SESSION_TTL_SECONDS: "3600"
|
||||
S3_ENDPOINT_URL: http://minio:9000
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_ACCESS_KEY: ${S3_ACCESS_KEY:-lab4access}
|
||||
S3_SECRET_KEY: ${S3_SECRET_KEY:-lab4secret-change-me}
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
minio:
|
||||
condition: service_healthy
|
||||
stop_grace_period: 15s
|
||||
deploy:
|
||||
resources:
|
||||
@@ -58,6 +86,7 @@ services:
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
minio_data:
|
||||
|
||||
networks:
|
||||
backend:
|
||||
backend:
|
||||
|
||||
+4
-1
@@ -12,6 +12,8 @@ http {
|
||||
listen 8080;
|
||||
server_name _;
|
||||
|
||||
client_max_body_size 10m;
|
||||
|
||||
location / {
|
||||
proxy_pass http://api_backend;
|
||||
proxy_http_version 1.1;
|
||||
@@ -22,8 +24,9 @@ http {
|
||||
proxy_connect_timeout 2s;
|
||||
proxy_send_timeout 30s;
|
||||
proxy_read_timeout 30s;
|
||||
proxy_request_buffering off;
|
||||
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||
proxy_next_upstream_tries 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
-1
@@ -3,4 +3,6 @@ uvicorn==0.24.0
|
||||
psycopg2-binary==2.9.9
|
||||
bcrypt==4.1.2
|
||||
python-multipart==0.0.6
|
||||
pydantic==2.5.0
|
||||
pydantic==2.5.0
|
||||
boto3==1.43.18
|
||||
Pillow==12.3.0
|
||||
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
@echo off
|
||||
cd /d %~dp0\..
|
||||
echo Restarting API and Database...
|
||||
docker compose restart api-1 api-2 postgres
|
||||
exit /b 0
|
||||
echo Restarting API, Database and MinIO...
|
||||
docker compose restart api-1 api-2 postgres minio
|
||||
exit /b %errorlevel%
|
||||
|
||||
+114
-129
@@ -34,59 +34,51 @@ def get_db():
|
||||
|
||||
|
||||
def init_db():
|
||||
"""Прогнать все миграции по порядку (idempotent)."""
|
||||
files = sorted(glob.glob(os.path.join(MIGRATIONS_DIR, "*.sql")))
|
||||
if not files:
|
||||
raise RuntimeError(f"No migrations found in {MIGRATIONS_DIR}")
|
||||
with get_db() as conn:
|
||||
with conn.cursor() as cur:
|
||||
for path in files:
|
||||
with open(path, "r") as f:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
cur.execute(f.read())
|
||||
print(f"[init_db] applied {len(files)} migration(s): "
|
||||
f"{[os.path.basename(p) for p in files]}")
|
||||
|
||||
|
||||
class PostgresStore:
|
||||
def _iso(dt):
|
||||
return dt.strftime('%Y-%m-%dT%H:%M:%SZ') if hasattr(dt, 'strftime') else dt
|
||||
|
||||
# ---------- users ----------
|
||||
|
||||
class PostgresStore:
|
||||
def create_user(self, username: str, display_name: str, password_hash: str) -> dict:
|
||||
with get_db() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT id FROM users WHERE username = %s", (username,))
|
||||
if cur.fetchone():
|
||||
raise ValueError("username_already_exists")
|
||||
user_id = str(uuid4())
|
||||
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
cur.execute(
|
||||
"INSERT INTO users (id, username, display_name, password_hash, created_at) "
|
||||
"VALUES (%s, %s, %s, %s, %s)",
|
||||
(user_id, username, display_name, password_hash, now)
|
||||
)
|
||||
return {"id": user_id, "username": username,
|
||||
"display_name": display_name, "created_at": now}
|
||||
with get_db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT id FROM users WHERE username = %s", (username,))
|
||||
if cur.fetchone():
|
||||
raise ValueError("username_already_exists")
|
||||
user_id = str(uuid4())
|
||||
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
cur.execute(
|
||||
"INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES (%s, %s, %s, %s, %s)",
|
||||
(user_id, username, display_name, password_hash, now))
|
||||
return {"id": user_id, "username": username, "display_name": display_name, "created_at": now}
|
||||
|
||||
def get_user(self, user_id: str) -> Optional[dict]:
|
||||
with get_db() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
||||
(user_id,))
|
||||
cur.execute("SELECT id, username, display_name, created_at FROM users WHERE id = %s", (user_id,))
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
row["created_at"] = row["created_at"].strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
row["created_at"] = _iso(row["created_at"])
|
||||
return row
|
||||
|
||||
def get_user_by_username(self, username: str) -> Optional[dict]:
|
||||
with get_db() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, password_hash, created_at "
|
||||
"FROM users WHERE username = %s", (username,))
|
||||
cur.execute("SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = %s", (username,))
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
row["created_at"] = row["created_at"].strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
row["created_at"] = _iso(row["created_at"])
|
||||
return row
|
||||
|
||||
# ---------- chats ----------
|
||||
def create_chat(self, title: str, member_ids: List[str], creator_id: str) -> dict:
|
||||
with get_db() as conn, conn.cursor() as cur:
|
||||
for member_id in member_ids:
|
||||
@@ -99,40 +91,23 @@ class PostgresStore:
|
||||
raise ValueError("duplicate_members")
|
||||
chat_id = str(uuid4())
|
||||
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
cur.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
|
||||
(chat_id, title, now))
|
||||
cur.execute("INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)", (chat_id, title, now))
|
||||
for member_id in member_ids:
|
||||
cur.execute(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
|
||||
(chat_id, member_id))
|
||||
return {"id": chat_id, "title": title,
|
||||
"member_ids": member_ids, "created_at": now}
|
||||
cur.execute("INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)", (chat_id, member_id))
|
||||
return {"id": chat_id, "title": title, "member_ids": member_ids, "created_at": now}
|
||||
|
||||
def get_chat(self, chat_id: str, user_id: str) -> Optional[dict]:
|
||||
with get_db() as conn, 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 c.id = %s AND cm.user_id = %s",
|
||||
(chat_id, user_id))
|
||||
cur.execute("SELECT c.id, c.title, c.created_at FROM chats c JOIN chat_members cm ON c.id = cm.chat_id WHERE c.id = %s AND cm.user_id = %s", (chat_id, user_id))
|
||||
chat = cur.fetchone()
|
||||
if not chat:
|
||||
return None
|
||||
cur.execute(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
|
||||
(chat_id,))
|
||||
members = [row["user_id"] for row in cur.fetchall()]
|
||||
return {"id": chat["id"], "title": chat["title"],
|
||||
"member_ids": members,
|
||||
"created_at": chat["created_at"].strftime('%Y-%m-%dT%H:%M:%SZ')}
|
||||
cur.execute("SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id", (chat_id,))
|
||||
return {"id": chat["id"], "title": chat["title"], "member_ids": [m["user_id"] for m in cur.fetchall()], "created_at": _iso(chat["created_at"])}
|
||||
|
||||
def list_chats(self, user_id: str, limit: int = 50,
|
||||
cursor: Optional[str] = None) -> Tuple[List[dict], Optional[str]]:
|
||||
def list_chats(self, user_id: str, limit: int = 50, cursor: Optional[str] = None) -> Tuple[List[dict], Optional[str]]:
|
||||
with get_db() as conn, conn.cursor() as cur:
|
||||
query = ("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")
|
||||
query = "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"
|
||||
params: List[Any] = [user_id]
|
||||
if cursor:
|
||||
parts = cursor.split(",", 1)
|
||||
@@ -147,34 +122,27 @@ class PostgresStore:
|
||||
page = rows[:limit]
|
||||
chats = []
|
||||
for row in page:
|
||||
cur.execute(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
|
||||
(row["id"],))
|
||||
chats.append({
|
||||
"id": row["id"], "title": row["title"],
|
||||
"member_ids": [m["user_id"] for m in cur.fetchall()],
|
||||
"created_at": row["created_at"].strftime('%Y-%m-%dT%H:%M:%SZ')})
|
||||
cur.execute("SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id", (row["id"],))
|
||||
chats.append({"id": row["id"], "title": row["title"], "member_ids": [m["user_id"] for m in cur.fetchall()], "created_at": _iso(row["created_at"])})
|
||||
next_cursor = None
|
||||
if has_more and page:
|
||||
last = page[-1]
|
||||
next_cursor = (f"{last['created_at'].strftime('%Y-%m-%dT%H:%M:%SZ')},"
|
||||
f"{last['id']}")
|
||||
next_cursor = f"{_iso(last['created_at'])},{last['id']}"
|
||||
return chats, next_cursor
|
||||
|
||||
# ---------- messages ----------
|
||||
def list_messages(self, chat_id: str, user_id: str, limit: int = 50,
|
||||
cursor: Optional[str] = None) -> Tuple[List[dict], Optional[str]]:
|
||||
def _message_attachments(self, cur, message_id: str) -> List[str]:
|
||||
cur.execute("SELECT attachment_id FROM message_attachments WHERE message_id = %s ORDER BY attachment_id", (message_id,))
|
||||
return [str(r["attachment_id"]) for r in cur.fetchall()]
|
||||
|
||||
def list_messages(self, chat_id: str, user_id: str, limit: int = 50, cursor: Optional[str] = None) -> Tuple[List[dict], Optional[str]]:
|
||||
with get_db() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, user_id))
|
||||
cur.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, user_id))
|
||||
if not cur.fetchone():
|
||||
cur.execute("SELECT id FROM chats WHERE id = %s", (chat_id,))
|
||||
if cur.fetchone():
|
||||
raise ValueError("user_not_in_chat")
|
||||
raise ValueError("chat_not_found")
|
||||
query = ("SELECT id, chat_id, sender_id, text, created_at "
|
||||
"FROM messages WHERE chat_id = %s")
|
||||
query = "SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = %s"
|
||||
params: List[Any] = [chat_id]
|
||||
if cursor:
|
||||
parts = cursor.split(",", 1)
|
||||
@@ -187,95 +155,112 @@ class PostgresStore:
|
||||
rows = cur.fetchall()
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
messages = [{
|
||||
"id": r["id"], "chat_id": r["chat_id"], "sender_id": r["sender_id"],
|
||||
"text": r["text"],
|
||||
"created_at": r["created_at"].strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
} for r in page]
|
||||
messages = []
|
||||
for r in page:
|
||||
messages.append({
|
||||
"id": r["id"], "chat_id": r["chat_id"], "sender_id": r["sender_id"],
|
||||
"text": r["text"], "created_at": _iso(r["created_at"]),
|
||||
"attachment_ids": self._message_attachments(cur, str(r["id"]))
|
||||
})
|
||||
next_cursor = None
|
||||
if has_more and page:
|
||||
last = page[-1]
|
||||
next_cursor = (f"{last['created_at'].strftime('%Y-%m-%dT%H:%M:%SZ')},"
|
||||
f"{last['id']}")
|
||||
next_cursor = f"{_iso(last['created_at'])},{last['id']}"
|
||||
return messages, next_cursor
|
||||
|
||||
# ---------- messages + idempotency (lab3) ----------
|
||||
def get_idempotent_result(self, user_id: str, method: str, path: str,
|
||||
key: str) -> Optional[dict]:
|
||||
with get_db() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT request_hash, status_code, response_body "
|
||||
"FROM idempotency_keys "
|
||||
"WHERE user_id=%s AND method=%s AND path=%s AND key=%s",
|
||||
(user_id, method, path, key))
|
||||
return cur.fetchone()
|
||||
def _validate_attachments_for_chat(self, cur, chat_id: str, attachment_ids: List[str]) -> None:
|
||||
if len(attachment_ids) > 10 or len(set(attachment_ids)) != len(attachment_ids):
|
||||
raise ValueError("invalid_attachment_ids")
|
||||
if not attachment_ids:
|
||||
return
|
||||
cur.execute("SELECT id, status, chat_id FROM attachments WHERE id = ANY(%s::uuid[])", (attachment_ids,))
|
||||
rows = {str(r["id"]): r for r in cur.fetchall()}
|
||||
for aid in attachment_ids:
|
||||
row = rows.get(aid)
|
||||
if not row or str(row["chat_id"]) != chat_id:
|
||||
raise ValueError("attachment_not_found")
|
||||
if row["status"] != "ready":
|
||||
raise ValueError("attachment_not_ready")
|
||||
|
||||
def create_message_idempotent(self, chat_id: str, sender_id: str, text: str,
|
||||
idem_key: str, path: str, request_hash: str) -> dict:
|
||||
"""
|
||||
Атомарно: проверка членства + вставка сообщения + запись ключа идемпотентности.
|
||||
На гонку уникальности ключа возвращает сохранённый ранее ответ.
|
||||
На конфликт хэша (другой payload с тем же ключом) — ValueError('idempotency_conflict').
|
||||
"""
|
||||
def create_message_idempotent(self, chat_id: str, sender_id: str, text: str, attachment_ids: List[str], idem_key: str, path: str, request_hash: str) -> dict:
|
||||
with get_db() as conn, conn.cursor() as cur:
|
||||
# 1. Проверить, не записан ли уже ключ
|
||||
cur.execute(
|
||||
"SELECT request_hash, status_code, response_body "
|
||||
"FROM idempotency_keys "
|
||||
"WHERE user_id=%s AND method='POST' AND path=%s AND key=%s",
|
||||
(sender_id, path, idem_key))
|
||||
cur.execute("SELECT request_hash, status_code, response_body FROM idempotency_keys WHERE user_id=%s AND method='POST' AND path=%s AND key=%s", (sender_id, path, idem_key))
|
||||
existing = cur.fetchone()
|
||||
if existing:
|
||||
if existing["request_hash"] != request_hash:
|
||||
raise ValueError("idempotency_conflict")
|
||||
return existing["response_body"]
|
||||
result = dict(existing["response_body"])
|
||||
result.setdefault("attachment_ids", [])
|
||||
return result
|
||||
|
||||
# 2. Проверить членство в чате
|
||||
cur.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, sender_id))
|
||||
cur.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, sender_id))
|
||||
if not cur.fetchone():
|
||||
cur.execute("SELECT id FROM chats WHERE id = %s", (chat_id,))
|
||||
if cur.fetchone():
|
||||
raise ValueError("sender_not_in_chat")
|
||||
raise ValueError("chat_not_found")
|
||||
if not text and not attachment_ids:
|
||||
raise ValueError("message_empty")
|
||||
self._validate_attachments_for_chat(cur, chat_id, attachment_ids)
|
||||
|
||||
# 3. Вставить сообщение
|
||||
message_id = str(uuid4())
|
||||
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
cur.execute(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) "
|
||||
"VALUES (%s, %s, %s, %s, %s)",
|
||||
(message_id, chat_id, sender_id, text, now))
|
||||
message = {
|
||||
"id": message_id, "chat_id": chat_id, "sender_id": sender_id,
|
||||
"text": text, "created_at": now
|
||||
}
|
||||
cur.execute("INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES (%s, %s, %s, %s, %s)", (message_id, chat_id, sender_id, text, now))
|
||||
for aid in attachment_ids:
|
||||
cur.execute("INSERT INTO message_attachments (message_id, attachment_id) VALUES (%s, %s)", (message_id, aid))
|
||||
message = {"id": message_id, "chat_id": chat_id, "sender_id": sender_id, "text": text, "created_at": now, "attachment_ids": attachment_ids}
|
||||
|
||||
# 4. Записать ключ идемпотентности (гонку закроет PK)
|
||||
try:
|
||||
cur.execute(
|
||||
"INSERT INTO idempotency_keys "
|
||||
"(user_id, method, path, key, request_hash, status_code, response_body) "
|
||||
"VALUES (%s, 'POST', %s, %s, %s, 201, %s)",
|
||||
(sender_id, path, idem_key, request_hash,
|
||||
json.dumps(message)))
|
||||
cur.execute("INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, status_code, response_body) VALUES (%s, 'POST', %s, %s, %s, 201, %s)", (sender_id, path, idem_key, request_hash, json.dumps(message)))
|
||||
except psycopg2.errors.UniqueViolation:
|
||||
# Параллельный запрос успел первым — откатываем свою вставку сообщения
|
||||
conn.rollback()
|
||||
cur.execute(
|
||||
"SELECT request_hash, status_code, response_body "
|
||||
"FROM idempotency_keys "
|
||||
"WHERE user_id=%s AND method='POST' AND path=%s AND key=%s",
|
||||
(sender_id, path, idem_key))
|
||||
cur.execute("SELECT request_hash, status_code, response_body FROM idempotency_keys WHERE user_id=%s AND method='POST' AND path=%s AND key=%s", (sender_id, path, idem_key))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise
|
||||
if row["request_hash"] != request_hash:
|
||||
raise ValueError("idempotency_conflict")
|
||||
return row["response_body"]
|
||||
|
||||
result = dict(row["response_body"])
|
||||
result.setdefault("attachment_ids", [])
|
||||
return result
|
||||
return message
|
||||
|
||||
def create_attachment(self, attachment: dict) -> dict:
|
||||
with get_db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s", (attachment["chat_id"], attachment["owner_id"]))
|
||||
if not cur.fetchone():
|
||||
cur.execute("SELECT id FROM chats WHERE id=%s", (attachment["chat_id"],))
|
||||
if cur.fetchone():
|
||||
raise ValueError("owner_not_in_chat")
|
||||
raise ValueError("chat_not_found")
|
||||
cur.execute(
|
||||
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, object_key, error_code, created_at, updated_at) VALUES (%s,%s,%s,%s,%s,%s,%s,'ready',%s,NULL,%s,%s)",
|
||||
(attachment["id"], attachment["chat_id"], attachment["owner_id"], attachment["filename"], attachment["content_type"], attachment["size_bytes"], attachment["sha256"], attachment["object_key"], attachment["created_at"], attachment["updated_at"]))
|
||||
return attachment
|
||||
|
||||
store = PostgresStore()
|
||||
def get_attachment(self, attachment_id: str, user_id: str) -> Optional[dict]:
|
||||
with get_db() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT a.id,a.chat_id,a.owner_id,a.filename,a.content_type,a.size_bytes,a.sha256,a.status,a.error_code,a.created_at,a.updated_at FROM attachments a JOIN chat_members cm ON cm.chat_id=a.chat_id AND cm.user_id=%s WHERE a.id=%s",
|
||||
(user_id, attachment_id))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return self._attachment_response(cur, row)
|
||||
|
||||
def _attachment_response(self, cur, row: dict) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]), "chat_id": str(row["chat_id"]), "owner_id": str(row["owner_id"]),
|
||||
"filename": row["filename"], "content_type": row["content_type"], "size_bytes": row["size_bytes"],
|
||||
"sha256": row["sha256"], "status": row["status"], "variants": [], "error_code": row["error_code"],
|
||||
"created_at": _iso(row["created_at"]), "updated_at": _iso(row["updated_at"])
|
||||
}
|
||||
|
||||
def get_attachment_object_key(self, attachment_id: str, user_id: str) -> Optional[str]:
|
||||
with get_db() as conn, conn.cursor() as cur:
|
||||
cur.execute("SELECT a.object_key FROM attachments a JOIN chat_members cm ON cm.chat_id=a.chat_id AND cm.user_id=%s WHERE a.id=%s", (user_id, attachment_id))
|
||||
row = cur.fetchone()
|
||||
return row["object_key"] if row else None
|
||||
|
||||
|
||||
store = PostgresStore()
|
||||
|
||||
+182
-77
@@ -3,24 +3,31 @@ import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from uuid import uuid4
|
||||
import io
|
||||
import warnings
|
||||
from datetime import datetime, timezone
|
||||
from uuid import UUID, uuid4
|
||||
from urllib.parse import unquote
|
||||
|
||||
from fastapi import FastAPI, Request, HTTPException, Query
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from fastapi.responses import JSONResponse, Response, StreamingResponse
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from typing import Optional
|
||||
from PIL import Image, UnidentifiedImageError, ImageFile, ImageFilter
|
||||
|
||||
from .models import (
|
||||
CreateUserRequest, CreateChatRequest, CreateMessageRequest,
|
||||
UserResponse, ChatResponse, MessageResponse, ChatPage, MessagePage,
|
||||
SessionResponse, HealthResponse
|
||||
SessionResponse, HealthResponse, AttachmentResponse
|
||||
)
|
||||
from .database import store, init_db, get_db_connection
|
||||
from .auth import hash_password, verify_password, create_session, get_session, delete_session
|
||||
from . import s3
|
||||
|
||||
# Идентификатор реплики — стабилен в пределах жизни процесса.
|
||||
# Задаётся через env INSTANCE_ID, иначе генерируется.
|
||||
INSTANCE_ID = os.getenv("INSTANCE_ID") or str(uuid4())
|
||||
MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
ALLOWED_CONTENT_TYPES = {"image/png": "PNG", "image/jpeg": "JPEG"}
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
@@ -28,6 +35,7 @@ app = FastAPI()
|
||||
@app.on_event("startup")
|
||||
async def startup_event():
|
||||
init_db()
|
||||
s3.ensure_bucket()
|
||||
print(f"[startup] INSTANCE_ID={INSTANCE_ID}")
|
||||
|
||||
|
||||
@@ -44,13 +52,11 @@ async def add_headers(request: Request, call_next):
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
request_id = getattr(request.state, "request_id", str(uuid4()))
|
||||
return JSONResponse(status_code=400, content={
|
||||
"error": {
|
||||
"code": "invalid_request",
|
||||
"message": "Неверный формат запроса, неверные типы данных или лишние поля",
|
||||
"request_id": request_id,
|
||||
}
|
||||
})
|
||||
return JSONResponse(status_code=400, content={"error": {
|
||||
"code": "invalid_request",
|
||||
"message": "Неверный формат запроса, неверные типы данных или лишние поля",
|
||||
"request_id": request_id,
|
||||
}})
|
||||
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
@@ -66,16 +72,11 @@ async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
content = exc.detail
|
||||
content["error"]["request_id"] = request_id
|
||||
else:
|
||||
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",
|
||||
}
|
||||
content = {"error": {
|
||||
"code": code_map.get(exc.status_code, "invalid_request"),
|
||||
"message": str(exc.detail),
|
||||
"request_id": request_id,
|
||||
}}
|
||||
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"}
|
||||
content = {"error": {"code": code_map.get(exc.status_code, "invalid_request"),
|
||||
"message": str(exc.detail), "request_id": request_id}}
|
||||
return JSONResponse(status_code=exc.status_code, content=content, headers=headers)
|
||||
|
||||
|
||||
@@ -100,7 +101,6 @@ async def get_current_user_from_request(request: Request) -> dict:
|
||||
conn.close()
|
||||
|
||||
|
||||
# ---------- health ----------
|
||||
@app.get("/health/live", response_model=HealthResponse)
|
||||
async def health_live():
|
||||
return {"status": "ok"}
|
||||
@@ -111,12 +111,13 @@ async def health_ready():
|
||||
try:
|
||||
conn = get_db_connection()
|
||||
conn.close()
|
||||
if not s3.check_available():
|
||||
raise RuntimeError("S3 unavailable")
|
||||
return {"status": "ok"}
|
||||
except Exception:
|
||||
raise HTTPException(503, detail="Database unavailable")
|
||||
raise HTTPException(503, detail="Required storage unavailable")
|
||||
|
||||
|
||||
# ---------- auth ----------
|
||||
@app.post("/api/v1/auth/sessions", response_model=SessionResponse, status_code=201)
|
||||
async def create_session_endpoint(request: Request):
|
||||
auth_header = request.headers.get("Authorization")
|
||||
@@ -138,14 +139,8 @@ async def create_session_endpoint(request: Request):
|
||||
conn = get_db_connection()
|
||||
try:
|
||||
session_data = create_session(conn, user["id"])
|
||||
return {
|
||||
"token": session_data["token"],
|
||||
"token_type": "Bearer",
|
||||
"expires_at": session_data["expires_at"],
|
||||
"user": {"id": user["id"], "username": user["username"],
|
||||
"display_name": user["display_name"],
|
||||
"created_at": user["created_at"]},
|
||||
}
|
||||
return {"token": session_data["token"], "token_type": "Bearer", "expires_at": session_data["expires_at"],
|
||||
"user": {"id": user["id"], "username": user["username"], "display_name": user["display_name"], "created_at": user["created_at"]}}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@@ -162,13 +157,10 @@ async def revoke_session(request: Request):
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
# ---------- users ----------
|
||||
@app.post("/api/v1/users", response_model=UserResponse, status_code=201)
|
||||
async def create_user(body: CreateUserRequest):
|
||||
try:
|
||||
user = store.create_user(body.username, body.display_name,
|
||||
hash_password(body.password))
|
||||
return user
|
||||
return store.create_user(body.username, body.display_name, hash_password(body.password))
|
||||
except ValueError as e:
|
||||
if str(e) == "username_already_exists":
|
||||
raise HTTPException(409, detail="Username already exists")
|
||||
@@ -180,25 +172,18 @@ async def get_current_user(request: Request):
|
||||
return await get_current_user_from_request(request)
|
||||
|
||||
|
||||
# ---------- chats ----------
|
||||
@app.post("/api/v1/chats", response_model=ChatResponse, status_code=201)
|
||||
async def create_chat(body: CreateChatRequest, request: Request):
|
||||
user = await get_current_user_from_request(request)
|
||||
try:
|
||||
return store.create_chat(body.title, body.member_ids, user["id"])
|
||||
except ValueError as e:
|
||||
mapping = {
|
||||
"user_not_found": "One or more members not found",
|
||||
"creator_not_in_members": "Creator must be in member list",
|
||||
"duplicate_members": "Duplicate member IDs",
|
||||
}
|
||||
mapping = {"user_not_found": "One or more members not found", "creator_not_in_members": "Creator must be in member list", "duplicate_members": "Duplicate member IDs"}
|
||||
raise HTTPException(400, detail=mapping.get(str(e), str(e)))
|
||||
|
||||
|
||||
@app.get("/api/v1/chats", response_model=ChatPage)
|
||||
async def list_chats(request: Request,
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: Optional[str] = Query(default=None, min_length=1)):
|
||||
async def list_chats(request: Request, limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None, min_length=1)):
|
||||
user = await get_current_user_from_request(request)
|
||||
chats, next_cursor = store.list_chats(user["id"], limit, cursor)
|
||||
return {"items": chats, "next_cursor": next_cursor}
|
||||
@@ -213,42 +198,31 @@ async def get_chat(chat_id: str, request: Request):
|
||||
return chat
|
||||
|
||||
|
||||
# ---------- messages ----------
|
||||
@app.post("/api/v1/chats/{chat_id}/messages",
|
||||
response_model=MessageResponse, status_code=201)
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", response_model=MessageResponse, status_code=201)
|
||||
async def create_message(chat_id: str, body: CreateMessageRequest, request: Request):
|
||||
user = await get_current_user_from_request(request)
|
||||
|
||||
idem_key = request.headers.get("Idempotency-Key")
|
||||
if not idem_key:
|
||||
raise HTTPException(400, detail="Idempotency-Key header is required")
|
||||
if len(idem_key) > 128 or not re.match(r'^[A-Za-z0-9._:-]+$', idem_key):
|
||||
raise HTTPException(400, detail="Idempotency-Key must match ^[A-Za-z0-9._:-]{1,128}$")
|
||||
|
||||
path = f"/api/v1/chats/{chat_id}/messages"
|
||||
request_hash = hashlib.sha256(
|
||||
json.dumps({"chat_id": chat_id, "text": body.text}, sort_keys=True).encode()
|
||||
).hexdigest()
|
||||
|
||||
try:
|
||||
message = store.create_message_idempotent(
|
||||
chat_id, user["id"], body.text,
|
||||
idem_key=idem_key, path=path, request_hash=request_hash)
|
||||
return message
|
||||
UUID(chat_id)
|
||||
except ValueError:
|
||||
raise HTTPException(400, detail="Invalid chat_id")
|
||||
user = await get_current_user_from_request(request)
|
||||
idem_key = request.headers.get("Idempotency-Key")
|
||||
if not idem_key or len(idem_key) > 128 or not re.match(r'^[A-Za-z0-9._:-]{1,128}$', idem_key):
|
||||
raise HTTPException(400, detail="Idempotency-Key must match ^[A-Za-z0-9._:-]{1,128}$")
|
||||
path = f"/api/v1/chats/{chat_id}/messages"
|
||||
request_hash = hashlib.sha256(json.dumps({"chat_id": chat_id, "text": body.text, "attachment_ids": body.attachment_ids}, sort_keys=True).encode()).hexdigest()
|
||||
try:
|
||||
return store.create_message_idempotent(chat_id, user["id"], body.text, body.attachment_ids, idem_key, path, request_hash)
|
||||
except ValueError as e:
|
||||
if str(e) == "idempotency_conflict":
|
||||
raise HTTPException(409, detail="Idempotency-Key reused with different payload")
|
||||
if str(e) == "chat_not_found":
|
||||
raise HTTPException(404, detail="Chat not found")
|
||||
if str(e) == "sender_not_in_chat":
|
||||
raise HTTPException(404, detail="User not in chat")
|
||||
raise HTTPException(400, detail=str(e))
|
||||
mapping = {"idempotency_conflict": (409, "Idempotency-Key reused with different payload"),
|
||||
"chat_not_found": (404, "Chat not found"), "sender_not_in_chat": (404, "User not in chat"),
|
||||
"attachment_not_found": (404, "Attachment not found"), "attachment_not_ready": (409, "Attachment is not ready"),
|
||||
"message_empty": (400, "Message text or attachment is required"), "invalid_attachment_ids": (400, "Invalid attachment_ids")}
|
||||
code, message = mapping.get(str(e), (400, str(e)))
|
||||
raise HTTPException(code, detail=message)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
async def list_messages(chat_id: str, request: Request,
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: Optional[str] = Query(default=None, min_length=1)):
|
||||
async def list_messages(chat_id: str, request: Request, limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None, min_length=1)):
|
||||
user = await get_current_user_from_request(request)
|
||||
try:
|
||||
messages, next_cursor = store.list_messages(chat_id, user["id"], limit, cursor)
|
||||
@@ -258,4 +232,135 @@ async def list_messages(chat_id: str, request: Request,
|
||||
raise HTTPException(404, detail="Chat not found")
|
||||
if str(e) == "user_not_in_chat":
|
||||
raise HTTPException(404, detail="User not in chat")
|
||||
raise HTTPException(400, detail=str(e))
|
||||
raise HTTPException(400, detail=str(e))
|
||||
|
||||
|
||||
def _validate_filename(filename: str) -> str:
|
||||
filename = unquote(filename)
|
||||
if not filename or len(filename) > 255:
|
||||
raise HTTPException(400, detail="Invalid filename")
|
||||
if any(ord(ch) == 0 or ch in '/\\' or ord(ch) < 32 or ord(ch) == 127 for ch in filename):
|
||||
raise HTTPException(400, detail="Invalid filename")
|
||||
return filename
|
||||
|
||||
|
||||
async def _read_limited_body(request: Request) -> bytes:
|
||||
content_length = request.headers.get("content-length")
|
||||
if content_length:
|
||||
try:
|
||||
if int(content_length) > MAX_ATTACHMENT_BYTES:
|
||||
raise HTTPException(413, detail="Attachment is too large")
|
||||
except ValueError:
|
||||
raise HTTPException(400, detail="Invalid Content-Length")
|
||||
buf = io.BytesIO()
|
||||
total = 0
|
||||
async for chunk in request.stream():
|
||||
total += len(chunk)
|
||||
if total > MAX_ATTACHMENT_BYTES:
|
||||
raise HTTPException(413, detail="Attachment is too large")
|
||||
buf.write(chunk)
|
||||
if total == 0:
|
||||
raise HTTPException(400, detail="Empty attachment")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _validate_image(data: bytes, declared_type: str):
|
||||
if declared_type not in ALLOWED_CONTENT_TYPES:
|
||||
raise HTTPException(415, detail="Only image/png and image/jpeg are supported")
|
||||
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
||||
ImageFile.LOAD_TRUNCATED_IMAGES = False
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
img = Image.open(io.BytesIO(data))
|
||||
actual = img.format
|
||||
if actual not in ALLOWED_CONTENT_TYPES.values() or ALLOWED_CONTENT_TYPES[declared_type] != actual:
|
||||
raise HTTPException(415, detail="Content-Type does not match image content")
|
||||
width, height = img.size
|
||||
if width * height > MAX_PIXELS:
|
||||
raise HTTPException(413, detail="Image has too many pixels")
|
||||
img.verify()
|
||||
return actual, width, height
|
||||
except HTTPException:
|
||||
raise
|
||||
except (UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
raise HTTPException(415, detail="Invalid or corrupted image")
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/attachments", response_model=AttachmentResponse, status_code=201)
|
||||
async def upload_attachment(chat_id: str, request: Request, filename: str = Query(..., min_length=1, max_length=255)):
|
||||
try:
|
||||
UUID(chat_id)
|
||||
except ValueError:
|
||||
raise HTTPException(400, detail="Invalid chat_id")
|
||||
user = await get_current_user_from_request(request)
|
||||
filename = _validate_filename(filename)
|
||||
content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||
if content_type not in ALLOWED_CONTENT_TYPES:
|
||||
raise HTTPException(415, detail="Only image/png and image/jpeg are supported")
|
||||
data = await _read_limited_body(request)
|
||||
actual, width, height = _validate_image(data, content_type)
|
||||
if len(data) > MAX_ATTACHMENT_BYTES or width * height > MAX_PIXELS:
|
||||
raise HTTPException(413, detail="Attachment exceeds limits")
|
||||
|
||||
attachment_id = str(uuid4())
|
||||
object_key = f"attachments/{attachment_id}/original"
|
||||
sha256 = hashlib.sha256(data).hexdigest()
|
||||
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
attachment = {"id": attachment_id, "chat_id": chat_id, "owner_id": user["id"], "filename": filename,
|
||||
"content_type": content_type, "size_bytes": len(data), "sha256": sha256,
|
||||
"object_key": object_key, "created_at": now, "updated_at": now}
|
||||
try:
|
||||
s3.put_bytes(object_key, io.BytesIO(data), len(data), content_type)
|
||||
except Exception:
|
||||
raise HTTPException(503, detail="Object storage unavailable")
|
||||
try:
|
||||
return store.create_attachment(attachment)
|
||||
except ValueError as e:
|
||||
try:
|
||||
s3.delete_object(object_key)
|
||||
except Exception:
|
||||
pass
|
||||
if str(e) == "chat_not_found":
|
||||
raise HTTPException(404, detail="Chat not found")
|
||||
if str(e) == "owner_not_in_chat":
|
||||
raise HTTPException(404, detail="Chat not found")
|
||||
raise HTTPException(400, detail=str(e))
|
||||
except Exception:
|
||||
try:
|
||||
s3.delete_object(object_key)
|
||||
except Exception:
|
||||
pass
|
||||
raise HTTPException(500, detail="Attachment metadata could not be saved")
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}", response_model=AttachmentResponse)
|
||||
async def get_attachment(attachment_id: str, request: Request):
|
||||
try:
|
||||
UUID(attachment_id)
|
||||
except ValueError:
|
||||
raise HTTPException(400, detail="Invalid attachment_id")
|
||||
user = await get_current_user_from_request(request)
|
||||
attachment = store.get_attachment(attachment_id, user["id"])
|
||||
if not attachment:
|
||||
raise HTTPException(404, detail="Attachment not found")
|
||||
return attachment
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}/content")
|
||||
async def download_attachment(attachment_id: str, request: Request, variant: str = Query(default="original")):
|
||||
try:
|
||||
UUID(attachment_id)
|
||||
except ValueError:
|
||||
raise HTTPException(400, detail="Invalid attachment_id")
|
||||
user = await get_current_user_from_request(request)
|
||||
if variant != "original":
|
||||
raise HTTPException(404, detail="Attachment variant not found")
|
||||
object_key = store.get_attachment_object_key(attachment_id, user["id"])
|
||||
if not object_key:
|
||||
raise HTTPException(404, detail="Attachment not found")
|
||||
try:
|
||||
obj = s3.get_object(object_key)
|
||||
except Exception:
|
||||
raise HTTPException(503, detail="Object storage unavailable")
|
||||
return StreamingResponse(obj["Body"], media_type=obj.get("ContentType", "application/octet-stream"), headers={"Content-Length": str(obj.get("ContentLength", ""))})
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
-- Lab 4: attachment metadata in PostgreSQL; bytes stay in private S3.
|
||||
ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_text_check;
|
||||
ALTER TABLE messages ADD CONSTRAINT messages_text_check
|
||||
CHECK (length(text) >= 0 AND length(text) <= 4000);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS attachments (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
owner_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
filename VARCHAR(255) NOT NULL,
|
||||
content_type VARCHAR(32) NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
size_bytes BIGINT NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
sha256 CHAR(64) NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||
status VARCHAR(16) NOT NULL CHECK (status = 'ready'),
|
||||
object_key TEXT NOT NULL UNIQUE,
|
||||
error_code TEXT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_attachments_chat ON attachments(chat_id, created_at, id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS message_attachments (
|
||||
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE RESTRICT,
|
||||
PRIMARY KEY (message_id, attachment_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_message_attachments_attachment
|
||||
ON message_attachments(attachment_id, message_id);
|
||||
+43
-5
@@ -1,10 +1,11 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, List
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from pydantic import BaseModel, Field, field_validator, ConfigDict
|
||||
import re
|
||||
|
||||
|
||||
class CreateUserRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
username: str = Field(..., min_length=3, max_length=32)
|
||||
display_name: str = Field(..., min_length=1, max_length=100)
|
||||
password: str = Field(..., min_length=12, max_length=128)
|
||||
@@ -32,6 +33,8 @@ class CreateUserRequest(BaseModel):
|
||||
|
||||
|
||||
class CreateChatRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
title: str = Field(..., min_length=1, max_length=100)
|
||||
member_ids: List[str] = Field(..., min_length=1, max_length=100)
|
||||
|
||||
@@ -44,15 +47,25 @@ class CreateChatRequest(BaseModel):
|
||||
|
||||
|
||||
class CreateMessageRequest(BaseModel):
|
||||
text: str = Field(..., min_length=1, max_length=4000)
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
text: str = Field(..., max_length=4000)
|
||||
attachment_ids: List[str] = Field(default_factory=list, max_length=10)
|
||||
|
||||
@field_validator('text')
|
||||
@classmethod
|
||||
def validate_text(cls, v):
|
||||
if not v.strip():
|
||||
if not v.strip() and not v == '':
|
||||
raise ValueError('text не может состоять только из пробелов')
|
||||
return v
|
||||
|
||||
@field_validator('attachment_ids')
|
||||
@classmethod
|
||||
def validate_attachment_ids(cls, v):
|
||||
if len(v) != len(set(v)):
|
||||
raise ValueError('attachment_ids должны быть уникальными')
|
||||
return v
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
id: str
|
||||
@@ -74,6 +87,7 @@ class MessageResponse(BaseModel):
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: str
|
||||
attachment_ids: List[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
@@ -94,4 +108,28 @@ class SessionResponse(BaseModel):
|
||||
|
||||
|
||||
class HealthResponse(BaseModel):
|
||||
status: str = "ok"
|
||||
status: str = "ok"
|
||||
|
||||
|
||||
class AttachmentVariant(BaseModel):
|
||||
name: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
|
||||
|
||||
class AttachmentResponse(BaseModel):
|
||||
id: str
|
||||
chat_id: str
|
||||
owner_id: str
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: str
|
||||
variants: List[AttachmentVariant]
|
||||
error_code: Optional[str]
|
||||
created_at: str
|
||||
updated_at: str
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
import boto3
|
||||
from botocore.client import Config
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
|
||||
S3_ENDPOINT_URL = os.getenv("S3_ENDPOINT_URL", "http://minio:9000")
|
||||
S3_REGION = os.getenv("S3_REGION", "us-east-1")
|
||||
S3_ACCESS_KEY = os.getenv("S3_ACCESS_KEY", os.getenv("MINIO_ROOT_USER", "minioadmin"))
|
||||
S3_SECRET_KEY = os.getenv("S3_SECRET_KEY", os.getenv("MINIO_ROOT_PASSWORD", "minioadmin"))
|
||||
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
|
||||
|
||||
|
||||
def client():
|
||||
return boto3.client(
|
||||
"s3",
|
||||
endpoint_url=S3_ENDPOINT_URL,
|
||||
aws_access_key_id=S3_ACCESS_KEY,
|
||||
aws_secret_access_key=S3_SECRET_KEY,
|
||||
region_name=S3_REGION,
|
||||
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
|
||||
)
|
||||
|
||||
|
||||
def ensure_bucket(retries: int = 20, delay: float = 1.0) -> None:
|
||||
last_error = None
|
||||
for _ in range(retries):
|
||||
try:
|
||||
s3 = client()
|
||||
try:
|
||||
s3.head_bucket(Bucket=S3_BUCKET)
|
||||
except ClientError as exc:
|
||||
code = str(exc.response.get("Error", {}).get("Code", ""))
|
||||
if code in {"404", "NoSuchBucket", "NotFound"}:
|
||||
s3.create_bucket(Bucket=S3_BUCKET)
|
||||
else:
|
||||
raise
|
||||
# No bucket policy is installed: MinIO's default bucket ACL is private.
|
||||
return
|
||||
except Exception as exc:
|
||||
last_error = exc
|
||||
time.sleep(delay)
|
||||
raise RuntimeError(f"S3 bucket bootstrap failed: {last_error}")
|
||||
|
||||
|
||||
def put_bytes(object_key: str, data, size: int, content_type: str) -> None:
|
||||
client().put_object(
|
||||
Bucket=S3_BUCKET,
|
||||
Key=object_key,
|
||||
Body=data,
|
||||
ContentLength=size,
|
||||
ContentType=content_type,
|
||||
)
|
||||
|
||||
|
||||
def get_object(object_key: str):
|
||||
return client().get_object(Bucket=S3_BUCKET, Key=object_key)
|
||||
|
||||
|
||||
def delete_object(object_key: str) -> None:
|
||||
client().delete_object(Bucket=S3_BUCKET, Key=object_key)
|
||||
|
||||
|
||||
def object_exists(object_key: str) -> bool:
|
||||
try:
|
||||
client().head_object(Bucket=S3_BUCKET, Key=object_key)
|
||||
return True
|
||||
except ClientError as exc:
|
||||
code = str(exc.response.get("Error", {}).get("Code", ""))
|
||||
if code in {"404", "NoSuchKey", "NotFound"}:
|
||||
return False
|
||||
raise
|
||||
|
||||
|
||||
def check_available() -> bool:
|
||||
try:
|
||||
client().head_bucket(Bucket=S3_BUCKET)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
Reference in New Issue
Block a user