File size: 2,134 Bytes
2756f0f
 
 
 
 
 
 
 
ae2c68f
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae2c68f
 
 
 
 
2756f0f
 
 
 
 
 
 
 
 
 
ae2c68f
2756f0f
 
 
ae2c68f
2756f0f
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""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=<path id> 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)