forked from mtusi2026/mtusi2026lab4
Carry over lab3 HA stack and add private S3 storage, Attachment API, orphan compensation/reaper, own tests, and evidence for smoke/persistence/failover.
317 lines
11 KiB
Python
317 lines
11 KiB
Python
"""Бизнес-логика lab4."""
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import uuid
|
|
from typing import List, Optional
|
|
|
|
from app import cursor as cursor_util
|
|
from app.auth import BASIC_CHALLENGE, parse_basic
|
|
from app.config import settings
|
|
from app.db import Database
|
|
from app.errors import conflict, invalid_request, not_found, unauthorized
|
|
from app.images import detect_and_validate_image
|
|
from app.models import Attachment, Chat, Message, User
|
|
from app.password import hash_password, verify_password
|
|
from app.s3store import S3Store
|
|
from app.sessions import SessionStore
|
|
from app.timefmt import now_utc
|
|
from app.validation import (
|
|
parse_limit,
|
|
parse_uuid,
|
|
reject_unknown,
|
|
require_display_name,
|
|
require_filename,
|
|
require_idempotency_key,
|
|
require_keys,
|
|
require_message_text,
|
|
require_object,
|
|
require_password,
|
|
require_title,
|
|
require_username,
|
|
)
|
|
|
|
|
|
class UserService:
|
|
def __init__(self, db: Database) -> None:
|
|
self.db = db
|
|
|
|
def create(self, body: object) -> dict:
|
|
data = require_object(body)
|
|
reject_unknown(data, {"username", "display_name", "password"})
|
|
require_keys(data, ("username", "display_name", "password"))
|
|
username = require_username(data["username"])
|
|
display_name = require_display_name(data["display_name"])
|
|
password = require_password(data["password"])
|
|
user = User(
|
|
id=str(uuid.uuid4()),
|
|
username=username,
|
|
display_name=display_name,
|
|
created_at=now_utc(),
|
|
password_hash=hash_password(password),
|
|
)
|
|
try:
|
|
self.db.add_user(user)
|
|
except KeyError as exc:
|
|
raise conflict("username уже занят") from exc
|
|
return user.to_dict()
|
|
|
|
|
|
class AuthService:
|
|
def __init__(self, db: Database, sessions: SessionStore) -> None:
|
|
self.db = db
|
|
self.sessions = sessions
|
|
|
|
def create_session(self, authorization: Optional[str]) -> dict:
|
|
username, password = parse_basic(authorization)
|
|
user = self.db.get_user_by_username(username)
|
|
if user is None or not verify_password(user.password_hash, password):
|
|
raise unauthorized("Неверные учётные данные", challenge=BASIC_CHALLENGE)
|
|
token, expires_at = self.sessions.create(user.id)
|
|
return {
|
|
"token": token,
|
|
"token_type": "Bearer",
|
|
"expires_at": expires_at,
|
|
"user": user.to_dict(),
|
|
}
|
|
|
|
def logout(self, token: str) -> None:
|
|
self.sessions.revoke(token)
|
|
|
|
|
|
class ChatService:
|
|
def __init__(self, db: Database) -> None:
|
|
self.db = db
|
|
|
|
def create(self, actor: User, body: object) -> dict:
|
|
data = require_object(body)
|
|
reject_unknown(data, {"title", "member_ids"})
|
|
require_keys(data, ("title", "member_ids"))
|
|
title = require_title(data["title"])
|
|
raw_members = data["member_ids"]
|
|
if not isinstance(raw_members, list):
|
|
raise invalid_request("member_ids должен быть массивом")
|
|
if len(raw_members) < 1 or len(raw_members) > 100:
|
|
raise invalid_request("member_ids: от 1 до 100 участников")
|
|
member_ids: List[str] = []
|
|
seen = set()
|
|
for item in raw_members:
|
|
mid = parse_uuid(item, "member_ids")
|
|
if mid in seen:
|
|
raise invalid_request("member_ids содержит дубликаты")
|
|
seen.add(mid)
|
|
member_ids.append(mid)
|
|
if actor.id not in seen:
|
|
raise invalid_request("Вызывающий должен быть в member_ids")
|
|
if not self.db.users_exist(member_ids):
|
|
raise invalid_request("Неизвестный участник")
|
|
chat = Chat(
|
|
id=str(uuid.uuid4()),
|
|
title=title,
|
|
member_ids=member_ids,
|
|
created_at=now_utc(),
|
|
)
|
|
try:
|
|
self.db.add_chat(chat)
|
|
except ValueError as exc:
|
|
raise invalid_request("Неизвестный участник") from exc
|
|
return chat.to_dict()
|
|
|
|
def get_for_member(self, actor: User, chat_id: str) -> Chat:
|
|
cid = parse_uuid(chat_id, "chat_id")
|
|
chat = self.db.get_chat(cid)
|
|
if chat is None or actor.id not in chat.member_ids:
|
|
raise not_found()
|
|
return chat
|
|
|
|
def list_for_user(self, actor: User, limit_raw: Optional[str], cursor_raw: Optional[str]) -> dict:
|
|
limit = parse_limit(limit_raw)
|
|
chats = self.db.list_chats_for(actor.id)
|
|
start = 0
|
|
if cursor_raw:
|
|
created_at, item_id = cursor_util.decode(cursor_raw, actor.id)
|
|
for i, chat in enumerate(chats):
|
|
if (chat.created_at, chat.id) > (created_at, item_id):
|
|
start = i
|
|
break
|
|
else:
|
|
start = len(chats)
|
|
page = chats[start : start + limit]
|
|
next_cursor = None
|
|
if start + limit < len(chats) and page:
|
|
last = page[-1]
|
|
next_cursor = cursor_util.encode(actor.id, last.created_at, last.id)
|
|
return {"items": [c.to_dict() for c in page], "next_cursor": next_cursor}
|
|
|
|
|
|
def _message_request_hash(text: str, attachment_ids: List[str]) -> str:
|
|
canonical = json.dumps(
|
|
{"text": text, "attachment_ids": attachment_ids},
|
|
ensure_ascii=False,
|
|
separators=(",", ":"),
|
|
sort_keys=True,
|
|
)
|
|
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
|
|
|
|
class MessageService:
|
|
def __init__(self, db: Database) -> None:
|
|
self.db = db
|
|
|
|
def create(
|
|
self,
|
|
actor: User,
|
|
chat: Chat,
|
|
body: object,
|
|
*,
|
|
idempotency_key: Optional[str],
|
|
method: str,
|
|
path: str,
|
|
) -> dict:
|
|
data = require_object(body)
|
|
reject_unknown(data, {"text", "attachment_ids"})
|
|
require_keys(data, ("text",))
|
|
raw_ids = data.get("attachment_ids", [])
|
|
if raw_ids is None:
|
|
raw_ids = []
|
|
if not isinstance(raw_ids, list):
|
|
raise invalid_request("attachment_ids должен быть массивом")
|
|
if len(raw_ids) > 10:
|
|
raise invalid_request("attachment_ids: максимум 10")
|
|
attachment_ids: List[str] = []
|
|
seen = set()
|
|
for item in raw_ids:
|
|
aid = parse_uuid(item, "attachment_ids")
|
|
if aid in seen:
|
|
raise invalid_request("attachment_ids содержит дубликаты")
|
|
seen.add(aid)
|
|
attachment_ids.append(aid)
|
|
|
|
allow_blank = len(attachment_ids) > 0
|
|
text = require_message_text(data["text"], allow_blank=allow_blank)
|
|
if text.strip() == "" and not attachment_ids:
|
|
raise invalid_request("text не может быть пустым")
|
|
|
|
if attachment_ids:
|
|
found = self.db.get_attachments_for_chat(chat.id, attachment_ids)
|
|
by_id = {a.id: a for a in found}
|
|
if len(by_id) != len(attachment_ids):
|
|
raise not_found()
|
|
for aid in attachment_ids:
|
|
att = by_id[aid]
|
|
if att.status != "ready":
|
|
raise conflict("Вложение ещё не готово или повреждено")
|
|
|
|
key = require_idempotency_key(idempotency_key)
|
|
message = Message(
|
|
id=str(uuid.uuid4()),
|
|
chat_id=chat.id,
|
|
sender_id=actor.id,
|
|
text=text,
|
|
created_at=now_utc(),
|
|
attachment_ids=attachment_ids,
|
|
)
|
|
payload, _created = self.db.create_message_idempotent(
|
|
message,
|
|
user_id=actor.id,
|
|
method=method,
|
|
path=path,
|
|
idem_key=key,
|
|
request_hash=_message_request_hash(text, attachment_ids),
|
|
)
|
|
return payload
|
|
|
|
def list_for_chat(
|
|
self,
|
|
chat: Chat,
|
|
limit_raw: Optional[str],
|
|
cursor_raw: Optional[str],
|
|
) -> dict:
|
|
limit = parse_limit(limit_raw)
|
|
after_created_at = None
|
|
after_id = None
|
|
if cursor_raw:
|
|
created_at, item_id = cursor_util.decode(cursor_raw, chat.id)
|
|
parse_uuid(item_id, "cursor.id")
|
|
after_created_at = created_at
|
|
after_id = item_id
|
|
rows = self.db.list_messages_page(
|
|
chat.id,
|
|
limit + 1,
|
|
after_created_at=after_created_at,
|
|
after_id=after_id,
|
|
)
|
|
page = rows[:limit]
|
|
next_cursor = None
|
|
if len(rows) > limit and page:
|
|
last = page[-1]
|
|
next_cursor = cursor_util.encode(chat.id, last.created_at, last.id)
|
|
return {"items": [m.to_dict() for m in page], "next_cursor": next_cursor}
|
|
|
|
|
|
class AttachmentService:
|
|
def __init__(self, db: Database, s3: S3Store) -> None:
|
|
self.db = db
|
|
self.s3 = s3
|
|
|
|
def upload(
|
|
self,
|
|
actor: User,
|
|
chat: Chat,
|
|
*,
|
|
filename_raw: Optional[str],
|
|
content_type: str,
|
|
data: bytes,
|
|
) -> dict:
|
|
filename = require_filename(filename_raw)
|
|
media = content_type.split(";")[0].strip().lower()
|
|
content_type_ok, _w, _h = detect_and_validate_image(data, media)
|
|
digest = hashlib.sha256(data).hexdigest()
|
|
att_id = str(uuid.uuid4())
|
|
object_key = f"attachments/{chat.id}/{att_id}"
|
|
ts = now_utc()
|
|
# S3 first; on DB failure compensate by deleting object (no permanent orphan).
|
|
self.s3.put_bytes(object_key, data, content_type_ok)
|
|
att = Attachment(
|
|
id=att_id,
|
|
chat_id=chat.id,
|
|
owner_id=actor.id,
|
|
filename=filename,
|
|
content_type=content_type_ok,
|
|
size_bytes=len(data),
|
|
sha256=digest,
|
|
object_key=object_key,
|
|
status="ready",
|
|
error_code=None,
|
|
created_at=ts,
|
|
updated_at=ts,
|
|
variants=[],
|
|
)
|
|
try:
|
|
self.db.add_attachment(att)
|
|
except Exception:
|
|
self.s3.delete_object(object_key)
|
|
raise
|
|
return att.to_dict()
|
|
|
|
def get_for_member(self, actor: User, attachment_id: str) -> Attachment:
|
|
aid = parse_uuid(attachment_id, "attachment_id")
|
|
att = self.db.get_attachment(aid)
|
|
if att is None:
|
|
raise not_found()
|
|
chat = self.db.get_chat(att.chat_id)
|
|
if chat is None or actor.id not in chat.member_ids:
|
|
raise not_found()
|
|
return att
|
|
|
|
def download_for_member(self, actor: User, attachment_id: str) -> tuple:
|
|
att = self.get_for_member(actor, attachment_id)
|
|
if att.status != "ready":
|
|
raise conflict("Содержимое вложения недоступно")
|
|
try:
|
|
data = self.s3.get_bytes(att.object_key)
|
|
except FileNotFoundError as exc:
|
|
raise not_found() from exc
|
|
return att, data
|