Поправила замечания про нарушение контракта OpenAPI
This commit is contained in:
+18
-7
@@ -1,5 +1,6 @@
|
|||||||
import base64
|
import base64
|
||||||
import json
|
import json
|
||||||
|
from datetime import datetime
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
from ..models.schemas import Chat, ChatPage, CreateChat, User
|
from ..models.schemas import Chat, ChatPage, CreateChat, User
|
||||||
@@ -16,14 +17,23 @@ def _encode_cursor(user_id: UUID, chat: Chat) -> str:
|
|||||||
return base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
|
return base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
|
||||||
|
|
||||||
|
|
||||||
def _decode_cursor(user_id: UUID, cursor: str) -> tuple:
|
def _decode_cursor(user_id: UUID, cursor: str) -> tuple[datetime, UUID]:
|
||||||
|
"""Курсор привязан к пользователю. Любая порча → 400, не 500."""
|
||||||
try:
|
try:
|
||||||
data = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode())
|
raw = base64.urlsafe_b64decode(cursor.encode()).decode()
|
||||||
if data.get("user_id") != str(user_id):
|
data = json.loads(raw)
|
||||||
raise ValueError("cursor_user_mismatch")
|
|
||||||
return UUID(data["id"]), data["created_at"]
|
|
||||||
except Exception:
|
except Exception:
|
||||||
raise HTTPException(status_code=400, detail="invalid_request")
|
raise HTTPException(status_code=400, detail="invalid_request")
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
raise HTTPException(status_code=400, detail="invalid_request")
|
||||||
|
if data.get("user_id") != str(user_id):
|
||||||
|
raise HTTPException(status_code=400, detail="invalid_request")
|
||||||
|
try:
|
||||||
|
created_at = datetime.fromisoformat(data["created_at"])
|
||||||
|
chat_id = UUID(data["id"])
|
||||||
|
except (KeyError, ValueError, TypeError):
|
||||||
|
raise HTTPException(status_code=400, detail="invalid_request")
|
||||||
|
return created_at, chat_id
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
@router.post(
|
||||||
@@ -61,8 +71,9 @@ def list_chats(
|
|||||||
user_id = user.id
|
user_id = user.id
|
||||||
chats = storage.list_chats_for_user(user_id)
|
chats = storage.list_chats_for_user(user_id)
|
||||||
if cursor:
|
if cursor:
|
||||||
cid, ccreated = _decode_cursor(user_id, cursor)
|
ccreated, cid = _decode_cursor(user_id, cursor)
|
||||||
chats = [c for c in chats if (c.created_at.isoformat(), str(c.id)) > (ccreated, str(cid))]
|
ccreated_iso = ccreated.isoformat()
|
||||||
|
chats = [c for c in chats if (c.created_at.isoformat(), str(c.id)) > (ccreated_iso, str(cid))]
|
||||||
page = chats[:limit]
|
page = chats[:limit]
|
||||||
next_cursor = _encode_cursor(user_id, page[-1]) if len(chats) > limit else None
|
next_cursor = _encode_cursor(user_id, page[-1]) if len(chats) > limit else None
|
||||||
return ChatPage(items=page, next_cursor=next_cursor)
|
return ChatPage(items=page, next_cursor=next_cursor)
|
||||||
|
|||||||
+12
-16
@@ -11,6 +11,9 @@ from .security import current_user
|
|||||||
|
|
||||||
router = APIRouter(prefix="/api/v1/chats", tags=["messages"])
|
router = APIRouter(prefix="/api/v1/chats", tags=["messages"])
|
||||||
|
|
||||||
|
# Контракт: Idempotency-Key ASCII [A-Za-z0-9._:-]{1,128}.
|
||||||
|
_IDEMPOTENCY_ALLOWED = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._:-")
|
||||||
|
|
||||||
|
|
||||||
def _require_member(chat_id: UUID, user_id: UUID):
|
def _require_member(chat_id: UUID, user_id: UUID):
|
||||||
chat = storage.get_chat(chat_id)
|
chat = storage.get_chat(chat_id)
|
||||||
@@ -35,12 +38,13 @@ def _decode_cursor(chat_id: UUID, cursor: str) -> tuple:
|
|||||||
|
|
||||||
|
|
||||||
def _canonical_body_hash(payload: CreateMessage) -> str:
|
def _canonical_body_hash(payload: CreateMessage) -> str:
|
||||||
"""sha256 канонизированного JSON. Отсутствующий attachment_ids == [].
|
"""sha256 канонизированного JSON.
|
||||||
Порядок ключей не важен (sort_keys). Это ровно то, что требует контракт:
|
|
||||||
'порядок ключей JSON и отсутствующий attachment_ids вместо [] семантически равны'.
|
Поле attachment_ids присутствует в модели со значением по умолчанию [],
|
||||||
|
поэтому payload {"text":"x"} и {"text":"x","attachment_ids":[]} дают
|
||||||
|
одинаковый model_dump и одинаковый хэш — как требует контракт.
|
||||||
"""
|
"""
|
||||||
data = payload.model_dump(exclude_none=True)
|
data = payload.model_dump()
|
||||||
data.setdefault("attachment_ids", [])
|
|
||||||
canonical = json.dumps(data, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
canonical = json.dumps(data, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
||||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
@@ -57,15 +61,13 @@ def create_message(
|
|||||||
user: User = Depends(current_user),
|
user: User = Depends(current_user),
|
||||||
idempotency_key: str = Header(..., alias="Idempotency-Key"),
|
idempotency_key: str = Header(..., alias="Idempotency-Key"),
|
||||||
) -> Message:
|
) -> Message:
|
||||||
# Контракт: ключ ASCII [A-Za-z0-9._:-]{1,128}.
|
# Строго ASCII, как требует контракт: isalnum() пропускает кириллицу.
|
||||||
if not (1 <= len(idempotency_key) <= 128):
|
if not (1 <= len(idempotency_key) <= 128):
|
||||||
raise HTTPException(status_code=400, detail="invalid_request")
|
raise HTTPException(status_code=400, detail="invalid_request")
|
||||||
if not all(c.isalnum() or c in "._:-" for c in idempotency_key):
|
if not all(c in _IDEMPOTENCY_ALLOWED for c in idempotency_key):
|
||||||
raise HTTPException(status_code=400, detail="invalid_request")
|
raise HTTPException(status_code=400, detail="invalid_request")
|
||||||
|
|
||||||
_require_member(chat_id, user.id)
|
_require_member(chat_id, user.id)
|
||||||
if not payload.text.strip():
|
|
||||||
raise HTTPException(status_code=400, detail="invalid_request")
|
|
||||||
|
|
||||||
method = "POST"
|
method = "POST"
|
||||||
path = "/api/v1/chats/%s/messages" % chat_id
|
path = "/api/v1/chats/%s/messages" % chat_id
|
||||||
@@ -73,7 +75,6 @@ def create_message(
|
|||||||
|
|
||||||
# Атомарная операция: INSERT ключа + INSERT сообщения + UPDATE ключа
|
# Атомарная операция: INSERT ключа + INSERT сообщения + UPDATE ключа
|
||||||
# в ОДНОЙ транзакции. Сбой между ними невозможен: либо всё, либо ничего.
|
# в ОДНОЙ транзакции. Сбой между ними невозможен: либо всё, либо ничего.
|
||||||
# Повтор с тем же ключом при завершённой записи вернёт сохранённый ответ.
|
|
||||||
state, message, info = storage.add_message_idempotent(
|
state, message, info = storage.add_message_idempotent(
|
||||||
chat_id=chat_id,
|
chat_id=chat_id,
|
||||||
sender_id=user.id,
|
sender_id=user.id,
|
||||||
@@ -89,17 +90,13 @@ def create_message(
|
|||||||
return message
|
return message
|
||||||
|
|
||||||
if state == "retry":
|
if state == "retry":
|
||||||
# Крайне редкий случай: конфликт при INSERT, но строки ещё нет.
|
|
||||||
raise HTTPException(status_code=503, detail="unavailable")
|
raise HTTPException(status_code=503, detail="unavailable")
|
||||||
|
|
||||||
# state == "replay"
|
# state == "replay"
|
||||||
if info["body_hash"] != body_hash:
|
if info["body_hash"] != body_hash:
|
||||||
raise HTTPException(status_code=409, detail="conflict")
|
raise HTTPException(status_code=409, detail="conflict")
|
||||||
if info["response_status"] == 0:
|
if info["response_status"] == 0:
|
||||||
# Строка с response_status=0 осталась от СТАРОЙ версии кода
|
# Строка от старой версии кода: не зависаем, отдаём 503.
|
||||||
# (до перехода на атомарную запись). Такое возможно только для
|
|
||||||
# записей, сделанных предыдущей версией. Считаем их незавершёнными
|
|
||||||
# и просим клиента повторить с новым ключом — но НЕ зависаем.
|
|
||||||
raise HTTPException(status_code=503, detail="unavailable")
|
raise HTTPException(status_code=503, detail="unavailable")
|
||||||
return Message.model_validate(info["response_body"])
|
return Message.model_validate(info["response_body"])
|
||||||
|
|
||||||
@@ -118,7 +115,6 @@ def list_messages(
|
|||||||
"""Keyset-пагинация в SQL: (created_at, id) по возрастанию"""
|
"""Keyset-пагинация в SQL: (created_at, id) по возрастанию"""
|
||||||
_require_member(chat_id, user.id)
|
_require_member(chat_id, user.id)
|
||||||
after = _decode_cursor(chat_id, cursor) if cursor else None
|
after = _decode_cursor(chat_id, cursor) if cursor else None
|
||||||
# Берём limit+1, чтобы понять, есть ли следующая страница
|
|
||||||
rows = storage.list_messages_page(chat_id, limit + 1, after=after)
|
rows = storage.list_messages_page(chat_id, limit + 1, after=after)
|
||||||
has_more = len(rows) > limit
|
has_more = len(rows) > limit
|
||||||
items = rows[:limit]
|
items = rows[:limit]
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ router = APIRouter(prefix="/api/v1", tags=["users"])
|
|||||||
status_code=201,
|
status_code=201,
|
||||||
)
|
)
|
||||||
def register_user(payload: CreateUser) -> User:
|
def register_user(payload: CreateUser) -> User:
|
||||||
"""Публичная регистрация."""
|
"""Публичная регистрация. Пробельные display_name/password отсекаются
|
||||||
|
валидаторами схемы; сюда попадают только валидные значения."""
|
||||||
try:
|
try:
|
||||||
return storage.create_user(payload.username, payload.display_name, payload.password)
|
return storage.create_user(payload.username, payload.display_name, payload.password)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
|
|||||||
+5
-2
@@ -114,8 +114,11 @@ def _error_response(
|
|||||||
headers = {}
|
headers = {}
|
||||||
if status_code == 401:
|
if status_code == 401:
|
||||||
headers["WWW-Authenticate"] = _unauthorized_challenge(path)
|
headers["WWW-Authenticate"] = _unauthorized_challenge(path)
|
||||||
# X-Instance-Id может не быть при ошибке до middleware — но middleware
|
# Контракт: X-Request-Id и X-Instance-Id обязательны во ВСЕХ ответах,
|
||||||
# оборачивает всё, так что заголовок будет добавлен в middleware.
|
# включая 500, которые формируются в обход middleware (exception handlers
|
||||||
|
# срабатывают ПОСЛЕ call_next). Проставляем их здесь явно.
|
||||||
|
headers["X-Request-Id"] = request_id
|
||||||
|
headers["X-Instance-Id"] = INSTANCE_ID
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
status_code=status_code,
|
status_code=status_code,
|
||||||
content={"error": {"code": code, "message": message, "request_id": request_id}},
|
content={"error": {"code": code, "message": message, "request_id": request_id}},
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ from datetime import datetime, timezone
|
|||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field, field_serializer
|
from pydantic import BaseModel, ConfigDict, Field, field_serializer, field_validator
|
||||||
|
|
||||||
|
|
||||||
def _to_z(dt: datetime) -> str:
|
def _to_z(dt: datetime) -> str:
|
||||||
@@ -13,6 +13,13 @@ def _to_z(dt: datetime) -> str:
|
|||||||
return dt.isoformat().replace("+00:00", "Z")
|
return dt.isoformat().replace("+00:00", "Z")
|
||||||
|
|
||||||
|
|
||||||
|
def _not_blank(value: str) -> str:
|
||||||
|
"""Контракт: обязательные строки не состоят только из пробельных символов."""
|
||||||
|
if value is None or value.strip() == "":
|
||||||
|
raise ValueError("must not be blank")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
class Health(BaseModel):
|
class Health(BaseModel):
|
||||||
model_config = ConfigDict(extra="forbid")
|
model_config = ConfigDict(extra="forbid")
|
||||||
status: str
|
status: str
|
||||||
@@ -24,6 +31,16 @@ class CreateUser(BaseModel):
|
|||||||
display_name: str = Field(min_length=1, max_length=100)
|
display_name: str = Field(min_length=1, max_length=100)
|
||||||
password: str = Field(min_length=12, max_length=128)
|
password: str = Field(min_length=12, max_length=128)
|
||||||
|
|
||||||
|
@field_validator("display_name")
|
||||||
|
@classmethod
|
||||||
|
def _display_name_not_blank(cls, v: str) -> str:
|
||||||
|
return _not_blank(v)
|
||||||
|
|
||||||
|
@field_validator("password")
|
||||||
|
@classmethod
|
||||||
|
def _password_not_blank(cls, v: str) -> str:
|
||||||
|
return _not_blank(v)
|
||||||
|
|
||||||
|
|
||||||
class User(BaseModel):
|
class User(BaseModel):
|
||||||
model_config = ConfigDict(extra="forbid")
|
model_config = ConfigDict(extra="forbid")
|
||||||
@@ -42,6 +59,11 @@ class CreateChat(BaseModel):
|
|||||||
title: str = Field(min_length=1, max_length=100)
|
title: str = Field(min_length=1, max_length=100)
|
||||||
member_ids: List[UUID] = Field(min_length=1, max_length=100)
|
member_ids: List[UUID] = Field(min_length=1, max_length=100)
|
||||||
|
|
||||||
|
@field_validator("title")
|
||||||
|
@classmethod
|
||||||
|
def _title_not_blank(cls, v: str) -> str:
|
||||||
|
return _not_blank(v)
|
||||||
|
|
||||||
|
|
||||||
class Chat(BaseModel):
|
class Chat(BaseModel):
|
||||||
model_config = ConfigDict(extra="forbid")
|
model_config = ConfigDict(extra="forbid")
|
||||||
@@ -56,8 +78,18 @@ class Chat(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class CreateMessage(BaseModel):
|
class CreateMessage(BaseModel):
|
||||||
|
"""Контракт: отсутствующий attachment_ids семантически равен [].
|
||||||
|
Поэтому поле опциональное с default_factory=list — модель принимает
|
||||||
|
оба варианта, а _canonical_body_hash видит одинаковый dict.
|
||||||
|
"""
|
||||||
model_config = ConfigDict(extra="forbid")
|
model_config = ConfigDict(extra="forbid")
|
||||||
text: str = Field(min_length=1, max_length=4000)
|
text: str = Field(min_length=1, max_length=4000)
|
||||||
|
attachment_ids: List[UUID] = Field(default_factory=list)
|
||||||
|
|
||||||
|
@field_validator("text")
|
||||||
|
@classmethod
|
||||||
|
def _text_not_blank(cls, v: str) -> str:
|
||||||
|
return _not_blank(v)
|
||||||
|
|
||||||
|
|
||||||
class Message(BaseModel):
|
class Message(BaseModel):
|
||||||
|
|||||||
Reference in New Issue
Block a user