fix(digest): harden daily digest after code review

- Retry the 06:00 send in place (6x / 5 min) instead of silently skipping
  the day when a DB blip or Telegram outage lands on the send minute; the
  digest path now uses send_telegram(raise_errors=True) so failures are
  visible to that retry, and send_telegram checks the HTTP status.
- Filter Stripe lines by processed_at, not the Stripe-side created stamp
  that survives delivery retries and could land inside an already-digested
  window.
- Drop invoice.payment_succeeded (near-alias of invoice.paid; counting both
  double-reports payments) and the Subscription.created_at count (upserts
  hide re-subscribing churned users) — customer.subscription.created events
  cover new subs correctly.
- Keep a strong reference to the digest task so it can't be GC'd mid-sleep.
This commit is contained in:
juancarlos.cavero 2026-08-18 14:53:31 +02:00
parent 9a4439af48
commit 5b4f5b2891
2 changed files with 52 additions and 32 deletions

View file

@ -76,10 +76,12 @@ def _cooldown_ok(kind: str) -> bool:
TELEGRAM_PREFIX = "OPENSHORTS ✂️ - "
async def send_telegram(text: str):
async def send_telegram(text: str, *, raise_errors: bool = False):
"""Push a plain-text message to the admin's Telegram chat. No-op if unset.
Best-effort: never raises — an alert failing must not break a webhook or job.
Best-effort by default: never raises — an alert failing must not break a
webhook or job. ``raise_errors=True`` is for callers with their own retry
(the daily digest), where swallowing the failure means losing the message.
"""
if not settings.telegram_configured:
return
@ -90,8 +92,11 @@ async def send_telegram(text: str):
"text": TELEGRAM_PREFIX + text,
"disable_web_page_preview": True}
async with httpx.AsyncClient(timeout=10) as client:
await client.post(url, json=payload)
resp = await client.post(url, json=payload)
resp.raise_for_status()
except Exception as e:
if raise_errors:
raise
print(f"⚠️ Telegram alert failed: {e}")

View file

@ -2,10 +2,13 @@
product (signups, processing activity, clips, revenue events), replacing
per-event pings that turned into spam as free usage grew.
Everything is computed from the DB at send time, so redeploys lose nothing.
Everything is computed from the DB at send time, so redeploys lose no data.
The send is scheduled by wall clock (sleep until the next 06:00 UTC): a deploy
in the middle of the day just re-arms the same next send, so there is no
duplicate-send window to guard with state.
duplicate-send window to guard with state. The one accepted loss: a deploy
that lands exactly across the send minute skips that day's message (the data
still shows up in DB queries; only the ping is lost). Transient failures at
send time are retried in-process rather than skipped.
"""
import asyncio
from datetime import datetime, timedelta, timezone
@ -13,15 +16,16 @@ from datetime import datetime, timedelta, timezone
from sqlalchemy import distinct, func, select
from . import database
from .models import StripeEvent, Subscription, UsageLedger, User, UserVideo
from .models import StripeEvent, UsageLedger, User, UserVideo
_SEND_HOUR_UTC = 6 # 08:00 Madrid in summer — with the first coffee
# Stripe event types worth a line in the digest, with a human label.
# invoice.payment_succeeded is deliberately absent: it is a near-alias of
# invoice.paid and counting both would double-report every payment.
_STRIPE_LABELS = {
"checkout.session.completed": "checkout completed",
"invoice.paid": "payment",
"invoice.payment_succeeded": "payment",
"invoice.payment_failed": "PAYMENT FAILED",
"customer.subscription.created": "new subscription",
"customer.subscription.deleted": "subscription ended",
@ -51,15 +55,17 @@ async def _window_stats(start, end):
.where(UserVideo.created_at >= start, UserVideo.created_at < end)
)).scalar_one()
new_subs = (await s.execute(
select(func.count(Subscription.id))
.where(Subscription.created_at >= start,
Subscription.created_at < end)
)).scalar_one()
# processed_at (server-side), NOT StripeEvent.created: Stripe keeps the
# original event timestamp across delivery retries, so an event
# delivered late after an outage would land inside an already-digested
# window and never be reported. New subscriptions are counted from the
# customer.subscription.created event rather than Subscription rows:
# the DB upserts re-subscribing churned users into their existing row,
# whose created_at never refreshes.
stripe_rows = (await s.execute(
select(StripeEvent.type, func.count(StripeEvent.id))
.where(StripeEvent.created >= start, StripeEvent.created < end)
.where(StripeEvent.processed_at >= start,
StripeEvent.processed_at < end)
.group_by(StripeEvent.type)
)).all()
@ -70,7 +76,6 @@ async def _window_stats(start, end):
"refunded": refunded,
"minutes": float(minutes or 0),
"clips": clips,
"new_subs": new_subs,
"stripe": {t: n for t, n in stripe_rows if t in _STRIPE_LABELS},
}
@ -84,8 +89,6 @@ def _format(stats) -> str:
+ (f" — {stats['refunded']} refunded" if stats['refunded'] else ""),
f"Clips created: {stats['clips']}",
]
if stats["new_subs"]:
lines.append(f"New subscriptions: {stats['new_subs']}")
for etype, n in sorted(stats["stripe"].items()):
lines.append(f"Stripe: {n}× {_STRIPE_LABELS[etype]}")
if stats["signups"] == 0 and stats["jobs"] == 0 and stats["clips"] == 0:
@ -98,26 +101,38 @@ async def send_daily_digest():
end = datetime.now(timezone.utc)
start = end - timedelta(hours=24)
stats = await _window_stats(start, end)
await send_telegram(_format(stats))
await send_telegram(_format(stats), raise_errors=True)
print("📊 Daily digest sent.")
_SEND_RETRIES = 6 # transient DB/Telegram trouble at send time...
_RETRY_DELAY_SECONDS = 300 # ...retries for up to 30 min instead of skipping
async def _digest_loop():
while True:
try:
now = datetime.now(timezone.utc)
target = now.replace(hour=_SEND_HOUR_UTC, minute=0, second=0,
microsecond=0)
if target <= now:
target += timedelta(days=1)
await asyncio.sleep((target - now).total_seconds())
# Retry in place rather than falling through to tomorrow's target —
# otherwise one DB blip at 06:00 silently swallows the whole day.
for attempt in range(_SEND_RETRIES):
try:
await send_daily_digest()
except asyncio.CancelledError:
break
except asyncio.CancelledError:
return
except Exception as e:
print(f"⚠️ Daily digest error: {e}")
await asyncio.sleep(300) # never busy-loop on a persistent failure
print(f"⚠️ Daily digest error (attempt {attempt + 1}): {e}")
await asyncio.sleep(_RETRY_DELAY_SECONDS)
_task = None # keep a strong reference: the loop only holds weak task refs
def start_digest():
asyncio.create_task(_digest_loop())
global _task
_task = asyncio.create_task(_digest_loop())