Spaces:
Running

File size: 2,099 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
57
58
59
60
61
"""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)
    )