:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(alerts): deliver platform alerts to subscribers by email (#114218)
Jimmy Zhu56ef64fba870
diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.pyindex e96ef8b59f8c..286e99879ba6 100644--- a/posthog/tasks/alerts/utils.py+++ b/posthog/tasks/alerts/utils.py@@ -17,7 +17,6 @@ from posthog.slo.context import get_current_slofrom posthog.slo.types import SloOperationfrom posthog.tasks.alerts.schedule_restriction import snap_candidate_utc_to_schedule_restriction-from products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.alerts.backend.facade.api import LLM_DETECTOR_UNAVAILABLE_ERROR_CODEfrom products.alerts.backend.facade.destinations import (ALERT_NOTIFICATION_FLUSH_TIMEOUT_SECONDS,@@ -27,7 +26,7 @@ from products.alerts.backend.facade.destinations import (produce_alert_internal_event,serialize_deliveries,)-from products.alerts.backend.facade.email import send_alert_email+from products.alerts.backend.facade.email import alert_email_recipients, send_alert_emailfrom products.alerts.backend.insight_alert_state_machine import (apply_invalid_configuration,apply_outcome,@@ -346,16 +345,7 @@ def next_scheduled_check_time(alert: AlertConfiguration) -> str | None:def get_alert_error_notification_recipients(alert: AlertConfiguration) -> list[tuple[int, str]]:- candidates = (- alert.team.all_users_with_access()- .filter(id__in=alert.subscribed_users.values_list("id", flat=True))- .only("id", "email")- )- return [- (user.id, user.email)- for user in candidates- if UserAccessControl(user, team=alert.team).check_access_level_for_object(alert.insight, "viewer")- ]+ return alert_email_recipients(team_id=alert.team_id, alert_id=alert.id)def _inconclusive_is_suppressed(verdict: str | None, inconclusive_action: str | None) -> bool:diff --git a/posthog/templates/email/alert_platform_notification.html b/posthog/templates/email/alert_platform_notification.htmlnew file mode 100644index 000000000000..84411a5f64a3--- /dev/null+++ b/posthog/templates/email/alert_platform_notification.html@@ -0,0 +1,11 @@+{% extends "email/base.html" %}+{% block heading %}{{ headline }}{% endblock %} {% block section %}+{% if details %}+ <ul>+ {% for detail in details %}+ <li><strong>{{ detail.label }}:</strong> {{ detail.value }}</li>+ {% endfor %}+ </ul>+{% endif %}+<p>You're getting this email because you're subscribed to this alert in PostHog.</p>+{% endblock %}diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.pyindex 3df23dd626ec..282ce4cec33b 100644--- a/posthog/temporal/tests/test_alerts_activities.py+++ b/posthog/temporal/tests/test_alerts_activities.py@@ -1720,7 +1720,7 @@ class TestNotifyAlert:async def test_error_notification_excludes_subscriber_without_insight_access(self, alert_with_user) -> None:with patch(- "posthog.tasks.alerts.utils.UserAccessControl.check_access_level_for_object",+ "products.alerts.backend.logic.alert_email.UserAccessControl.check_access_level_for_object",return_value=False,):recipients = await sync_to_async(get_alert_error_notification_recipients)(alert_with_user)diff --git a/products/alerts/backend/apps.py b/products/alerts/backend/apps.pyindex 96ec9f7bb15f..4f41b4020cc5 100644--- a/products/alerts/backend/apps.py+++ b/products/alerts/backend/apps.py@@ -15,7 +15,7 @@ class AlertsConfig(AppConfig):from products.alerts.backend import activity_logging # noqa: F401, PLC0415# The platform cannot import this product, so it reaches this product's destinations here.- from products.alerts.backend.facade.destinations import list_alert_destination_groups # noqa: PLC0415+ from products.alerts.backend.facade.destinations import list_delivery_destination_groups # noqa: PLC0415from products.alerts_platform.backend.facade.delivery import register_destination_resolver # noqa: PLC0415- register_destination_resolver(list_alert_destination_groups)+ register_destination_resolver(list_delivery_destination_groups)diff --git a/products/alerts/backend/facade/destinations.py b/products/alerts/backend/facade/destinations.pyindex 8e3b6b6da992..7ccd84f8c6bd 100644--- a/products/alerts/backend/facade/destinations.py+++ b/products/alerts/backend/facade/destinations.py@@ -26,7 +26,7 @@ from products.alerts_platform.backend.facade.contracts import (OwnedAlertDestination,)-from ..logic import destination_configs, destinations, insight_alert_destinations+from ..logic import alert_email, destination_configs, destinations, insight_alert_destinationsALERT_NOTIFICATION_FLUSH_TIMEOUT_SECONDS: Final = 10.0@@ -209,3 +209,12 @@ def alert_internal_event_delivered(return destinations.alert_internal_event_delivered(produce_result, team_id=team_id, alert_id=alert_id, event_name=event_name)+++def list_delivery_destination_groups(+ *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]+) -> list[AlertDestinationGroup]:+ """Everything the shared platform delivers one alert's events to, including subscriber email."""+ return alert_email.list_delivery_destination_groups(+ team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids+ )diff --git a/products/alerts/backend/facade/email.py b/products/alerts/backend/facade/email.pyindex fac5c65b3378..83b3d0a306a1 100644--- a/products/alerts/backend/facade/email.py+++ b/products/alerts/backend/facade/email.py@@ -3,9 +3,12 @@from __future__ import annotationsfrom collections.abc import Collection+from uuid import UUIDfrom posthog.email import EmailMessage+from products.alerts.backend.logic import alert_email+def send_alert_email(*,@@ -25,3 +28,8 @@ def send_alert_email(for recipient in recipients:message.add_recipient(email=recipient)message.send()+++def alert_email_recipients(*, team_id: int, alert_id: UUID) -> list[tuple[int, str]]:+ """Subscribed users who can still view the project and the alert's insight, as (id, email)."""+ return alert_email.alert_email_recipients(team_id=team_id, alert_id=alert_id)diff --git a/products/alerts/backend/logic/alert_email.py b/products/alerts/backend/logic/alert_email.pynew file mode 100644index 000000000000..af2f9f7cf40a--- /dev/null+++ b/products/alerts/backend/logic/alert_email.py@@ -0,0 +1,75 @@+"""Who an insight alert emails, for the production check and for the shared platform.++An insight alert emails its subscribed users besides any HogFunction destinations. Both senders+read recipients here, so a user who loses access to the insight stops receiving either.+"""++from __future__ import annotations++from collections.abc import Collection+from typing import Final+from uuid import UUID++from posthog.cdp.internal_events import LEGACY_INSIGHT_ALERT_EVENT++from products.access_control.backend.facade.user_access_control import UserAccessControl+from products.alerts.backend.logic.destinations import list_alert_destination_groups+from products.alerts.backend.models.alert import AlertConfiguration+from products.alerts_platform.backend.facade.contracts import (+ AlertDestinationData,+ AlertDestinationGroup,+ DestinationType,+)++# A failed check has no internal event of its own, because production emails it directly. The+# platform routes errored transitions to email by this id, which no HogFunction can subscribe to.+INSIGHT_ALERT_ERRORED_EVENT_ID: Final = "$insight_alert_errored"++_EMAIL_EVENT_IDS: Final = frozenset({LEGACY_INSIGHT_ALERT_EVENT, INSIGHT_ALERT_ERRORED_EVENT_ID})+++def alert_email_recipients(*, team_id: int, alert_id: UUID) -> list[tuple[int, str]]:+ """Subscribed users who can still view the project and the alert's insight."""+ alert = AlertConfiguration.objects.filter(team_id=team_id, id=alert_id).select_related("team", "insight").first()+ if alert is None:+ return []+ candidates = (+ alert.team.all_users_with_access()+ .filter(id__in=alert.subscribed_users.values_list("id", flat=True))+ .only("id", "email")+ )+ return [+ (user.id, user.email)+ for user in candidates+ if UserAccessControl(user, team=alert.team).check_access_level_for_object(alert.insight, "viewer")+ ]+++def list_delivery_destination_groups(+ *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]+) -> list[AlertDestinationGroup]:+ """Everything the platform delivers one alert's events to: its HogFunction destinations, plus+ its subscribers' email for an insight alert.++ Separate from `list_alert_destination_groups`, which the alert APIs list and delete through. An+ email group there would show up as a destination a person could delete.+ """+ groups = list_alert_destination_groups(team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids)+ email = _insight_email_group(team_id=team_id, alert_id=alert_id, allowed_event_ids=allowed_event_ids)+ return [*groups, email] if email is not None else groups+++def _insight_email_group(+ *, team_id: int, alert_id: str, allowed_event_ids: Collection[str]+) -> AlertDestinationGroup | None:+ if _EMAIL_EVENT_IDS.isdisjoint(allowed_event_ids):+ return None+ try:+ alert_uuid = UUID(alert_id)+ except ValueError:+ return None+ addresses = sorted({email for _, email in alert_email_recipients(team_id=team_id, alert_id=alert_uuid) if email})+ if not addresses:+ return None+ data: AlertDestinationData = {"type": DestinationType.EMAIL, "email_addresses": addresses}+ return AlertDestinationGroup(hog_function_ids=(), data=data, fully_enabled=True)diff --git a/products/alerts/backend/logic/destination_configs.py b/products/alerts/backend/logic/destination_configs.pyindex fafdd9590d51..b6bf976ab047 100644--- a/products/alerts/backend/logic/destination_configs.py+++ b/products/alerts/backend/logic/destination_configs.py@@ -370,6 +370,11 @@ def _redact_routing_key(value: str) -> str:return f"••••{value[-4:]}"+# Email reaches an alert's subscribers and is never stored as a HogFunction, so it has no spec.+HOG_FUNCTION_DESTINATION_TYPES: tuple[DestinationType, ...] = tuple(+ destination_type for destination_type in DestinationType if destination_type != DestinationType.EMAIL+)+DESTINATION_SPECS: dict[DestinationType, DestinationSpec] = {spec.type: specfor spec in (diff --git a/products/alerts/backend/test/insight_alerts.py b/products/alerts/backend/test/insight_alerts.pynew file mode 100644index 000000000000..dad6f628abc5--- /dev/null+++ b/products/alerts/backend/test/insight_alerts.py@@ -0,0 +1,35 @@+from typing import Any++from posthog.schema import ChartDisplayType, EventsNode, IntervalType, TrendsFilter, TrendsQuery++from posthog.models.team import Team+from posthog.schema_enums import AlertCalculationInterval++from products.alerts.backend.models.alert import AlertConfiguration, Threshold+from products.product_analytics.backend.facade.models import Insight+++def create_insight_alert(team: Team, **overrides: Any) -> AlertConfiguration:+ insight = Insight.objects.create(+ team=team,+ name="insight",+ query=TrendsQuery(+ series=[EventsNode(event="$pageview")],+ interval=IntervalType.DAY,+ trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),+ ).model_dump(),+ )+ threshold = Threshold.objects.create(+ team=team, insight=insight, configuration={"type": "absolute", "bounds": {"upper": 100.0}}+ )+ fields: dict[str, Any] = {+ "team": team,+ "insight": insight,+ "name": "alert",+ "calculation_interval": AlertCalculationInterval.DAILY.value,+ "config": {"type": "TrendsAlertConfig", "series_index": 0},+ "condition": {"type": "absolute_value"},+ "threshold": threshold,+ }+ fields.update(overrides)+ return AlertConfiguration.objects.create(**fields)diff --git a/products/alerts/backend/test/test_alert_email.py b/products/alerts/backend/test/test_alert_email.pynew file mode 100644index 000000000000..c766eb44c431--- /dev/null+++ b/products/alerts/backend/test/test_alert_email.py@@ -0,0 +1,60 @@+from posthog.test.base import APIBaseTest++from parameterized import parameterized++from posthog.cdp.internal_events import LEGACY_INSIGHT_ALERT_EVENT+from posthog.models.user import User++from products.alerts.backend.facade.destinations import list_alert_destination_groups, list_delivery_destination_groups+from products.alerts.backend.logic.alert_email import INSIGHT_ALERT_ERRORED_EVENT_ID+from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription+from products.alerts.backend.test.insight_alerts import create_insight_alert+from products.alerts_platform.backend.facade.contracts import DestinationType+++class TestInsightAlertEmailDestination(APIBaseTest):+ def _alert(self) -> AlertConfiguration:+ return create_insight_alert(self.team)++ def _subscribe(self, alert: AlertConfiguration, user: User) -> None:+ AlertSubscription.objects.create(user=user, alert_configuration=alert)++ @parameterized.expand([("firing", LEGACY_INSIGHT_ALERT_EVENT), ("errored", INSIGHT_ALERT_ERRORED_EVENT_ID)])+ def test_the_platform_emails_subscribers_who_can_still_see_the_alert(self, _name: str, event_id: str) -> None:+ alert = self._alert()+ self._subscribe(alert, self.user)+ self._subscribe(alert, User.objects.create(email="[email protected]"))++ groups = list_delivery_destination_groups(+ team_id=self.team.id, alert_id=str(alert.id), allowed_event_ids=[event_id]+ )++ assert [group.data for group in groups] == [+ {"type": DestinationType.EMAIL, "email_addresses": [self.user.email]}+ ]+ # The alert APIs list and delete through this one, so an email group there would read as a+ # destination a person could remove.+ assert (+ list_alert_destination_groups(team_id=self.team.id, alert_id=str(alert.id), allowed_event_ids=[event_id])+ == []+ )++ @parameterized.expand(+ [+ ("another_sources_event", True, None, "$logs_alert_firing"),+ ("an_alert_id_that_is_not_an_insight_alert", True, "legacy-logs-alert", LEGACY_INSIGHT_ALERT_EVENT),+ ("an_alert_nobody_subscribed_to", False, None, LEGACY_INSIGHT_ALERT_EVENT),+ ]+ )+ def test_no_email_group_without_an_insight_alert_and_a_subscriber(+ self, _name: str, subscribed: bool, alert_id: str | None, event_id: str+ ) -> None:+ alert = self._alert()+ if subscribed:+ self._subscribe(alert, self.user)++ groups = list_delivery_destination_groups(+ team_id=self.team.id, alert_id=alert_id or str(alert.id), allowed_event_ids=[event_id]+ )++ assert groups == []diff --git a/products/alerts/backend/test/test_destinations.py b/products/alerts/backend/test/test_destinations.pyindex e3f04b4cc290..069e3a9ca03f 100644--- a/products/alerts/backend/test/test_destinations.py+++ b/products/alerts/backend/test/test_destinations.py@@ -12,7 +12,11 @@ from parameterized import parameterizedfrom posthog.models.team.team import Teamfrom products.alerts.backend.facade.destinations import serialize_deliveries-from products.alerts.backend.logic.destination_configs import DESTINATION_SPECS, build_alert_destination_config+from products.alerts.backend.logic.destination_configs import (+ DESTINATION_SPECS,+ HOG_FUNCTION_DESTINATION_TYPES,+ build_alert_destination_config,+)from products.alerts.backend.logic.destinations import (SPEC_BY_TEMPLATE_ID,AlertDestinationGroupKey,@@ -170,7 +174,7 @@ def _group_key_of(config: AlertDestinationConfig) -> AlertDestinationGroupKey:class TestAlertDestinationGroupKey:- @pytest.mark.parametrize("destination_type", list(DestinationType))+ @pytest.mark.parametrize("destination_type", HOG_FUNCTION_DESTINATION_TYPES)def test_a_config_built_for_any_destination_type_is_readable(self, destination_type: DestinationType) -> None:assert _group_key_of(_config_for(destination_type, "$logs_alert_firing")).is_config_readable@@ -184,7 +188,7 @@ class TestAlertDestinationGroupKey:def test_template_ids_and_destination_types_name_each_other_one_to_one(self) -> None:assert set(SPEC_BY_TEMPLATE_ID) == {spec.template_id for spec in DESTINATION_SPECS.values()}- assert {spec.type for spec in SPEC_BY_TEMPLATE_ID.values()} == set(DestinationType)+ assert {spec.type for spec in SPEC_BY_TEMPLATE_ID.values()} == set(HOG_FUNCTION_DESTINATION_TYPES)class TestGroupAlertDestinationRows:diff --git a/products/alerts/backend/test/test_platform_source_cycle.py b/products/alerts/backend/test/test_platform_source_cycle.pyindex 203d7fa12ca3..a25d9f2063ae 100644--- a/products/alerts/backend/test/test_platform_source_cycle.py+++ b/products/alerts/backend/test/test_platform_source_cycle.py@@ -9,8 +9,6 @@ from django.test import override_settingsfrom parameterized import parameterized-from posthog.schema import ChartDisplayType, EventsNode, IntervalType, TrendsFilter, TrendsQuery-from posthog.clickhouse.client.connection import ClickHouseUserfrom posthog.clickhouse.query_tagging import get_query_tagsfrom posthog.exceptions import ClickHouseAtCapacity, ClickHouseClusterMemoryLimitExceeded@@ -20,13 +18,14 @@ from posthog.schema_enums import AlertCalculationIntervalfrom posthog.tasks.alerts.utils import AlertEvaluationResultfrom products.alerts.backend.evaluation.contract import AlertExtractionError-from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, Threshold+from products.alerts.backend.models.alert import AlertCheck, AlertConfigurationfrom products.alerts.backend.platform_source_cycle import (CAPACITY_REJECTED,INFLIGHT_KEY,evaluate_insight_check,plan_insight_batch,)+from products.alerts.backend.test.insight_alerts import create_insight_alertfrom products.alerts_platform.backend.facade import testing as platform_testingfrom products.alerts_platform.backend.facade.api import record_outcomes, slot_offrom products.alerts_platform.backend.facade.contracts import (@@ -35,7 +34,6 @@ from products.alerts_platform.backend.facade.contracts import (PlatformConfigurationSnapshot,SourceKind,)-from products.product_analytics.backend.facade.models import Insight_MODULE = "products.alerts.backend.platform_source_cycle"# A Wednesday, so no weekend rule applies.@@ -49,30 +47,7 @@ class TestPlatformInsightEvaluation(APIBaseTest):self.addCleanup(get_client().delete, INFLIGHT_KEY)def _alert(self, **overrides: Any) -> AlertConfiguration:- insight = Insight.objects.create(- team=self.team,- name="insight",- query=TrendsQuery(- series=[EventsNode(event="$pageview")],- interval=IntervalType.DAY,- trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),- ).model_dump(),- )- threshold = Threshold.objects.create(- team=self.team, insight=insight, configuration={"type": "absolute", "bounds": {"upper": 100.0}}- )- fields: dict[str, Any] = {- "team": self.team,- "insight": insight,- "name": "alert",- "calculation_interval": AlertCalculationInterval.DAILY.value,- "config": {"type": "TrendsAlertConfig", "series_index": 0},- "condition": {"type": "absolute_value"},- "threshold": threshold,- "next_check_at": CUTOFF - timedelta(minutes=1),- }- fields.update(overrides)- return AlertConfiguration.objects.create(**fields)+ return create_insight_alert(self.team, **{"next_check_at": CUTOFF - timedelta(minutes=1), **overrides})def _copy(self, alert: AlertConfiguration | None) -> PlatformConfigurationSnapshot:with team_scope(self.team.id):diff --git a/products/alerts_platform/backend/delivery/email.py b/products/alerts_platform/backend/delivery/email.pynew file mode 100644index 000000000000..f9c230988c13--- /dev/null+++ b/products/alerts_platform/backend/delivery/email.py@@ -0,0 +1,78 @@+"""Email delivery, to the people subscribed to an alert.++The addresses arrive resolved. The product that owns the subscriptions applies its access rules+before the platform sees an address. Sending goes through `posthog.email`, which records every+recipient against a campaign key, so a retried delivery sends nobody a second copy.++An email starts no conversation, so a send returns no handle and a resolve is a new email.+"""++import hashlib+from typing import Final++from django.core.exceptions import ImproperlyConfigured++from posthog.email import EmailMessage++from products.alerts_platform.backend.delivery.message import AlertMessage+from products.alerts_platform.backend.delivery.transport import DeliveryError, MessageHandle+from products.alerts_platform.backend.delivery.wire import credential_digest+from products.alerts_platform.backend.facade.contracts import AlertDestinationData++PROVIDER: Final = "email"+TEMPLATE_NAME: Final = "alert_platform_notification"+++def _campaign_key(message: AlertMessage) -> str:+ # One key per transition a check recorded. `posthog.email` refuses a second send under one key+ # to one recipient, so a retry of this delivery reaches nobody twice. The column holds 128+ # characters, which a long evaluation or group key would exceed, so the key is a digest.+ transition = message.transition+ parts = (+ message.configuration_id,+ transition.grouping_key,+ transition.kind.value,+ transition.occurred_at.isoformat(),+ )+ return f"alert-platform-{hashlib.sha256('|'.join(parts).encode()).hexdigest()[:32]}"+++def subject_for(message: AlertMessage) -> str:+ # The alert name is user-written, and a header cannot carry a line break.+ return f"PostHog alert: {' '.join(message.headline.split())}"+++class EmailTransport:+ provider = PROVIDER++ def channel_target(self, target: AlertDestinationData) -> str:+ # A digest rather than the addresses, which the thread row would otherwise store.+ return credential_digest("\n".join(sorted(target.get("email_addresses", []))))++ def deliver(+ self,+ *,+ team_id: int,+ target: AlertDestinationData,+ message: AlertMessage,+ in_reply_to: MessageHandle | None = None,+ ) -> MessageHandle | None:+ addresses = target.get("email_addresses") or []+ if not addresses:+ raise DeliveryError("This email destination has no recipients.")+ try:+ email = EmailMessage(+ campaign_key=_campaign_key(message),+ template_name=TEMPLATE_NAME,+ subject=subject_for(message),+ template_context={+ "headline": message.headline,+ "details": [{"label": detail.label, "value": detail.value} for detail in message.details],+ },+ )+ except ImproperlyConfigured as error:+ raise DeliveryError("Email is not configured where this alert is delivered from.") from error+ for address in addresses:+ email.add_recipient(email=address)+ email.send()+ return Nonediff --git a/products/alerts_platform/backend/delivery/evaluation.py b/products/alerts_platform/backend/delivery/evaluation.pyindex 13b6526bc7c2..5f9ed6320bb1 100644--- a/products/alerts_platform/backend/delivery/evaluation.py+++ b/products/alerts_platform/backend/delivery/evaluation.py@@ -16,6 +16,7 @@ from posthog.models import Teamfrom products.alerts_platform.backend.delivery.destinations import list_alert_destination_groupsfrom products.alerts_platform.backend.delivery.discord import DiscordTransportfrom products.alerts_platform.backend.delivery.dispatch import deliver+from products.alerts_platform.backend.delivery.email import EmailTransportfrom products.alerts_platform.backend.delivery.pagerduty import PagerDutyTransportfrom products.alerts_platform.backend.delivery.slack import SlackTransportfrom products.alerts_platform.backend.delivery.teams import TeamsTransport@@ -50,6 +51,7 @@ _TRANSPORTS: Final[dict[DestinationType, type[DeliveryTransport]]] = {DestinationType.TEAMS: TeamsTransport,DestinationType.DISCORD: DiscordTransport,DestinationType.PAGERDUTY: PagerDutyTransport,+ DestinationType.EMAIL: EmailTransport,}diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.pyindex a35105b185bd..17c323f7d967 100644--- a/products/alerts_platform/backend/facade/contracts.py+++ b/products/alerts_platform/backend/facade/contracts.py@@ -464,6 +464,7 @@ class DestinationType(LabeledStrEnum):WEBHOOK = "webhook", "Webhook"TEAMS = "teams", "Microsoft Teams"PAGERDUTY = "pagerduty", "PagerDuty"+ EMAIL = "email", "Email"class PagerDutySeverity(StrEnum):@@ -499,6 +500,7 @@ class AlertDestinationData(TypedDict):pagerduty_routing_key: NotRequired[str]pagerduty_severity: NotRequired[str]pagerduty_region: NotRequired[str]+ email_addresses: NotRequired[list[str]]class AlertDestinationValidationError(Exception):diff --git a/products/alerts_platform/backend/tests/test_delivery_email.py b/products/alerts_platform/backend/tests/test_delivery_email.pynew file mode 100644index 000000000000..2b9a024a9f51--- /dev/null+++ b/products/alerts_platform/backend/tests/test_delivery_email.py@@ -0,0 +1,79 @@+from typing import cast++import pytest+from unittest.mock import MagicMock, call, patch++from django.core.exceptions import ImproperlyConfigured+from django.template.loader import render_to_string+from django.test import SimpleTestCase++from products.alerts_platform.backend.delivery.email import TEMPLATE_NAME, EmailTransport+from products.alerts_platform.backend.delivery.message import MessageDetail+from products.alerts_platform.backend.delivery.transport import DeliveryError+from products.alerts_platform.backend.facade.contracts import AlertDestinationData, AlertEventKind+from products.alerts_platform.backend.tests.delivery_messages import alert_message, announced_transition++TARGET = cast(AlertDestinationData, {"type": "email", "email_addresses": ["[email protected]", "[email protected]"]})+++class TestEmailTransport(SimpleTestCase):+ def _deliver(+ self, kind: AlertEventKind = AlertEventKind.FIRING, headline: str = "API errors is firing"+ ) -> MagicMock:+ message = alert_message(+ headline=headline,+ details=(MessageDetail(label="Value", value="312"),),+ transition=announced_transition(kind),+ )+ with patch("products.alerts_platform.backend.delivery.email.EmailMessage") as email_message:+ handle = EmailTransport().deliver(team_id=2, target=TARGET, message=message)+ assert handle is None+ return email_message++ def test_one_email_reaches_every_subscriber(self) -> None:+ email_message = self._deliver(headline="API errors\nis firing")++ kwargs = email_message.call_args.kwargs+ assert kwargs["template_name"] == TEMPLATE_NAME+ assert kwargs["subject"] == "PostHog alert: API errors is firing"+ assert email_message.return_value.add_recipient.call_args_list == [+ call(email="[email protected]"),+ call(email="[email protected]"),+ ]+ email_message.return_value.send.assert_called_once_with()++ def test_a_retry_reuses_the_campaign_key_and_a_new_transition_does_not(self) -> None:+ def key(kind: AlertEventKind) -> str:+ return self._deliver(kind).call_args.kwargs["campaign_key"]++ # The campaign key is what stops a retried delivery emailing anyone a second copy.+ assert key(AlertEventKind.FIRING) == key(AlertEventKind.FIRING)+ assert key(AlertEventKind.FIRING) != key(AlertEventKind.RESOLVED)+ assert len(key(AlertEventKind.FIRING)) <= 128++ def test_a_destination_without_recipients_is_refused(self) -> None:+ with pytest.raises(DeliveryError):+ EmailTransport().deliver(+ team_id=2, target=cast(AlertDestinationData, {"type": "email"}), message=alert_message()+ )++ def test_an_instance_without_email_names_the_cause(self) -> None:+ with patch(+ "products.alerts_platform.backend.delivery.email.EmailMessage",+ side_effect=ImproperlyConfigured("Email is not enabled in this instance."),+ ):+ with pytest.raises(DeliveryError, match="not configured"):+ EmailTransport().deliver(team_id=2, target=TARGET, message=alert_message())++ def test_the_template_renders_the_headline_and_every_detail(self) -> None:+ html = render_to_string(+ f"email/{TEMPLATE_NAME}.html",+ {+ "headline": "API errors is firing",+ "details": [{"label": "Value", "value": "312"}, {"label": "Threshold", "value": "> 300"}],+ },+ )++ assert "API errors is firing" in html+ assert "Value:</strong> 312" in html+ assert "Threshold:</strong> > 300" in html