Files
mtusi2026lab3/src/idempotency.py
T
2026-11-12 20:23:11 +03:00

113 lines
2.4 KiB
Python

import json
from uuid import UUID
from src import config
async def get_idempotency_key(
conn,
user_id: UUID,
method: str,
path: str,
key: str,
) -> dict | None:
"""
Вызывается внутри транзакции.
Advisory lock не позволяет двум API-репликам одновременно
создать два сообщения с одним Idempotency-Key.
"""
lock_key = f"{user_id}:{method}:{path}:{key}"
await conn.execute(
"""
SELECT pg_advisory_xact_lock(hashtextextended($1, 0))
""",
lock_key,
)
await conn.execute(
"""
DELETE FROM idempotency_keys
WHERE user_id = $1
AND method = $2
AND path = $3
AND key = $4
AND created_at <= NOW() - ($5 || ' seconds')::interval
""",
user_id,
method,
path,
key,
str(config.IDEMPOTENCY_TTL_SECONDS),
)
row = await conn.fetchrow(
"""
SELECT request_hash, response_status, response_body, created_at
FROM idempotency_keys
WHERE user_id = $1
AND method = $2
AND path = $3
AND key = $4
""",
user_id,
method,
path,
key,
)
if row is None:
return None
response_body = row["response_body"]
if isinstance(response_body, str):
response_body = json.loads(response_body)
return {
"request_hash": row["request_hash"],
"response_status": row["response_status"],
"response": response_body,
"created_at": row["created_at"],
}
async def set_idempotency_key(
conn,
user_id: UUID,
method: str,
path: str,
key: str,
request_hash: str,
response_status: int,
response: dict,
):
"""
Сохраняет результат запроса в той же транзакции,
что и само сообщение.
"""
await conn.execute(
"""
INSERT INTO idempotency_keys (
user_id,
method,
path,
key,
request_hash,
response_status,
response_body
)
VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb)
""",
user_id,
method,
path,
key,
request_hash,
response_status,
json.dumps(response, ensure_ascii=False),
)