update
This commit is contained in:
46
APP/backup 24.2.26/aza_stripe_idempotency.py
Normal file
46
APP/backup 24.2.26/aza_stripe_idempotency.py
Normal file
@@ -0,0 +1,46 @@
|
||||
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()
|
||||
Reference in New Issue
Block a user