diff --git a/app/db/models.py b/app/db/models.py index 08d6827..2c925f6 100644 --- a/app/db/models.py +++ b/app/db/models.py @@ -127,6 +127,7 @@ class Attachment(Base): error_code: Mapped[str] = mapped_column(String(50), nullable=True) s3_key: Mapped[str] = mapped_column(String(500), nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc), nullable=False) class MessageAttachment(Base): __tablename__ = "message_attachments" diff --git a/app/main.py b/app/main.py index fe3ad54..862e90d 100644 --- a/app/main.py +++ b/app/main.py @@ -18,15 +18,10 @@ from sqlalchemy.ext.asyncio import AsyncSession from starlette.middleware.base import BaseHTTPMiddleware from .auth import ( - SESSION_TTL, - create_session, - get_current_user, - hash_password, - hash_token, - revoke_current_session, - verify_password, + SESSION_TTL, create_session, get_current_user, + hash_password, revoke_current_session, verify_password, ) -from .db.models import IdempotencyRecord, SessionRow, User, Attachment, MessageAttachment +from .db.models import IdempotencyRecord, User, Attachment, MessageAttachment from .db.session import get_db from .models import CreateChat, CreateMessage, CreateUser from .repositories import chats as chats_repo @@ -35,35 +30,17 @@ from .repositories import users as users_repo from .s3_client import s3, BUCKET, ensure_bucket from .image_utils import validate_image -# уникальный id инстанса (берется из имени контейнера в docker) INSTANCE_ID = os.environ.get("HOSTNAME", f"api-{socket.gethostname()}") - request_id_var: ContextVar[str] = ContextVar("request_id", default="") _HTTP_CODES = { - 400: "invalid_request", - 401: "unauthorized", - 404: "not_found", - 409: "conflict", - 413: "payload_too_large", - 415: "unsupported_media_type", - 429: "rate_limited", - 503: "unavailable", - 500: "internal_error", + 400: "invalid_request", 401: "unauthorized", 404: "not_found", + 409: "conflict", 413: "payload_too_large", 415: "unsupported_media_type", + 429: "rate_limited", 503: "unavailable", 500: "internal_error", } def err_json(status: int, code: str, message: str) -> JSONResponse: - resp = JSONResponse( - status_code=status, - content={ - "error": { - "code": code, - "message": message, - "request_id": request_id_var.get(), - } - }, - ) - # добавляем заголовок инстанса даже в ошибки + resp = JSONResponse(status_code=status, content={"error": {"code": code, "message": message, "request_id": request_id_var.get()}}) resp.headers["X-Instance-Id"] = INSTANCE_ID return resp @@ -73,7 +50,6 @@ class RequestIdMiddleware(BaseHTTPMiddleware): request_id_var.set(rid) response = await call_next(request) response.headers["X-Request-Id"] = rid - # добавляем заголовок инстанса во все успешные ответы response.headers["X-Instance-Id"] = INSTANCE_ID return response @@ -81,7 +57,6 @@ app = FastAPI(title="MTUSI Messenger — lab4") app.add_middleware(RequestIdMiddleware) security = HTTPBasic(auto_error=False) -# при старте приложения проверяем, что бакет в minio создан @app.on_event("startup") def startup_event(): ensure_bucket() @@ -108,97 +83,56 @@ def _iso_z(dt: datetime) -> str: return dt.isoformat().replace("+00:00", "Z") def _user_json(u: User) -> dict: - return { - "id": str(u.id), - "username": u.username, - "display_name": u.display_name, - "created_at": _iso_z(u.created_at), - } + return {"id": str(u.id), "username": u.username, "display_name": u.display_name, "created_at": _iso_z(u.created_at)} def _chat_json(chat, member_ids: list[str]) -> dict: + return {"id": str(chat.id), "title": chat.title, "member_ids": member_ids, "created_at": _iso_z(chat.created_at)} + +def _msg_json(m, attachment_ids=None) -> dict: return { - "id": str(chat.id), - "title": chat.title, - "member_ids": member_ids, - "created_at": _iso_z(chat.created_at), + "id": str(m.id), "chat_id": str(m.chat_id), "sender_id": str(m.sender_id), + "text": m.text, "created_at": _iso_z(m.created_at), + "attachment_ids": [str(a) for a in (attachment_ids or [])] } -def _msg_json(m) -> dict: - return { - "id": str(m.id), - "chat_id": str(m.chat_id), - "sender_id": str(m.sender_id), - "text": m.text, - "created_at": _iso_z(m.created_at), - } - -# хелпер для формирования json метаданных вложения def _attachment_json(att: Attachment) -> dict: return { - "id": str(att.id), - "chat_id": str(att.chat_id), - "owner_id": str(att.owner_id), - "filename": att.filename, - "content_type": att.content_type, - "size_bytes": att.size_bytes, - "sha256": att.sha256, - "status": att.status, - "error_code": att.error_code, + "id": str(att.id), "chat_id": str(att.chat_id), "owner_id": str(att.owner_id), + "filename": att.filename, "content_type": att.content_type, "size_bytes": att.size_bytes, + "sha256": att.sha256, "status": att.status, "error_code": att.error_code, + "variants": [], "created_at": _iso_z(att.created_at), + "updated_at": _iso_z(att.updated_at), } -# ---------- health ---------- @app.get("/health/live") -def live(): - return {"status": "ok"} +def live(): return {"status": "ok"} @app.get("/health/ready") async def ready(db: AsyncSession = Depends(get_db)): - try: - await db.execute(text("SELECT 1")) - except Exception: - return err_json(503, "unavailable", "Database unavailable") + try: await db.execute(text("SELECT 1")) + except Exception: return err_json(503, "unavailable", "Database unavailable") return {"status": "ok"} -# ---------- users ---------- @app.post("/api/v1/users", status_code=201) async def register(body: CreateUser, db: AsyncSession = Depends(get_db)): existing = await users_repo.get_by_username(db, body.username) - if existing is not None: - raise HTTPException(409, "Username already exists") + if existing is not None: raise HTTPException(409, "Username already exists") try: - user = await users_repo.create( - db, body.username, body.display_name, hash_password(body.password) - ) - except Exception: - raise HTTPException(409, "Username already exists") + user = await users_repo.create(db, body.username, body.display_name, hash_password(body.password)) + except Exception: raise HTTPException(409, "Username already exists") return _user_json(user) -# ---------- sessions ---------- @app.post("/api/v1/auth/sessions", status_code=201) -async def login( - creds: Optional[HTTPBasicCredentials] = Depends(security), - db: AsyncSession = Depends(get_db), -): +async def login(creds: Optional[HTTPBasicCredentials] = Depends(security), db: AsyncSession = Depends(get_db)): basic_challenge = 'Basic realm="messenger", charset="UTF-8"' - if creds is None: - raise HTTPException( - status_code=401, detail="Unauthorized", headers={"WWW-Authenticate": basic_challenge} - ) + if creds is None: raise HTTPException(401, "Unauthorized", headers={"WWW-Authenticate": basic_challenge}) user = await users_repo.get_by_username(db, creds.username) if user is None or not verify_password(creds.password, user.password_hash): - raise HTTPException( - status_code=401, detail="Unauthorized", headers={"WWW-Authenticate": basic_challenge} - ) + raise HTTPException(401, "Unauthorized", headers={"WWW-Authenticate": basic_challenge}) expires = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL) token = await create_session(str(user.id)) - - return { - "token": token, - "token_type": "Bearer", - "expires_at": _iso_z(expires), - "user": _user_json(user), - } + return {"token": token, "token_type": "Bearer", "expires_at": _iso_z(expires), "user": _user_json(user)} @app.delete("/api/v1/auth/sessions/current", status_code=204) async def logout(authorization: str = Header(...), db: AsyncSession = Depends(get_db)): @@ -208,35 +142,22 @@ async def logout(authorization: str = Header(...), db: AsyncSession = Depends(ge async def me(user: User = Depends(get_current_user)): return _user_json(user) -# ---------- chats ---------- @app.post("/api/v1/chats", status_code=201) -async def create_chat( - body: CreateChat, - user: User = Depends(get_current_user), - db: AsyncSession = Depends(get_db), -): - if user.id not in body.member_ids: - raise HTTPException(400, "Caller must be in member_ids") +async def create_chat(body: CreateChat, user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): + if user.id not in body.member_ids: raise HTTPException(400, "Caller must be in member_ids") try: chat = await chats_repo.create_atomic(db, body.title, body.member_ids) - except ValueError: - raise HTTPException(404, "Member not found") + except ValueError: raise HTTPException(404, "Member not found") return _chat_json(chat, [str(x) for x in body.member_ids]) @app.get("/api/v1/chats") -async def list_chats( - user: User = Depends(get_current_user), - limit: int = Query(50, ge=1, le=100), - cursor: Optional[str] = Query(None, min_length=1), - db: AsyncSession = Depends(get_db), -): +async def list_chats(user: User = Depends(get_current_user), limit: int = Query(50, ge=1, le=100), cursor: Optional[str] = Query(None, min_length=1), db: AsyncSession = Depends(get_db)): parsed = None if cursor is not None: try: c_created, c_id = cursor.split("|", 1) parsed = (datetime.fromisoformat(c_created), UUID(c_id)) - except Exception: - raise HTTPException(400, "Invalid cursor") + except Exception: raise HTTPException(400, "Invalid cursor") rows, next_cursor = await chats_repo.list_for_user(db, user.id, limit, parsed) items = [] for chat in rows: @@ -246,49 +167,30 @@ async def list_chats( return {"items": items, "next_cursor": nxt} @app.get("/api/v1/chats/{chat_id}") -async def get_chat( - chat_id: UUID, - user: User = Depends(get_current_user), - db: AsyncSession = Depends(get_db), -): +async def get_chat(chat_id: UUID, user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): chat = await chats_repo.get_if_member(db, chat_id, user.id) - if chat is None: - raise HTTPException(404, "Chat not found") + if chat is None: raise HTTPException(404, "Chat not found") members = await chats_repo.list_member_ids(db, chat.id) return _chat_json(chat, [str(m) for m in members]) -# ---------- messages ---------- @app.post("/api/v1/chats/{chat_id}/messages", status_code=201) -async def post_message( - chat_id: UUID, - body: CreateMessage, - idempotency_key: str = Header(..., alias="Idempotency-Key"), - user: User = Depends(get_current_user), - db: AsyncSession = Depends(get_db), -): +async def post_message(chat_id: UUID, body: CreateMessage, idempotency_key: str = Header(..., alias="Idempotency-Key"), user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): chat = await chats_repo.get_if_member(db, chat_id, user.id) - if chat is None: - raise HTTPException(404, "Chat not found") + if chat is None: raise HTTPException(404, "Chat not found") + + if not body.text.strip() and not body.attachment_ids: + raise HTTPException(400, "Empty message without attachments") req_hash = hashlib.sha256(body.model_dump_json().encode("utf-8")).hexdigest() - - # проверяем, есть ли уже такой ключ идемпотентности - stmt = select(IdempotencyRecord).where( - IdempotencyRecord.user_id == user.id, - IdempotencyRecord.key == idempotency_key, - ) + stmt = select(IdempotencyRecord).where(IdempotencyRecord.user_id == user.id, IdempotencyRecord.key == idempotency_key) record = (await db.execute(stmt)).scalar_one_or_none() if record: - if record.request_hash != req_hash: - raise HTTPException(409, "Idempotency key conflict") - # возвращаем сохраненный ответ (201 и тот же JSON) + if record.request_hash != req_hash: raise HTTPException(409, "Idempotency key conflict") return JSONResponse(status_code=201, content=json.loads(record.response_body)) - # создаем сообщение msg = await messages_repo.create_and_invalidate(db, chat_id, user.id, body.text) - # привязываем вложения, если они были переданы if body.attachment_ids: for att_id in body.attachment_ids: att = await db.get(Attachment, att_id) @@ -296,21 +198,13 @@ async def post_message( raise HTTPException(404, f"Attachment {att_id} not found in this chat") db.add(MessageAttachment(message_id=msg.id, attachment_id=att_id)) - resp_dict = _msg_json(msg) - resp_dict["attachment_ids"] = [str(a) for a in (body.attachment_ids or [])] + resp_dict = _msg_json(msg, body.attachment_ids) resp_body = json.dumps(resp_dict) - # сохраняем ключ идемпотентности - db.add(IdempotencyRecord( - user_id=user.id, - key=idempotency_key, - request_hash=req_hash, - response_body=resp_body - )) + db.add(IdempotencyRecord(user_id=user.id, key=idempotency_key, request_hash=req_hash, response_body=resp_body)) try: await db.commit() except IntegrityError: - # гонка: другая реплика уже вставила этот ключ await db.rollback() record = (await db.execute(stmt)).scalar_one_or_none() if record and record.request_hash == req_hash: @@ -320,96 +214,65 @@ async def post_message( return JSONResponse(status_code=201, content=json.loads(resp_body)) @app.get("/api/v1/chats/{chat_id}/messages") -async def list_messages( - chat_id: UUID, - user: User = Depends(get_current_user), - limit: int = Query(50, ge=1, le=100), - cursor: Optional[str] = Query(None, min_length=1), - db: AsyncSession = Depends(get_db), -): +async def list_messages(chat_id: UUID, user: User = Depends(get_current_user), limit: int = Query(50, ge=1, le=100), cursor: Optional[str] = Query(None, min_length=1), db: AsyncSession = Depends(get_db)): chat = await chats_repo.get_if_member(db, chat_id, user.id) - if chat is None: - raise HTTPException(404, "Chat not found") + if chat is None: raise HTTPException(404, "Chat not found") parsed = None if cursor is not None: try: c_created, c_id = cursor.split("|", 1) parsed = (datetime.fromisoformat(c_created), UUID(c_id)) - except Exception: - raise HTTPException(400, "Invalid cursor") + except Exception: raise HTTPException(400, "Invalid cursor") rows, next_cursor, _cached = await messages_repo.list_page_cached(db, chat_id, limit, parsed) + msg_ids = [m.id for m in rows] + att_map = {} + if msg_ids: + att_stmt = select(MessageAttachment.message_id, MessageAttachment.attachment_id).where(MessageAttachment.message_id.in_(msg_ids)) + att_rows = (await db.execute(att_stmt)).all() + for mid, aid in att_rows: att_map.setdefault(mid, []).append(aid) + + items = [_msg_json(m, att_map.get(m.id, [])) for m in rows] nxt = f"{next_cursor[0].isoformat()}|{next_cursor[1]}" if next_cursor else None - return {"items": [_msg_json(m) for m in rows], "next_cursor": nxt} + return {"items": items, "next_cursor": nxt} -# ---------- attachments ---------- @app.post("/api/v1/chats/{chat_id}/attachments", status_code=201) -async def upload_attachment( - chat_id: UUID, - filename: str = Query(..., min_length=1, max_length=255), - request: Request = None, - user: User = Depends(get_current_user), - db: AsyncSession = Depends(get_db), -): - # проверяем, что чат существует и юзер в нем состоит +async def upload_attachment(chat_id: UUID, request: Request, filename: str = Query(..., min_length=1, max_length=255), user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): chat = await chats_repo.get_if_member(db, chat_id, user.id) - if not chat: - raise HTTPException(404, "Chat not found") + if not chat: raise HTTPException(404, "Chat not found") - # читаем сырые байты из тела запроса content = await request.body() - - # валидируем картинку (размер и формат) mime = validate_image(content) sha256 = hashlib.sha256(content).hexdigest() ext = ".png" if mime == "image/png" else ".jpg" s3_key = f"{chat_id}/{uuid.uuid4()}{ext}" - # загружаем в minio s3.put_object(Bucket=BUCKET, Key=s3_key, Body=content, ContentType=mime) - # сохраняем метаданные в базу - att = Attachment( - chat_id=chat_id, owner_id=user.id, filename=filename, - content_type=mime, size_bytes=len(content), sha256=sha256, - status="ready", s3_key=s3_key, - ) + att = Attachment(chat_id=chat_id, owner_id=user.id, filename=filename, content_type=mime, size_bytes=len(content), sha256=sha256, status="ready", s3_key=s3_key) db.add(att) await db.commit() await db.refresh(att) return _attachment_json(att) @app.get("/api/v1/attachments/{attachment_id}") -async def get_attachment( - attachment_id: UUID, - user: User = Depends(get_current_user), - db: AsyncSession = Depends(get_db), -): +async def get_attachment(attachment_id: UUID, user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): att = await db.get(Attachment, attachment_id) - if not att: - raise HTTPException(404, "Attachment not found") + if not att: raise HTTPException(404, "Attachment not found") chat = await chats_repo.get_if_member(db, att.chat_id, user.id) - if not chat: - raise HTTPException(404, "Attachment not found") + if not chat: raise HTTPException(404, "Attachment not found") return _attachment_json(att) @app.get("/api/v1/attachments/{attachment_id}/content") -async def download_attachment( - attachment_id: UUID, - user: User = Depends(get_current_user), - db: AsyncSession = Depends(get_db), -): +async def download_attachment(attachment_id: UUID, user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)): att = await db.get(Attachment, attachment_id) - if not att: - raise HTTPException(404, "Attachment not found") + if not att: raise HTTPException(404, "Attachment not found") chat = await chats_repo.get_if_member(db, att.chat_id, user.id) - if not chat: - raise HTTPException(404, "Attachment not found") + if not chat: raise HTTPException(404, "Attachment not found") - # вытаскиваем файл из minio и отдаем его клиенту obj = s3.get_object(Bucket=BUCKET, Key=att.s3_key) content = obj["Body"].read() return Response(content=content, media_type=att.content_type) diff --git a/app/models.py b/app/models.py index e98a1a9..39f0676 100644 --- a/app/models.py +++ b/app/models.py @@ -1,8 +1,6 @@ from uuid import UUID - from pydantic import BaseModel, ConfigDict, Field, field_validator - class CreateUser(BaseModel): model_config = ConfigDict(extra="forbid") username: str = Field(pattern=r"^[a-z0-9_]{3,32}$") @@ -16,7 +14,6 @@ class CreateUser(BaseModel): raise ValueError("must not be blank") return v - class CreateChat(BaseModel): model_config = ConfigDict(extra="forbid") title: str = Field(min_length=1, max_length=100) @@ -36,18 +33,11 @@ class CreateChat(BaseModel): raise ValueError("duplicate member_ids") return v - class CreateMessage(BaseModel): model_config = ConfigDict(extra="forbid") - text: str = Field(min_length=1, max_length=4000) - - @field_validator("text") - @classmethod - def _text_not_blank(cls, v: str) -> str: - if not v.strip(): - raise ValueError("text must not be blank") - return v - + # min_length=0 разрешает пустой текст, если прикреплен файл + text: str = Field(min_length=0, max_length=4000) + attachment_ids: list[UUID] | None = None class SessionResponse(BaseModel): token: str @@ -66,9 +56,6 @@ class AttachmentResponse(BaseModel): sha256: str status: str error_code: str | None = None + variants: list = [] created_at: str - -class CreateMessage(BaseModel): - model_config = ConfigDict(extra="forbid") - text: str = Field(min_length=1, max_length=4000) - attachment_ids: list[UUID] | None = None \ No newline at end of file + updated_at: str \ No newline at end of file diff --git a/compose.yaml b/compose.yaml index 0628438..52b1505 100644 --- a/compose.yaml +++ b/compose.yaml @@ -27,7 +27,7 @@ services: retries: 10 minio: - image: minio/minio:RELEASE.2025-04-22T22-12-26Z + image: dappros/minio:RELEASE.2025-09-07T16-13-09Z command: server /data --console-address ":9001" environment: MINIO_ROOT_USER: ${MINIO_ROOT_USER} diff --git a/migrations/versions/133990c80d19_add_updated_at_to_attachments.py b/migrations/versions/133990c80d19_add_updated_at_to_attachments.py new file mode 100644 index 0000000..029d184 --- /dev/null +++ b/migrations/versions/133990c80d19_add_updated_at_to_attachments.py @@ -0,0 +1,30 @@ +"""add updated_at to attachments + +Revision ID: 133990c80d19 +Revises: abc40f94dd51 +Create Date: 2026-11-11 21:06:40.354578 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '133990c80d19' +down_revision: Union[str, None] = 'abc40f94dd51' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('attachments', sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False)) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('attachments', 'updated_at') + # ### end Alembic commands ### diff --git a/migrations/versions/abc40f94dd51_add_updated_at_to_attachments.py b/migrations/versions/abc40f94dd51_add_updated_at_to_attachments.py new file mode 100644 index 0000000..d32898d --- /dev/null +++ b/migrations/versions/abc40f94dd51_add_updated_at_to_attachments.py @@ -0,0 +1,30 @@ +"""add updated_at to attachments + +Revision ID: abc40f94dd51 +Revises: 67c68635da78 +Create Date: 2026-11-11 20:58:37.486897 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'abc40f94dd51' +down_revision: Union[str, None] = '67c68635da78' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + pass + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + pass + # ### end Alembic commands ### diff --git a/tests/client.py b/tests/client.py index f0499a2..5116569 100644 --- a/tests/client.py +++ b/tests/client.py @@ -49,7 +49,8 @@ def validate(value, schema, where='response'): check(value == schema['const'], where + ': invalid const') if isinstance(value,dict): props = schema.get('properties',{}) - check(all(k in value for k in schema.get('required',[])), where + ': missing required fields') + missing = [k for k in schema.get('required',[]) if k not in value] + check(not missing, where + ': missing required fields: ' + str(missing)) if schema.get('additionalProperties') is False: check(not set(value).difference(props), where + ': unexpected fields') for key, sub in props.items():