Files
aza/AzA march 2026 - Kopie (6)/aza_stripe_idempotency.py
2026-04-16 13:32:32 +02:00

47 lines
1.2 KiB
Python

import sqlite3
import time
def ensure_stripe_events_table(conn: sqlite3.Connection) -> None:
"""
Creates the stripe_events table if it doesn't exist.
Used for idempotency of webhook deliveries.
"""
conn.execute(
"""
CREATE TABLE IF NOT EXISTS stripe_events (
event_id TEXT PRIMARY KEY,
received_at INTEGER NOT NULL
);
"""
)
conn.commit()
def try_claim_event(conn: sqlite3.Connection, event_id: str) -> bool:
"""
Returns True if we successfully claimed (inserted) the event_id,
False if it already exists (duplicate delivery).
"""
ensure_stripe_events_table(conn)
try:
conn.execute(
"INSERT INTO stripe_events (event_id, received_at) VALUES (?, ?);",
(event_id, int(time.time())),
)
conn.commit()
return True
except sqlite3.IntegrityError:
# Duplicate delivery
return False
def prune_old_events(conn: sqlite3.Connection, max_age_days: int = 30) -> None:
"""
Optional cleanup to avoid unbounded growth.
"""
cutoff = int(time.time()) - max_age_days * 24 * 60 * 60
conn.execute("DELETE FROM stripe_events WHERE received_at < ?;", (cutoff,))
conn.commit()