Skip to content

: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.

feat(alerts): let a source word its own alert messages (#114187)

Jimmy Zhue411b5d23ed5
diff --git a/products/alerts_platform/backend/delivery/describers.py b/products/alerts_platform/backend/delivery/describers.py
new file mode 100644
index 000000000000..d0e03057453b
--- /dev/null
+++ b/products/alerts_platform/backend/delivery/describers.py
@@ -0,0 +1,78 @@
+"""How each source words its own notifications.
+
+The platform imports no source, so a source registers its describer here when Django starts, the
+way `products.alerts` registers its destination resolver.
+"""
+
+from typing import Final
+
+import structlog
+
+from posthog.slack.channels import clip_text
+
+from products.alerts_platform.backend.facade.contracts import (
+ AnnouncedTransition,
+ SourceDescriber,
+ SourceDescription,
+ SourceKind,
+)
+
+# A source's context names things a user chose, such as services, so its size is unbounded. The
+# bound is set once here, so every transport's own budget starts from the same small print.
+MAX_CONTEXT_LINES: Final = 3
+MAX_CONTEXT_LINE_CHARS: Final = 300
+# A data link can carry a whole filter in its query string. Slack refuses a post whose button URL is
+# over 3000 characters, so a longer link is dropped rather than costing the message.
+MAX_DATA_LINK_URL_CHARS: Final = 2000
+
+logger = structlog.get_logger(__name__)
+
+_describers: dict[SourceKind, SourceDescriber] = {}
+
+
+def register(source: SourceKind, describer: SourceDescriber) -> None:
+ # One owner per source. A second registrant would silently reword another product's alerts.
+ registered = _describers.get(source)
+ if registered is not None and registered is not describer:
+ raise RuntimeError(f"A different describer is already registered for {source} alerts.")
+ _describers[source] = describer
+
+
+def describe(source: SourceKind, *, project_id: int, transition: AnnouncedTransition) -> SourceDescription:
+ """The source's own words for a transition, or an empty description.
+
+ Empty when nothing is registered, because the platform's wording is a complete message, so a
+ source without a describer still delivers.
+ """
+ describer = _describers.get(source)
+ if describer is None:
+ return SourceDescription()
+ try:
+ # Bounding the answer is inside the try too, so a describer that returns the wrong shape
+ # falls back like one that raises.
+ return _bounded(source, describer(project_id=project_id, transition=transition))
+ except Exception:
+ # The wording is never worth a lost notification. The platform's own wording goes out
+ # instead, and the counter makes a source whose alerts all fell back visible.
+ logger.exception("alerts_platform.describer_failed", source=source.value)
+ # Imported here because source apps reach this module from ready(), and the metrics module
+ # would load temporalio into every process at startup.
+ from products.alerts_platform.backend.temporal.metrics import ( # noqa: PLC0415 - keeps temporalio off the import path
+ increment_describer_failures,
+ safe_record,
+ )
+
+ safe_record(increment_describer_failures, source.value)
+ return SourceDescription()
+
+
+def _bounded(source: SourceKind, description: SourceDescription) -> SourceDescription:
+ data_link = description.data_link
+ if data_link is not None and len(data_link.url) > MAX_DATA_LINK_URL_CHARS:
+ logger.warning("alerts_platform.data_link_too_long", source=source.value, length=len(data_link.url))
+ data_link = None
+ return SourceDescription(
+ details=description.details,
+ context=tuple(clip_text(line, MAX_CONTEXT_LINE_CHARS) for line in description.context[:MAX_CONTEXT_LINES]),
+ data_link=data_link,
+ )
diff --git a/products/alerts_platform/backend/delivery/discord.py b/products/alerts_platform/backend/delivery/discord.py
index 71ee7c1503cc..373d79c61ab9 100644
--- a/products/alerts_platform/backend/delivery/discord.py
+++ b/products/alerts_platform/backend/delivery/discord.py
@@ -19,6 +19,10 @@ PROVIDER: Final = "discord"
MAX_CONTENT_CHARS: Final = 2000
+# The footer is taken off the top of the budget, so it is bounded to leave the details most of it.
+MAX_FOOTER_CONTEXT_CHARS: Final = 300
+MAX_FOOTER_LINK_URL_CHARS: Final = 500
+
# Stops a URL in a query error from unfurling into a preview of a page the alert never chose.
SUPPRESS_EMBEDS: Final = 1 << 2
@@ -32,12 +36,27 @@ def escape_markdown(text: str) -> str:
def content_for(message: AlertMessage) -> str:
- link = f"\n\n[View alert](<{message.alert_url}>)"
- return _body(message, MAX_CONTENT_CHARS - len(link)) + link
+ footer = _footer(message)
+ return _body(message, MAX_CONTENT_CHARS - len(footer)) + footer
+
+
+def _footer(message: AlertMessage) -> str:
+ # The alert link is always short. A data link long enough to crowd out the details is left out.
+ links = [
+ f"[{escape_markdown(link.label)}](<{link.url}>)"
+ for link in message.links
+ if len(link.url) <= MAX_FOOTER_LINK_URL_CHARS
+ ]
+ footer = "\n\n"
+ if message.context:
+ # `-# ` is Discord's small print. Context names things a user chose, so it is escaped.
+ context = clip_text(" | ".join(message.context), MAX_FOOTER_CONTEXT_CHARS)
+ footer += f"-# {escape_markdown(context)}\n"
+ return footer + " · ".join(links)
def _body(message: AlertMessage, limit: int) -> str:
- headline = f"**{escape_markdown(message.headline)}**"
+ headline = f"**{escape_markdown(message.title)}**"
lines = [f"**{detail.label}:** {escape_markdown(detail.value)}" for detail in message.details]
if not lines:
return headline
diff --git a/products/alerts_platform/backend/delivery/message.py b/products/alerts_platform/backend/delivery/message.py
index 1d3812d01e9c..5b2f7eed4f39 100644
--- a/products/alerts_platform/backend/delivery/message.py
+++ b/products/alerts_platform/backend/delivery/message.py
@@ -1,8 +1,9 @@
"""What a notification says, built from the rows the evaluation recorded.
-Source-agnostic. Every fact comes from an `AnnouncedTransition`, which the platform projects from
-a `PlatformAlertEvent`, so a message states what its own check decided however long after the
-check it is rendered. A provider turns this into its own body shape.
+Every fact comes from an `AnnouncedTransition`, which the platform projects from a
+`PlatformAlertEvent`, so a message states what its own check decided however long after the check
+it is rendered. A source can word parts of it in its own vocabulary through a registered describer.
+A provider turns this into its own body shape.
"""
from typing import Any, Final
@@ -10,11 +11,14 @@ from typing import Any, Final
from posthog.dataclasses import frozen
from posthog.utils import absolute_uri, pluralize
+from products.alerts_platform.backend.delivery.describers import describe
from products.alerts_platform.backend.facade.contracts import (
AlertEventKind,
AnnouncedTransition,
EvaluationAnnouncement,
IncidentAction,
+ MessageDetail,
+ MessageLink,
SourceKind,
)
@@ -25,6 +29,14 @@ _HEADLINES: Final[dict[AlertEventKind, str]] = {
AlertEventKind.BROKEN: "{kind} alert '{name}' is turned off",
}
+# The symbols the legacy messages use, so a pilot team sees the same state at a glance on both paths.
+_SYMBOLS: Final[dict[AlertEventKind, str]] = {
+ AlertEventKind.FIRING: "🔴",
+ AlertEventKind.RESOLVED: "🟢",
+ AlertEventKind.ERRORED: "🟡",
+ AlertEventKind.BROKEN: "⚠️",
+}
+
_SOURCE_LABELS: Final[dict[SourceKind, str]] = {
SourceKind.LOGS: "Log",
SourceKind.INSIGHT: "Insight",
@@ -37,33 +49,39 @@ _INCIDENT_KINDS: Final[dict[IncidentAction, AlertEventKind]] = {
}
-@frozen
-class MessageDetail:
- """One labelled fact in a message. Every provider renders these the same way, as a Slack
- section, an Adaptive Card body, or lines of markdown."""
-
- label: str
- value: str
-
-
@frozen
class AlertMessage:
"""One notification, before a provider formats it.
- `headline` and `details` are the copy, and a provider that renders text uses only those. The
- other fields are the facts the copy was written from, for a provider whose body is data.
- `incident_action` is set only on a message for an incident manager destination.
+ `headline`, `details`, `context` and the links are the copy, and a provider that renders text
+ uses only those. `symbol` marks the state for a reader, and a provider whose body is data
+ leaves it out. The other fields are the facts the copy was written from. `incident_action` is
+ set only on a message for an incident manager destination.
"""
headline: str
+ symbol: str
details: tuple[MessageDetail, ...]
configuration_id: str
alert_name: str
source: SourceKind
alert_url: str
transition: AnnouncedTransition
+ context: tuple[str, ...] = ()
+ data_link: MessageLink | None = None
incident_action: IncidentAction | None = None
+ @property
+ def title(self) -> str:
+ """The headline with its state symbol, for a provider a person reads."""
+ return f"{self.symbol} {self.headline}"
+
+ @property
+ def links(self) -> tuple[MessageLink, ...]:
+ """The source's data first, because that is where a responder starts."""
+ view_alert = MessageLink(label="View alert", url=self.alert_url)
+ return (self.data_link, view_alert) if self.data_link is not None else (view_alert,)
+
def alert_url(project_id: int, configuration_id: str) -> str:
# pinned: the platform alert page route in products/alerts_platform/manifest.tsx.
@@ -83,7 +101,7 @@ def _threshold(condition: dict[str, Any]) -> str | None:
return f"{operator} {count}"
-def _breach_details(transition: AnnouncedTransition) -> list[MessageDetail]:
+def _breach_details(transition: AnnouncedTransition) -> tuple[MessageDetail, ...]:
details: list[MessageDetail] = []
if transition.value is not None:
details.append(MessageDetail(label="Value", value=_number(transition.value)))
@@ -93,16 +111,16 @@ def _breach_details(transition: AnnouncedTransition) -> list[MessageDetail]:
window_minutes = transition.condition.get("window_minutes")
if window_minutes:
details.append(MessageDetail(label="Window", value=pluralize(window_minutes, "minute")))
- return details
+ return tuple(details)
-def _failure_details(transition: AnnouncedTransition, consecutive_failures: int) -> list[MessageDetail]:
+def _failure_details(transition: AnnouncedTransition, consecutive_failures: int) -> tuple[MessageDetail, ...]:
details: list[MessageDetail] = []
if transition.error_message:
details.append(MessageDetail(label="Error", value=transition.error_message))
if consecutive_failures:
details.append(MessageDetail(label="Failed checks", value=str(consecutive_failures)))
- return details
+ return tuple(details)
def build_message(
@@ -127,20 +145,24 @@ def build_message(
# here without an incident action means that filter is gone.
raise ValueError(f"{transition.kind} announces nothing and has no message")
+ # Platform rows live on the project's root team, so its id is the project id.
+ project_id = team_id
+ description = describe(announcement.source, project_id=project_id, transition=transition)
failure_kinds = (AlertEventKind.ERRORED, AlertEventKind.BROKEN)
- details = (
- _failure_details(transition, announcement.consecutive_failures)
- if transition.kind in failure_kinds
- else _breach_details(transition)
- )
+ if transition.kind in failure_kinds:
+ details = _failure_details(transition, announcement.consecutive_failures)
+ else:
+ details = description.details or _breach_details(transition)
return AlertMessage(
headline=headline.format(kind=_SOURCE_LABELS[announcement.source], name=announcement.alert_name),
- details=tuple(details),
+ symbol=_SYMBOLS[kind],
+ details=details,
configuration_id=announcement.configuration_id,
alert_name=announcement.alert_name,
source=announcement.source,
- # Platform rows live on the project's root team, so its id is the project id.
- alert_url=alert_url(team_id, announcement.configuration_id),
+ alert_url=alert_url(project_id, announcement.configuration_id),
transition=transition,
+ context=description.context,
+ data_link=description.data_link,
incident_action=incident_action,
)
diff --git a/products/alerts_platform/backend/delivery/pagerduty.py b/products/alerts_platform/backend/delivery/pagerduty.py
index 3fa4069a00f7..3d5b42a8dad3 100644
--- a/products/alerts_platform/backend/delivery/pagerduty.py
+++ b/products/alerts_platform/backend/delivery/pagerduty.py
@@ -73,6 +73,8 @@ def pagerduty_body(message: AlertMessage, *, routing_key: str, severity: PagerDu
transition = message.transition
body["client"] = "PostHog"
body["client_url"] = message.alert_url
+ if message.data_link is not None:
+ body["links"] = [{"href": message.data_link.url, "text": message.data_link.label}]
body["payload"] = {
"summary": message.headline[:_MAX_SUMMARY_LENGTH],
"source": SOURCE,
diff --git a/products/alerts_platform/backend/delivery/slack.py b/products/alerts_platform/backend/delivery/slack.py
index 7b3899b430bf..fe64f84d2ea3 100644
--- a/products/alerts_platform/backend/delivery/slack.py
+++ b/products/alerts_platform/backend/delivery/slack.py
@@ -15,18 +15,22 @@ from posthog.slack.channels import (
SlackButton,
actions_block,
clip_text,
+ context_block,
header_block,
post_message,
section_block,
)
from posthog.slack.formatting import escape_slack_mrkdwn
-from products.alerts_platform.backend.delivery.message import AlertMessage, MessageDetail
+from products.alerts_platform.backend.delivery.message import AlertMessage
from products.alerts_platform.backend.delivery.transport import DeliveryError, MessageHandle
-from products.alerts_platform.backend.facade.contracts import AlertDestinationData
+from products.alerts_platform.backend.facade.contracts import AlertDestinationData, MessageDetail
PROVIDER: Final = "slack"
+# Slack refuses a post whose context element is over 3000 characters.
+MAX_CONTEXT_CHARS: Final = 3000
+
# Separates alert traffic from the API-driven calls on the shared Slack egress metrics.
EGRESS_SOURCE: Final = "alerts"
@@ -49,10 +53,15 @@ def _body(details: tuple[MessageDetail, ...]) -> str:
def blocks_for(message: AlertMessage) -> list[dict[str, Any]]:
- blocks: list[dict[str, Any]] = [header_block(message.headline)]
+ blocks: list[dict[str, Any]] = [header_block(message.title)]
if message.details:
blocks.append(section_block(_body(message.details)))
- blocks.append(actions_block([SlackButton(text="View alert", url=message.alert_url)]))
+ if message.context:
+ # Context names things a user chose, such as services, so it is escaped like a detail.
+ # Escaping can grow it fourfold, so the clip comes after it.
+ context = " | ".join(escape_slack_mrkdwn(line) for line in message.context)
+ blocks.append(context_block(clip_text(context, MAX_CONTEXT_CHARS)))
+ blocks.append(actions_block([SlackButton(text=link.label, url=link.url) for link in message.links]))
return blocks
@@ -82,7 +91,7 @@ class SlackTransport:
channel,
blocks_for(message),
# The one place the alert's name reaches mrkdwn: the header renders plain text.
- escape_slack_mrkdwn(message.headline),
+ escape_slack_mrkdwn(message.title),
thread_ts=in_reply_to.external_ref.get("ts") if in_reply_to else None,
)
except SlackApiError as error:
diff --git a/products/alerts_platform/backend/delivery/teams.py b/products/alerts_platform/backend/delivery/teams.py
index 8cc15d3b8ea1..93ee9b95e8b1 100644
--- a/products/alerts_platform/backend/delivery/teams.py
+++ b/products/alerts_platform/backend/delivery/teams.py
@@ -50,12 +50,13 @@ def _clip(text: str, budget: int) -> str:
def card_for(message: AlertMessage) -> dict[str, Any]:
- headline = escape_markdown(message.headline)
+ headline = escape_markdown(message.title)
body: list[dict[str, Any]] = [{"type": "TextBlock", "text": headline, "weight": "Bolder", "wrap": True}]
+ context = escape_markdown(" | ".join(message.context))
if message.details:
# An error message can carry a whole query, so it is a detail that overflows. Each detail
# gets an equal share, so clipping the error cannot drop the failure count after it.
- share = (TEXT_BUDGET_BYTES - _wire_size(headline)) // len(message.details)
+ share = (TEXT_BUDGET_BYTES - _wire_size(headline) - _wire_size(context)) // len(message.details)
body.append(
{
"type": "FactSet",
@@ -65,6 +66,9 @@ def card_for(message: AlertMessage) -> dict[str, Any]:
],
}
)
+ if context:
+ body.append({"type": "TextBlock", "text": context, "isSubtle": True, "size": "Small", "wrap": True})
+ actions = [{"type": "Action.OpenUrl", "title": link.label, "url": link.url} for link in message.links]
return {
"type": "message",
"attachments": [
@@ -76,7 +80,7 @@ def card_for(message: AlertMessage) -> dict[str, Any]:
"type": "AdaptiveCard",
"version": "1.2",
"body": body,
- "actions": [{"type": "Action.OpenUrl", "title": "View alert", "url": message.alert_url}],
+ "actions": actions,
},
}
],
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index 2e77dc3bfd04..8fd54c9f6b8f 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -595,6 +595,49 @@ class DestinationResolver(Protocol):
) -> list[AlertDestinationGroup]: ...
+@frozen
+class MessageDetail:
+ """One labelled fact in a message. Every provider renders these the same way, as a Slack
+ section, an Adaptive Card body, or lines of markdown."""
+
+ label: str
+ value: str
+
+
+@frozen
+class MessageLink:
+ label: str
+ url: str
+
+
+@frozen
+class SourceDescription:
+ """What a source says about one transition, in the words its own product uses.
+
+ The platform imports no source, so it can say only "Value: 11". A source can say "11 logs in
+ 10m". Every part is optional, and a part a source leaves out falls back to the platform's
+ own wording or to nothing.
+ """
+
+ # Replaces the platform's breach details. A failed or turned-off check keeps the platform's
+ # failure details, because the failure is the platform's, not the source's.
+ details: tuple[MessageDetail, ...] = ()
+ # Short lines of small print, such as which services an alert watches.
+ context: tuple[str, ...] = ()
+ # Where the data behind the alert is, such as the matching logs.
+ data_link: MessageLink | None = None
+
+
+class SourceDescriber(Protocol):
+ """How a source describes its transitions. A source registers one for native delivery.
+
+ It runs once per destination on the send path, inside a delivery that a held thread or a
+ failure repeats. So it builds its answer from the transition alone and does no I/O.
+ """
+
+ def __call__(self, *, project_id: int, transition: AnnouncedTransition) -> SourceDescription: ...
+
+
# Comparison against a source's own stack.
#
# What a comparison reads, and what a source must supply for one.
diff --git a/products/alerts_platform/backend/facade/delivery.py b/products/alerts_platform/backend/facade/delivery.py
index ecb8169c331d..6bf9951a8744 100644
--- a/products/alerts_platform/backend/facade/delivery.py
+++ b/products/alerts_platform/backend/facade/delivery.py
@@ -1,8 +1,12 @@
-"""Facade for native delivery: how the product that owns destinations plugs them in."""
+"""Facade for native delivery: how other products plug in destinations and their own wording."""
-from products.alerts_platform.backend.delivery import destinations
-from products.alerts_platform.backend.facade.contracts import DestinationResolver
+from products.alerts_platform.backend.delivery import describers, destinations
+from products.alerts_platform.backend.facade.contracts import DestinationResolver, SourceDescriber, SourceKind
def register_destination_resolver(resolver: DestinationResolver) -> None:
destinations.register(resolver)
+
+
+def register_source_describer(source: SourceKind, describer: SourceDescriber) -> None:
+ describers.register(source, describer)
diff --git a/products/alerts_platform/backend/temporal/metrics.py b/products/alerts_platform/backend/temporal/metrics.py
index cc1f81afb1d7..beb8af64268b 100644
--- a/products/alerts_platform/backend/temporal/metrics.py
+++ b/products/alerts_platform/backend/temporal/metrics.py
@@ -104,6 +104,14 @@ def increment_deliveries_deferred(source: str, count: int) -> None:
).add(count)
+def increment_describer_failures(source: str) -> None:
+ """A source's describer raised, so its alerts went out in the platform's generic wording."""
+ get_metric_meter({"source": source}).create_counter(
+ "alerts_platform_describer_failures_total",
+ "Messages sent in the platform's wording because the source's describer raised",
+ ).add(1)
+
+
def increment_deliveries_previewed(source: str) -> None:
get_metric_meter({"source": source}).create_counter(
"alerts_platform_deliveries_previewed_total",
diff --git a/products/alerts_platform/backend/tests/delivery_messages.py b/products/alerts_platform/backend/tests/delivery_messages.py
index 4bc7b2a7cc50..f36e8b80649b 100644
--- a/products/alerts_platform/backend/tests/delivery_messages.py
+++ b/products/alerts_platform/backend/tests/delivery_messages.py
@@ -10,11 +10,13 @@ from requests import PreparedRequest, Response, Session
from requests.adapters import BaseAdapter
from requests.structures import CaseInsensitiveDict
-from products.alerts_platform.backend.delivery.message import AlertMessage, MessageDetail
+from products.alerts_platform.backend.delivery.message import AlertMessage
from products.alerts_platform.backend.facade.contracts import (
AlertEventKind,
AnnouncedTransition,
IncidentAction,
+ MessageDetail,
+ MessageLink,
SourceKind,
)
@@ -45,15 +47,21 @@ def alert_message(
transition: AnnouncedTransition | None = None,
alert_name: str = "API errors",
incident_action: IncidentAction | None = None,
+ symbol: str = "\U0001f534",
+ context: tuple[str, ...] = (),
+ data_link: MessageLink | None = None,
) -> AlertMessage:
return AlertMessage(
headline=headline,
+ symbol=symbol,
details=details,
configuration_id="cfg-1",
alert_name=alert_name,
source=SourceKind.LOGS,
alert_url=ALERT_URL,
transition=transition or announced_transition(),
+ context=context,
+ data_link=data_link,
incident_action=incident_action,
)
diff --git a/products/alerts_platform/backend/tests/test_delivery_discord.py b/products/alerts_platform/backend/tests/test_delivery_discord.py
index f9353d5bc4b7..63009b8be03a 100644
--- a/products/alerts_platform/backend/tests/test_delivery_discord.py
+++ b/products/alerts_platform/backend/tests/test_delivery_discord.py
@@ -7,9 +7,8 @@ from django.test import SimpleTestCase
from parameterized import parameterized
from products.alerts_platform.backend.delivery.discord import MAX_CONTENT_CHARS, DiscordTransport, content_for
-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
+from products.alerts_platform.backend.facade.contracts import AlertDestinationData, MessageDetail, MessageLink
from products.alerts_platform.backend.tests.delivery_messages import ALERT_URL, alert_message, pinned_post
@@ -21,28 +20,48 @@ class TestDiscordMessage(SimpleTestCase):
MessageDetail(label="Threshold", value="> 300"),
MessageDetail(label="Error", value="bad query\n# not a heading"),
),
+ context=("Services: [api](https://evil.example)",),
+ data_link=MessageLink(
+ label="View logs", url="https://app.example.com/project/1/logs?serviceNames=%5B%22checkout%22%5D"
+ ),
)
body = DiscordTransport().body_for(message)
assert body == {
- "content": "**@everyone \\[Checkout\\](https://evil.example) is firing**\n\n"
- "**Threshold:** \\> 300\n**Error:** bad query\n\\# not a heading"
- f"\n\n[View alert](<{ALERT_URL}>)",
+ "content": "**\U0001f534 @everyone \\[Checkout\\](https://evil.example) is firing**\n\n"
+ "**Threshold:** \\> 300\n**Error:** bad query\n\\# not a heading\n\n"
+ "-# Services: \\[api\\](https://evil.example)\n"
+ f"[View logs](<https://app.example.com/project/1/logs?serviceNames=%5B%22checkout%22%5D>) · [View alert](<{ALERT_URL}>)",
"allowed_mentions": {"parse": []},
"flags": 4,
}
- def test_a_long_error_keeps_the_message_inside_what_discord_accepts(self) -> None:
+ @parameterized.expand(
+ [
+ ("long_error", (), None),
+ (
+ "long_error_context_and_data_link",
+ ("Services: " + "api," * 400,) * 3,
+ MessageLink(label="View logs", url="https://app.example.com/logs?" + "q" * 3000),
+ ),
+ ]
+ )
+ def test_a_long_message_stays_inside_what_discord_accepts(
+ self, _name: str, context: tuple[str, ...], data_link: MessageLink | None
+ ) -> None:
message = alert_message(
headline="API errors could not be checked",
details=(MessageDetail(label="Error", value="x" * 5000), MessageDetail(label="Failed checks", value="3")),
+ context=context,
+ data_link=data_link,
)
content = content_for(message)
assert len(content) <= MAX_CONTENT_CHARS
- assert content.endswith(f"**Failed checks:** 3\n\n[View alert](<{ALERT_URL}>)")
+ assert "**Failed checks:** 3" in content
+ assert content.endswith(f"[View alert](<{ALERT_URL}>)")
class TestDiscordTransport(SimpleTestCase):
diff --git a/products/alerts_platform/backend/tests/test_delivery_message.py b/products/alerts_platform/backend/tests/test_delivery_message.py
index 4e872855663c..d4493a0056bc 100644
--- a/products/alerts_platform/backend/tests/test_delivery_message.py
+++ b/products/alerts_platform/backend/tests/test_delivery_message.py
@@ -2,16 +2,32 @@ from datetime import UTC, datetime
from typing import Any
import pytest
+from unittest.mock import patch
-from products.alerts_platform.backend.delivery.message import AlertMessage, MessageDetail, build_message
+from products.alerts_platform.backend.delivery import describers
+from products.alerts_platform.backend.delivery.message import AlertMessage, build_message
from products.alerts_platform.backend.facade.contracts import (
AlertEventKind,
AnnouncedTransition,
EvaluationAnnouncement,
IncidentAction,
+ MessageDetail,
+ MessageLink,
+ SourceDescription,
SourceKind,
)
+
+def _described_by(describer: Any) -> Any:
+ return patch.dict(describers._describers, {SourceKind.LOGS: describer})
+
+
+LOGS_DESCRIPTION = SourceDescription(
+ details=(MessageDetail(label="Threshold breached", value="300 logs in 5m (threshold: above 100)"),),
+ context=("Services: checkout",),
+ data_link=MessageLink(label="View logs", url="https://app.example.com/project/7/logs"),
+)
+
CONDITION = {"threshold_count": 100, "threshold_operator": "above", "window_minutes": 5}
@@ -108,16 +124,60 @@ class TestAlertMessage:
_build(_announcement(), _transition(AlertEventKind.CHECK))
@pytest.mark.parametrize(
- "action,expected",
+ "action,expected,symbol",
[
- (IncidentAction.TRIGGER, "Log alert 'API errors' is firing"),
- (IncidentAction.RESOLVE, "Log alert 'API errors' is resolved"),
+ (IncidentAction.TRIGGER, "Log alert 'API errors' is firing", "\U0001f534"),
+ (IncidentAction.RESOLVE, "Log alert 'API errors' is resolved", "\U0001f7e2"),
],
)
- def test_a_held_check_speaks_for_the_incident_it_moved(self, action: IncidentAction, expected: str) -> None:
+ def test_a_held_check_speaks_for_the_incident_it_moved(
+ self, action: IncidentAction, expected: str, symbol: str
+ ) -> None:
message = _build(_announcement(), _transition(AlertEventKind.CHECK), incident_action=action)
- assert (message.headline, message.incident_action) == (expected, action)
+ assert (message.headline, message.symbol, message.incident_action) == (expected, symbol, action)
+
+ def test_a_source_words_a_breach_in_its_own_vocabulary(self) -> None:
+ with _described_by(lambda **_: LOGS_DESCRIPTION):
+ message = _build(_announcement(), _transition(AlertEventKind.FIRING))
+
+ assert (message.details, message.context, message.data_link) == (
+ LOGS_DESCRIPTION.details,
+ LOGS_DESCRIPTION.context,
+ LOGS_DESCRIPTION.data_link,
+ )
+
+ def test_a_failed_check_keeps_the_platform_failure_details_under_a_source_description(self) -> None:
+ with _described_by(lambda **_: LOGS_DESCRIPTION):
+ message = _build(
+ _announcement(consecutive_failures=3),
+ _transition(AlertEventKind.ERRORED, value=None, error_message="Query is too expensive"),
+ )
+
+ assert message.details[0] == MessageDetail(label="Error", value="Query is too expensive")
+ assert message.data_link == LOGS_DESCRIPTION.data_link
+
+ def test_a_source_link_too_long_for_slack_is_left_out(self) -> None:
+ long_link = MessageLink(label="View logs", url="https://app.example.com/logs?" + "q" * 3000)
+ description = SourceDescription(context=("Services: checkout",), data_link=long_link)
+
+ with _described_by(lambda **_: description):
+ message = _build(_announcement(), _transition(AlertEventKind.FIRING))
+
+ assert (message.context, message.data_link) == (("Services: checkout",), None)
+
+ @pytest.mark.parametrize("answer", ["raises", "returns_none"])
+ def test_a_broken_describer_still_delivers_the_platform_wording(self, answer: str) -> None:
+ def broken(**_: Any) -> Any:
+ if answer == "raises":
+ raise KeyError("serviceNames")
+ return None
+
+ with _described_by(broken):
+ message = _build(_announcement(), _transition(AlertEventKind.FIRING))
+
+ assert MessageDetail(label="Threshold", value="above 100") in message.details
+ assert (message.context, message.data_link) == ((), None)
def test_a_partial_condition_drops_the_line_it_cannot_state(self) -> None:
message = _build(_announcement(), _transition(AlertEventKind.FIRING, condition={}))
diff --git a/products/alerts_platform/backend/tests/test_delivery_pagerduty.py b/products/alerts_platform/backend/tests/test_delivery_pagerduty.py
index e36d12c08159..c92bfd1ffed8 100644
--- a/products/alerts_platform/backend/tests/test_delivery_pagerduty.py
+++ b/products/alerts_platform/backend/tests/test_delivery_pagerduty.py
@@ -9,13 +9,14 @@ from django.test import SimpleTestCase
import requests
from parameterized import parameterized
-from products.alerts_platform.backend.delivery.message import AlertMessage, MessageDetail
+from products.alerts_platform.backend.delivery.message import AlertMessage
from products.alerts_platform.backend.delivery.pagerduty import PagerDutyTransport, pagerduty_body
from products.alerts_platform.backend.delivery.transport import DeliveryError
from products.alerts_platform.backend.facade.contracts import (
AlertDestinationData,
AlertEventKind,
IncidentAction,
+ MessageDetail,
PagerDutySeverity,
)
from products.alerts_platform.backend.tests.delivery_messages import (
diff --git a/products/alerts_platform/backend/tests/test_delivery_slack.py b/products/alerts_platform/backend/tests/test_delivery_slack.py
index c6574b6d9a29..0d63f4477258 100644
--- a/products/alerts_platform/backend/tests/test_delivery_slack.py
+++ b/products/alerts_platform/backend/tests/test_delivery_slack.py
@@ -11,10 +11,9 @@ from slack_sdk.errors import SlackApiError
from posthog.models.integration import Integration
from posthog.slack.channels import MAX_HEADER_CHARS, MAX_SECTION_CHARS
-from products.alerts_platform.backend.delivery.message import MessageDetail
from products.alerts_platform.backend.delivery.slack import SlackTransport, blocks_for
from products.alerts_platform.backend.delivery.transport import DeliveryError, MessageHandle
-from products.alerts_platform.backend.facade.contracts import AlertDestinationData
+from products.alerts_platform.backend.facade.contracts import AlertDestinationData, MessageDetail, MessageLink
from products.alerts_platform.backend.tests.delivery_messages import ALERT_URL, alert_message
MESSAGE = alert_message(
@@ -51,16 +50,27 @@ class TestSlackBlocks(SimpleTestCase):
assert len(section["text"]["text"]) <= MAX_SECTION_CHARS
assert "*Failed checks:* 3" in section["text"]["text"]
- def test_a_query_error_cannot_speak_as_slack_markup(self) -> None:
+ def test_user_text_cannot_speak_as_slack_markup(self) -> None:
message = alert_message(
headline="API errors could not be checked",
details=(MessageDetail(label="Error", value="no column <!channel> in <http://x|table>"),),
+ context=("Services: <!channel>",),
)
- body = blocks_for(message)[1]["text"]["text"]
+ blocks = blocks_for(message)
+ body = blocks[1]["text"]["text"]
+ context = blocks[2]["elements"][0]["text"]
- assert "<!channel>" not in body
+ assert "<!channel>" not in body + context
assert "&lt;!channel&gt;" in body
+ assert context == "Services: &lt;!channel&gt;"
+
+ def test_escaped_context_stays_inside_what_slack_accepts(self) -> None:
+ message = alert_message(context=("&" * 300,) * 3)
+
+ context = blocks_for(message)[-2]["elements"][0]["text"]
+
+ assert len(context) <= 3000
def test_a_message_without_details_carries_no_empty_section(self) -> None:
blocks = blocks_for(alert_message(headline="API errors is resolved", details=()))
@@ -68,6 +78,17 @@ class TestSlackBlocks(SimpleTestCase):
assert [block["type"] for block in blocks] == ["header", "actions"]
assert blocks[1]["elements"][0]["url"] == ALERT_URL
+ def test_the_source_data_link_comes_before_the_alert_link(self) -> None:
+ data_url = "https://app.example.com/project/1/logs"
+ message = alert_message(data_link=MessageLink(label="View logs", url=data_url))
+
+ buttons = blocks_for(message)[-1]["elements"]
+
+ assert [(button["text"]["text"], button["url"]) for button in buttons] == [
+ ("View logs", data_url),
+ ("View alert", ALERT_URL),
+ ]
+
class TestSlackTransport(APIBaseTest):
def setUp(self) -> None:
diff --git a/products/alerts_platform/backend/tests/test_delivery_teams.py b/products/alerts_platform/backend/tests/test_delivery_teams.py
index c4631d5cfe98..6dea89ce10bb 100644
--- a/products/alerts_platform/backend/tests/test_delivery_teams.py
+++ b/products/alerts_platform/backend/tests/test_delivery_teams.py
@@ -7,10 +7,9 @@ from django.test import SimpleTestCase
from parameterized import parameterized
-from products.alerts_platform.backend.delivery.message import MessageDetail
from products.alerts_platform.backend.delivery.teams import TeamsTransport, card_for
from products.alerts_platform.backend.delivery.transport import DeliveryError
-from products.alerts_platform.backend.facade.contracts import AlertDestinationData
+from products.alerts_platform.backend.facade.contracts import AlertDestinationData, MessageDetail, MessageLink
from products.alerts_platform.backend.tests.delivery_messages import ALERT_URL, alert_message, pinned_post
TEAMS_URL = "https://prod-00.westus.logic.azure.com:443/workflows/abc/triggers/manual/paths/invoke?sig=fake"
@@ -21,6 +20,10 @@ class TestTeamsCard(SimpleTestCase):
message = alert_message(
headline="[Checkout](https://evil.example) is firing",
details=(MessageDetail(label="Value", value="312"), MessageDetail(label="Error", value="no *column*")),
+ context=("Services: [api](https://evil.example)",),
+ data_link=MessageLink(
+ label="View logs", url="https://app.example.com/project/1/logs?serviceNames=%5B%22checkout%22%5D"
+ ),
)
assert card_for(message) == {
@@ -36,7 +39,7 @@ class TestTeamsCard(SimpleTestCase):
"body": [
{
"type": "TextBlock",
- "text": r"\[Checkout\](https://evil.example) is firing",
+ "text": "\U0001f534 " + r"\[Checkout\](https://evil.example) is firing",
"weight": "Bolder",
"wrap": True,
},
@@ -47,8 +50,22 @@ class TestTeamsCard(SimpleTestCase):
{"title": "Error", "value": r"no \*column\*"},
],
},
+ {
+ "type": "TextBlock",
+ "text": r"Services: \[api\](https://evil.example)",
+ "isSubtle": True,
+ "size": "Small",
+ "wrap": True,
+ },
+ ],
+ "actions": [
+ {
+ "type": "Action.OpenUrl",
+ "title": "View logs",
+ "url": "https://app.example.com/project/1/logs?serviceNames=%5B%22checkout%22%5D",
+ },
+ {"type": "Action.OpenUrl", "title": "View alert", "url": ALERT_URL},
],
- "actions": [{"type": "Action.OpenUrl", "title": "View alert", "url": ALERT_URL}],
},
}
],
diff --git a/products/alerts_platform/backend/tests/test_delivery_webhook.py b/products/alerts_platform/backend/tests/test_delivery_webhook.py
index 525186d4599e..057aa5c7eeee 100644
--- a/products/alerts_platform/backend/tests/test_delivery_webhook.py
+++ b/products/alerts_platform/backend/tests/test_delivery_webhook.py
@@ -14,7 +14,6 @@ from posthog.models.scoping import team_scope
from posthog.security.pinned_requests import SSRFBlockedError
from products.alerts_platform.backend.delivery.dispatch import deliver
-from products.alerts_platform.backend.delivery.message import MessageDetail
from products.alerts_platform.backend.delivery.thread_store import DatabaseThreadStore
from products.alerts_platform.backend.delivery.transport import DeliveryError
from products.alerts_platform.backend.delivery.webhook import WebhookTransport, alertmanager_body
@@ -22,6 +21,7 @@ from products.alerts_platform.backend.facade.contracts import (
AlertDestinationData,
AlertEventKind,
EvaluationAnnouncement,
+ MessageDetail,
SourceKind,
)
from products.alerts_platform.backend.models import PlatformAlertConfiguration, PlatformAlertThread