"""Stripe-style idempotency: the first result for a key is replayed on retries; reusing a key with different arguments is an error.""" from __future__ import annotations import enum import uuid from dataclasses import dataclass from typing import Any from sqlalchemy import select, update from sqlalchemy.dialects.postgresql import insert from sqlalchemy.ext.asyncio import AsyncSession from core.gateway.models import IdempotencyKey class ClaimStatus(enum.StrEnum): CLAIMED = "claimed" # first use: caller must execute and then complete() REPLAY = "replay" # completed before with the same call: return stored result CONFLICT = "conflict" # same key, different call IN_PROGRESS = "in_progress" # another worker holds it @dataclass(frozen=True) class Claim: status: ClaimStatus result: dict[str, Any] | None = None async def claim( session: AsyncSession, tenant_id: uuid.UUID, key: uuid.UUID, call_hash: str ) -> Claim: inserted = ( await session.execute( insert(IdempotencyKey) .values(tenant_id=tenant_id, key=key, call_hash=call_hash, status="in_progress") .on_conflict_do_nothing(index_elements=[IdempotencyKey.key]) .returning(IdempotencyKey.key) ) ).scalar_one_or_none() if inserted is not None: return Claim(ClaimStatus.CLAIMED) row = ( await session.execute(select(IdempotencyKey).where(IdempotencyKey.key == key)) ).scalar_one_or_none() if row is None or row.call_hash != call_hash: # row is None: key exists under another tenant (invisible through RLS) return Claim(ClaimStatus.CONFLICT) if row.status == "completed": return Claim(ClaimStatus.REPLAY, row.result) return Claim(ClaimStatus.IN_PROGRESS) async def complete(session: AsyncSession, key: uuid.UUID, result: dict[str, Any]) -> None: await session.execute( update(IdempotencyKey) .where(IdempotencyKey.key == key) .values(status="completed", result=result) )