From 9a4439af48ff594489a3a52a739c8f76c70d4e18 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 18 Aug 2026 14:40:55 +0200 Subject: [PATCH] feat(alerts): daily Telegram ops digest One message per day at 06:00 UTC with signups, processing activity (users, jobs, minutes, refunds), clips created, new subscriptions and notable Stripe events, all computed from the DB at send time so redeploys lose nothing. Replaces the per-event free-tier pings removed in the previous commit. --- cloud/__init__.py | 3 +- cloud/digest.py | 123 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 125 insertions(+), 1 deletion(-) create mode 100644 cloud/digest.py diff --git a/cloud/__init__.py b/cloud/__init__.py index 099d05f..e59665a 100644 --- a/cloud/__init__.py +++ b/cloud/__init__.py @@ -44,9 +44,10 @@ async def setup_async(app, keep_reservation_ids=None): ``keep_reservation_ids`` belong to jobs being resumed after a restart and must not be refunded (see app._resume_interrupted_jobs). """ - from . import database, metering, videos + from . import database, digest, metering, videos await database.init_engine() await metering.release_orphaned_reservations(keep_ids=keep_reservation_ids) metering.start_sweeper() videos.start_sweeper() + digest.start_digest() print("☁️ Cloud billing mode ENABLED (DB ready, metering active).") diff --git a/cloud/digest.py b/cloud/digest.py new file mode 100644 index 0000000..2732cf5 --- /dev/null +++ b/cloud/digest.py @@ -0,0 +1,123 @@ +"""Daily ops digest to Telegram: one message per day with the pulse of the +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. +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. +""" +import asyncio +from datetime import datetime, timedelta, timezone + +from sqlalchemy import distinct, func, select + +from . import database +from .models import StripeEvent, Subscription, 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. +_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", +} + + +async def _window_stats(start, end): + async with database.session() as s: + signups = (await s.execute( + select(func.count(User.id)) + .where(User.created_at >= start, User.created_at < end) + )).scalar_one() + + jobs, processors, refunded, minutes = (await s.execute( + select( + func.count(UsageLedger.id), + func.count(distinct(UsageLedger.user_id)), + func.count(UsageLedger.id).filter(UsageLedger.status == "released"), + func.coalesce(func.sum(UsageLedger.minutes), 0), + ).where(UsageLedger.job_type == "process", + UsageLedger.created_at >= start, + UsageLedger.created_at < end) + )).one() + + clips = (await s.execute( + select(func.count(UserVideo.id)) + .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() + + stripe_rows = (await s.execute( + select(StripeEvent.type, func.count(StripeEvent.id)) + .where(StripeEvent.created >= start, StripeEvent.created < end) + .group_by(StripeEvent.type) + )).all() + + return { + "signups": signups, + "jobs": jobs, + "processors": processors, + "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}, + } + + +def _format(stats) -> str: + lines = [ + "📊 Daily digest (last 24h)", + f"Signups: {stats['signups']}", + f"Processing: {stats['processors']} user(s), {stats['jobs']} job(s), " + f"{stats['minutes']:.0f} min" + + (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: + lines.append("(quiet day)") + return "\n".join(lines) + + +async def send_daily_digest(): + from .alerts import send_telegram + end = datetime.now(timezone.utc) + start = end - timedelta(hours=24) + stats = await _window_stats(start, end) + await send_telegram(_format(stats)) + print("📊 Daily digest sent.") + + +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()) + await send_daily_digest() + except asyncio.CancelledError: + break + except Exception as e: + print(f"⚠️ Daily digest error: {e}") + await asyncio.sleep(300) # never busy-loop on a persistent failure + + +def start_digest(): + asyncio.create_task(_digest_loop())