"""Idempotency-Key support for retried writes (POST /sessions, POST /drill-logs). Usage in a controller: return await run_idempotent(db, account.id, idempotency_key, body, lambda: service.create(...), status_code=201) The first call runs the handler and stores its response; a retry with the same key and body replays it; the same key with a different body is a 409. Pass scope= when the route has a target id, so one key cannot replay across targets. """ import hashlib import json from collections.abc import Awaitable, Callable from uuid import UUID from fastapi.encoders import jsonable_encoder from fastapi.responses import JSONResponse from pydantic import BaseModel from sqlalchemy.ext.asyncio import AsyncSession from app.core.errors import Conflict from app.modules.idempotency.models import IdempotencyKey def _hash(body: BaseModel, scope: UUID | None) -> str: payload = body.model_dump(mode="json") if scope is not None: payload = {"target": str(scope), "body": payload} return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest() async def run_idempotent( db: AsyncSession, account_id: UUID, key: str | None, body: BaseModel, handler: Callable[[], Awaitable[BaseModel]], *, status_code: int, scope: UUID | None = None, ) -> JSONResponse: if not key: return JSONResponse(jsonable_encoder(await handler()), status_code=status_code) request_hash = _hash(body, scope) stored = await db.get(IdempotencyKey, (account_id, key)) if stored is not None: if stored.request_hash != request_hash: raise Conflict("This Idempotency-Key was used for a different request.", code="IDEMPOTENCY_KEY_REUSED") return JSONResponse(stored.response_body, status_code=stored.response_status) response_body = jsonable_encoder(await handler()) db.add(IdempotencyKey(account_id=account_id, key=key, request_hash=request_hash, response_status=status_code, response_body=response_body)) await db.flush() return JSONResponse(response_body, status_code=status_code)