forked from mtusi2026/mtusi2026lab3
feat: implement instance id and idempotency key handling
This commit is contained in:
+48
-2
@@ -1,9 +1,15 @@
|
||||
import os
|
||||
import uuid
|
||||
import socket
|
||||
from contextvars import ContextVar
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
INSTANCE_ID = os.environ.get("HOSTNAME", f"api-{socket.gethostname()}")
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
@@ -46,7 +52,7 @@ _HTTP_CODES = {
|
||||
|
||||
|
||||
def err_json(status: int, code: str, message: str) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
resp = JSONResponse(
|
||||
status_code=status,
|
||||
content={
|
||||
"error": {
|
||||
@@ -56,6 +62,8 @@ def err_json(status: int, code: str, message: str) -> JSONResponse:
|
||||
}
|
||||
},
|
||||
)
|
||||
resp.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return resp
|
||||
|
||||
|
||||
class RequestIdMiddleware(BaseHTTPMiddleware):
|
||||
@@ -64,6 +72,7 @@ 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
|
||||
|
||||
|
||||
@@ -249,14 +258,51 @@ async def get_chat(
|
||||
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")
|
||||
|
||||
req_hash = hashlib.sha256(body.model_dump_json().encode("utf-8")).hexdigest()
|
||||
|
||||
# 1. Проверяем, есть ли уже такой ключ
|
||||
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)
|
||||
return JSONResponse(status_code=201, content=json.loads(record.response_body))
|
||||
|
||||
# 2. Создаём сообщение
|
||||
msg = await messages_repo.create_and_invalidate(db, chat_id, user.id, body.text)
|
||||
return _msg_json(msg)
|
||||
resp_body = json.dumps(_msg_json(msg))
|
||||
|
||||
# 3. Сохраняем ключ
|
||||
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:
|
||||
return JSONResponse(status_code=201, content=json.loads(record.response_body))
|
||||
raise HTTPException(409, "Idempotency key conflict")
|
||||
|
||||
return JSONResponse(status_code=201, content=json.loads(resp_body))
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
|
||||
Reference in New Issue
Block a user