caelum0x d56639a594
Some checks failed
build-images / web (push) Has been cancelled
vision2026-ci / Python SDK resource tests (push) Has been cancelled
build-images / api (push) Has been cancelled
build-images / worker-gpu (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Has been cancelled
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Has been cancelled
codeql / Analyze (javascript-typescript) (push) Has been cancelled
codeql / Analyze (python) (push) Has been cancelled
perf / API hot-path micro-smoke (budgeted) (push) Has been cancelled
perf / Desktop engine crates (release build check) (push) Has been cancelled
vision2026-ci / API phase modules (ruff + pytest) (push) Has been cancelled
vision2026-ci / Alembic upgrade + drift check (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Has been cancelled
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

66 lines
3.0 KiB
Python

"""Megaphone's publish digest (2026-11-08 fix for per-run email spam).
Before this, every ``python -m app.domains.megaphone run`` invocation mailed
its own "Megaphone week N: X videos" summary. The real weekly cron
(``run-weekly.sh``) only calls this once a week, so that was fine there — but
manual single-product dogfooding runs (``--only alsat``, then ``--only
huddle``, then ``--only caldesk``, each a separate CLI invocation on the same
day) each sent their own mail, so the owner got 3 near-identical "Megaphone
week 2026w45" emails in one day instead of one.
Fix: gate the actual mail send to at most once per ~36h (same TTL and Redis-
backed dedup store already used by the funnel's own daily digest, see
``app/services/funnel/weekly.py::run_daily_digest``) and compute "what's new"
not from this one run's in-memory list but from the durable R2 manifest
(``upload_date`` per video — every product's publish already writes there).
That means:
* A run whose claim succeeds reports every video published since the last
successful digest, however many separate CLI invocations that spanned.
* A run whose claim is denied (something already mailed today) sends nothing
— but nothing is lost: the video it just published is already durable in
the manifest and will show up in whichever later run's digest succeeds.
"""
from __future__ import annotations
import json
from datetime import datetime, timedelta, timezone
from typing import Any, Mapping
from loguru import logger
STATE_KEY = "megaphone/digest-state.json"
#: Mirrors funnel's `DIGEST_TTL_S` (36h, i.e. "once per UTC day" with a buffer
#: for late/retried runs) — see app/services/funnel/weekly.py.
DIGEST_TTL_S = 36 * 60 * 60
#: First-ever run (no saved state yet): look back far enough to not miss
#: anything recent, but not the whole history.
LOOKBACK_DAYS = 7
def dedup_store() -> Any:
from app.domains.observability.render_metrics import _dedup_store
return _dedup_store()
def load_last_sent(publisher: Any) -> datetime:
try:
obj = publisher._client._s3.get_object(Bucket=publisher._client._bucket, Key=STATE_KEY)
raw = json.loads(obj["Body"].read().decode("utf-8"))
return datetime.fromisoformat(str(raw["last_sent_at"]).replace("Z", "+00:00"))
except Exception as exc: # noqa: BLE001 - first run, or unreadable: look back LOOKBACK_DAYS
logger.info(f"megaphone: no readable digest state yet ({type(exc).__name__})")
return datetime.now(timezone.utc) - timedelta(days=LOOKBACK_DAYS)
def save_last_sent(publisher: Any, now: datetime) -> None:
publisher.put_json(STATE_KEY, {"last_sent_at": now.astimezone(timezone.utc).isoformat()})
def videos_since(manifest: Mapping[str, Any], since: datetime) -> list[dict[str, Any]]:
"""Manifest entries published strictly after ``since`` (newest first, as stored)."""
since_iso = since.astimezone(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
return [v for v in (manifest.get("videos") or []) if str(v.get("upload_date") or "") > since_iso]