forked from mtusi2026/mtusi2026lab6
66 lines
2.5 KiB
Python
66 lines
2.5 KiB
Python
"""Логика идемпотентности для POST запросов."""
|
|
import hashlib
|
|
import json
|
|
import re
|
|
|
|
from .errors import ApiError, bad_request
|
|
|
|
# Контракт: ASCII [A-Za-z0-9._:-]{1,128}
|
|
_IDEM_KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}")
|
|
|
|
|
|
def get_request_hash(data: dict) -> str:
|
|
"""Хеш тела, независимый от порядка ключей.
|
|
|
|
Отсутствующий attachment_ids семантически равен [] — нормализуем,
|
|
иначе {"text":"x"} и {"text":"x","attachment_ids":[]} дают разные хеши.
|
|
"""
|
|
normalized = dict(data)
|
|
normalized.setdefault("attachment_ids", [])
|
|
return hashlib.sha256(json.dumps(normalized, sort_keys=True).encode("utf-8")).hexdigest()
|
|
|
|
|
|
def check_and_lock(conn, user_id: str, method: str, path: str, key: str, req_hash: str):
|
|
if not key:
|
|
raise bad_request("Missing Idempotency-Key")
|
|
if not _IDEM_KEY_RE.fullmatch(key):
|
|
raise bad_request("Invalid Idempotency-Key format")
|
|
|
|
lock_id = f"{user_id}:{method}:{path}:{key}"
|
|
conn.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", (lock_id,))
|
|
|
|
row = conn.execute("""
|
|
SELECT request_hash, status_code, response_body
|
|
FROM idempotency_keys
|
|
WHERE user_id = %s AND method = %s AND path = %s AND key = %s
|
|
""", (user_id, method, path, key)).fetchone()
|
|
|
|
if row:
|
|
if row["request_hash"] != req_hash:
|
|
raise ApiError(409, "conflict", "Idempotency-Key conflict: body differs")
|
|
if row["status_code"] is not None and row["response_body"] is not None:
|
|
return False, json.loads(row["response_body"])
|
|
return True, None
|
|
|
|
return True, None
|
|
|
|
|
|
def save_result(conn, user_id, method, path, key, req_hash, status_code, response_body):
|
|
conn.execute("""
|
|
INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, status_code, response_body)
|
|
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
|
ON CONFLICT (user_id, method, path, key) DO UPDATE
|
|
SET status_code = EXCLUDED.status_code, response_body = EXCLUDED.response_body
|
|
""", (user_id, method, path, key, req_hash, status_code, json.dumps(response_body)))
|
|
|
|
|
|
def cleanup(conn, ttl_seconds: int):
|
|
conn.execute("""
|
|
DELETE FROM idempotency_keys
|
|
WHERE (user_id, method, path, key) IN (
|
|
SELECT user_id, method, path, key
|
|
FROM idempotency_keys
|
|
WHERE created_at < now() - make_interval(secs => %s)
|
|
LIMIT 100
|
|
)
|
|
""", (ttl_seconds,)) |