Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
130 lines
6.1 KiB
Python
130 lines
6.1 KiB
Python
"""Persistent, per-user Telegram reminders shared by bot and Mini App."""
|
|
from contextlib import closing
|
|
import math
|
|
import sqlite3
|
|
import time
|
|
from typing import Any
|
|
import uuid
|
|
|
|
|
|
MAX_PENDING = 100
|
|
MAX_ATTEMPTS = 5
|
|
PUBLIC_FIELDS = ("id", "text", "due_at", "status", "created_at", "sent_at", "last_error")
|
|
|
|
|
|
def _connect(db_path):
|
|
con = sqlite3.connect(db_path, timeout=10)
|
|
con.row_factory = sqlite3.Row
|
|
return con
|
|
|
|
|
|
def init_db(db_path):
|
|
with closing(_connect(db_path)) as con:
|
|
con.execute("""CREATE TABLE IF NOT EXISTS wa_reminders (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
uid INTEGER NOT NULL,
|
|
text TEXT NOT NULL,
|
|
due_at INTEGER NOT NULL,
|
|
status TEXT NOT NULL DEFAULT 'pending',
|
|
created_at INTEGER NOT NULL,
|
|
sent_at INTEGER,
|
|
last_error TEXT,
|
|
attempts INTEGER NOT NULL DEFAULT 0,
|
|
lease_until INTEGER NOT NULL DEFAULT 0,
|
|
claim_token TEXT
|
|
)""")
|
|
con.execute("CREATE INDEX IF NOT EXISTS wa_reminders_due ON wa_reminders(status, due_at)")
|
|
con.execute("CREATE INDEX IF NOT EXISTS wa_reminders_owner ON wa_reminders(uid, created_at)")
|
|
con.commit()
|
|
|
|
|
|
def _public(row) -> dict[str, Any]:
|
|
return {key: row[key] for key in PUBLIC_FIELDS}
|
|
|
|
|
|
def create_reminder(db_path, uid, text, due_at, now=None):
|
|
now = int(time.time() if now is None else now)
|
|
if not isinstance(uid, int) or isinstance(uid, bool) or uid <= 0:
|
|
raise ValueError("invalid_user")
|
|
if not isinstance(text, str) or not text.strip() or len(text.strip()) > 1000:
|
|
raise ValueError("invalid_text")
|
|
if isinstance(due_at, bool) or not isinstance(due_at, (int, float)) or not math.isfinite(due_at):
|
|
raise ValueError("invalid_due")
|
|
due_at = int(due_at)
|
|
if not now + 30 <= due_at <= now + 366 * 86400:
|
|
raise ValueError("invalid_due")
|
|
with closing(_connect(db_path)) as con:
|
|
con.execute("BEGIN IMMEDIATE")
|
|
count = con.execute("SELECT COUNT(*) FROM wa_reminders WHERE uid=? AND status IN ('pending','sending')", (uid,)).fetchone()[0]
|
|
if count >= MAX_PENDING:
|
|
raise ValueError("too_many")
|
|
cur = con.execute("INSERT INTO wa_reminders(uid,text,due_at,created_at) VALUES (?,?,?,?)",
|
|
(uid, text.strip(), due_at, now))
|
|
row = con.execute("SELECT * FROM wa_reminders WHERE id=?", (cur.lastrowid,)).fetchone()
|
|
con.commit()
|
|
return _public(row)
|
|
|
|
|
|
def list_reminders(db_path, uid, limit=50):
|
|
limit = max(1, min(100, int(limit)))
|
|
with closing(_connect(db_path)) as con:
|
|
rows = con.execute("SELECT * FROM wa_reminders WHERE uid=? ORDER BY "
|
|
"CASE WHEN status IN ('pending','sending') THEN 0 ELSE 1 END, "
|
|
"CASE WHEN status IN ('pending','sending') THEN due_at ELSE -created_at END, id DESC LIMIT ?",
|
|
(uid, limit)).fetchall()
|
|
return [_public(row) for row in rows]
|
|
|
|
|
|
def cancel_reminder(db_path, uid, reminder_id):
|
|
if not isinstance(reminder_id, int) or isinstance(reminder_id, bool) or reminder_id <= 0:
|
|
raise ValueError("invalid_id")
|
|
with closing(_connect(db_path)) as con:
|
|
changed = con.execute("UPDATE wa_reminders SET status='cancelled' WHERE id=? AND uid=? AND status='pending'",
|
|
(reminder_id, uid)).rowcount
|
|
con.commit()
|
|
return changed == 1
|
|
|
|
|
|
def claim_due(db_path, now=None, limit=20, lease_seconds=120):
|
|
"""Claim due work atomically; expired leases recover after process restarts."""
|
|
now = int(time.time() if now is None else now)
|
|
limit = max(1, min(20, int(limit)))
|
|
with closing(_connect(db_path)) as con:
|
|
con.execute("BEGIN IMMEDIATE")
|
|
con.execute("UPDATE wa_reminders SET status=CASE WHEN attempts>=? THEN 'failed' ELSE 'pending' END, "
|
|
"claim_token=NULL, lease_until=0, last_error='delivery_interrupted' "
|
|
"WHERE status='sending' AND lease_until<=?", (MAX_ATTEMPTS, now))
|
|
rows = con.execute("SELECT * FROM wa_reminders WHERE status='pending' AND due_at<=? "
|
|
"AND attempts<? ORDER BY due_at,id LIMIT ?", (now, MAX_ATTEMPTS, limit)).fetchall()
|
|
result = []
|
|
for row in rows:
|
|
token = uuid.uuid4().hex
|
|
con.execute("UPDATE wa_reminders SET status='sending', attempts=attempts+1, lease_until=?, claim_token=? WHERE id=?",
|
|
(now + max(30, int(lease_seconds)), token, row["id"]))
|
|
result.append({**dict(row), "status": "sending", "attempts": row["attempts"] + 1, "claim_token": token})
|
|
con.commit()
|
|
return result
|
|
|
|
|
|
def finish_delivery(db_path, reminder_id, claim_token, *, error=None, permanent=False, retry_after=None, now=None):
|
|
"""Only the current delivery lease may complete or reschedule a reminder."""
|
|
now = int(time.time() if now is None else now)
|
|
with closing(_connect(db_path)) as con:
|
|
con.execute("BEGIN IMMEDIATE")
|
|
row = con.execute("SELECT attempts FROM wa_reminders WHERE id=? AND status='sending' AND claim_token=?",
|
|
(reminder_id, claim_token)).fetchone()
|
|
if row is None:
|
|
return False
|
|
if error is None:
|
|
con.execute("UPDATE wa_reminders SET status='sent',sent_at=?,last_error=NULL,lease_until=0,claim_token=NULL WHERE id=?",
|
|
(now, reminder_id))
|
|
else:
|
|
failed = permanent or row["attempts"] >= MAX_ATTEMPTS
|
|
delay = min(3600, max(15, int(retry_after or (30 * 2 ** row["attempts"]))))
|
|
# Store error classes/codes, never exception bodies (which can contain credentials).
|
|
code = ''.join(c for c in str(error) if c.isalnum() or c == '_')[:80] or 'delivery_failed'
|
|
con.execute("UPDATE wa_reminders SET status=?,due_at=?,last_error=?,lease_until=0,claim_token=NULL WHERE id=?",
|
|
('failed' if failed else 'pending', now + delay, code, reminder_id))
|
|
con.commit()
|
|
return True
|