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(metrics): manage metrics alert destinations (#125101)

Jimmy Zhuf79012402525
diff --git a/products/metrics/backend/alerts/destinations.py b/products/metrics/backend/alerts/destinations.py
index 5e4f0778a94e..d3232b66f042 100644
--- a/products/metrics/backend/alerts/destinations.py
+++ b/products/metrics/backend/alerts/destinations.py
@@ -1,100 +1,32 @@
-"""What each metrics alert event says, and where its destinations may send it.
+"""The event ids of a metrics alert's transitions, and the destination types it sends to.
-A destination is a set of HogFunctions, one per event kind it handles. Native delivery reads them to
-find who to tell and words the message itself, so their templates never run.
+A metrics alert's destinations are `AlertDestination` rows. Delivery maps each event id back to the
+transition it announces, so it knows which rows hear it, and words the message itself.
"""
-from dataclasses import replace
-from typing import Final, Literal
+from typing import Final
-from products.alerts_platform.backend.facade.contracts import (
- AlertDestinationAction,
- AlertEventKind,
- EventKindSpec,
- IncidentAction,
-)
-
-EventKind = Literal["firing", "resolved", "errored", "broken", "incident_opened", "incident_closed"]
-
-_PRODUCT_LABEL = "metric alert"
-_METRICS_URL = "{project.url}/metrics"
-_DATA: Final[dict[str, str]] = {
- "alert_id": "{event.properties.alert_id}",
- "alert_name": "{event.properties.alert_name}",
- "query": "{event.properties.query}",
- "value": "{event.properties.value}",
-}
+from products.alerts_platform.backend.facade.contracts import AlertEventKind, DestinationType, IncidentAction
-_FIRING = EventKindSpec(
- event_id="$metrics_alert_firing",
- display_kind="firing",
- header="🔴 Metric alert '{event.properties.alert_name}' is firing",
- details=(("Query", "{event.properties.query}"), ("Value", "{event.properties.value}")),
- primary_action_url=_METRICS_URL,
- primary_action_label="View in PostHog",
- webhook_body={
- "id": "{event.uuid}",
- "type": "metrics_alert.firing",
- "timestamp": "{event.properties.triggered_at}",
- "data": _DATA,
- },
- product_label=_PRODUCT_LABEL,
+METRICS_ALERT_DESTINATION_TYPES: Final = (
+ DestinationType.SLACK,
+ DestinationType.WEBHOOK,
+ DestinationType.TEAMS,
+ DestinationType.DISCORD,
+ DestinationType.PAGERDUTY,
)
-EVENT_KIND_CONFIG: Final[dict[EventKind, EventKindSpec]] = {
- "firing": _FIRING,
- "resolved": replace(
- _FIRING,
- event_id="$metrics_alert_resolved",
- display_kind="resolved",
- header="🟢 Metric alert '{event.properties.alert_name}' is resolved",
- webhook_body={**_FIRING.webhook_body, "type": "metrics_alert.resolved"},
- ),
- "errored": replace(
- _FIRING,
- event_id="$metrics_alert_errored",
- display_kind="errored",
- header="🟡 Metric alert '{event.properties.alert_name}' could not be checked",
- details=(("Reason", "{event.properties.error_message}"),),
- webhook_body={**_FIRING.webhook_body, "type": "metrics_alert.errored"},
- ),
- "broken": replace(
- _FIRING,
- event_id="$metrics_alert_broken",
- display_kind="turned off",
- header="⚠️ Metric alert '{event.properties.alert_name}' is turned off",
- details=(("Reason", "{event.properties.error_message}"),),
- webhook_body={**_FIRING.webhook_body, "type": "metrics_alert.broken"},
- ),
- # The edge kinds follow every move into and out of FIRING, whatever cooldown decided. An
- # incident manager needs a resolve for every trigger, or the incident it opened stays open.
- "incident_opened": replace(
- _FIRING,
- event_id="$metrics_alert_incident_opened",
- display_kind="incident opened",
- webhook_body={},
- additional_actions=(AlertDestinationAction(url=_METRICS_URL, label="View in PostHog"),),
- incident_action=IncidentAction.TRIGGER,
- ),
- "incident_closed": replace(
- _FIRING,
- event_id="$metrics_alert_incident_closed",
- display_kind="incident closed",
- header="Metric alert '{event.properties.alert_name}' stopped firing",
- details=(("Reason", "{event.properties.reason}"),),
- webhook_body={},
- incident_action=IncidentAction.RESOLVE,
- ),
-}
-
-EVENT_IDS: Final[tuple[str, ...]] = tuple(spec.event_id for spec in EVENT_KIND_CONFIG.values())
-
-# Which event id each announced kind's destinations filter on. Resolved here because the platform
-# imports no source.
+# The event id each announced kind travels under. Resolved here because the platform imports no source.
EVENT_IDS_BY_KIND: Final[dict[str, str]] = {
- key: spec.event_id for key, spec in EVENT_KIND_CONFIG.items() if key in set(AlertEventKind)
+ AlertEventKind.FIRING.value: "$metrics_alert_firing",
+ AlertEventKind.RESOLVED.value: "$metrics_alert_resolved",
+ AlertEventKind.ERRORED.value: "$metrics_alert_errored",
+ AlertEventKind.BROKEN.value: "$metrics_alert_broken",
}
+# The event id each incident action travels under. An incident follows every move into and out of
+# FIRING, whatever cooldown decided, so an incident manager gets a resolve for every trigger.
EVENT_IDS_BY_INCIDENT_ACTION: Final[dict[str, str]] = {
- spec.incident_action.value: spec.event_id for spec in EVENT_KIND_CONFIG.values() if spec.incident_action
+ IncidentAction.TRIGGER.value: "$metrics_alert_incident_opened",
+ IncidentAction.RESOLVE.value: "$metrics_alert_incident_closed",
}
diff --git a/products/metrics/backend/alerts/evaluation.py b/products/metrics/backend/alerts/evaluation.py
index d1dc1a647dce..392a37c6a4bd 100644
--- a/products/metrics/backend/alerts/evaluation.py
+++ b/products/metrics/backend/alerts/evaluation.py
@@ -35,8 +35,7 @@ from posthog.dataclasses import frozen
from posthog.models import Team
from posthog.temporal.alerts.admission import hold_evaluation_slot, release_evaluation_slot
-from products.alerts.backend.facade.destinations import configured_destination_template_ids
-from products.alerts_platform.backend.facade.api import due_checks, slot_of
+from products.alerts_platform.backend.facade.api import due_checks, has_incident_destination, slot_of
from products.alerts_platform.backend.facade.contracts import (
AlertDeliveryRequest,
GroupingMode,
@@ -424,17 +423,12 @@ def _request(
A firing that opens or closes needs a delivery even when cooldown or mute held the message,
because a paging destination needs one resolve for every trigger.
"""
- destination_alert_id = str(check.destination_alert_id)
actions = {
key: action
for key, (before, after) in moves.items()
if (action := decide_incident_action(before, after, policy=POLICY)) is not None
}
- if actions and not configured_destination_template_ids(
- team_id=check.team_id,
- alert_id=destination_alert_id,
- allowed_event_ids=tuple(EVENT_IDS_BY_INCIDENT_ACTION.values()),
- ):
+ if actions and not has_incident_destination(team_id=check.team_id, configuration_id=check.id):
actions = {}
if not sends_messages and not actions:
return None
@@ -443,7 +437,7 @@ def _request(
team_id=check.team_id,
configuration_id=str(check.id),
evaluation_key=recorded.evaluation_key,
- destination_alert_id=destination_alert_id,
+ destination_alert_id=str(check.destination_alert_id),
event_ids_by_kind=EVENT_IDS_BY_KIND,
event_ids_by_incident_action=EVENT_IDS_BY_INCIDENT_ACTION,
incident_actions=actions,
diff --git a/products/metrics/backend/alerts/source_config.py b/products/metrics/backend/alerts/source_config.py
index 3ca751c67bd3..3b678f6f2040 100644
--- a/products/metrics/backend/alerts/source_config.py
+++ b/products/metrics/backend/alerts/source_config.py
@@ -1,21 +1,19 @@
"""The `source_config` of a metrics alert on the alerts platform, and its native lifecycle.
A metrics alert has no row of its own in this product. The platform creates and deletes it, and its
-configuration id is the id its destinations match on.
+destinations are `AlertDestination` rows that go with it.
"""
from typing import Final, Literal, Self
-from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, model_validator
-from products.alerts.backend.facade.destinations import soft_delete_all_alert_destinations
from products.alerts_platform.backend.facade.contracts import (
NativeAlertLifecycle,
PlatformAlertConfigurationEdit,
SourceConfigSpec,
)
-from products.metrics.backend.alerts.destinations import EVENT_IDS, EVENT_IDS_BY_INCIDENT_ACTION
+from products.metrics.backend.alerts.destinations import EVENT_IDS_BY_INCIDENT_ACTION
from products.metrics.backend.alerts.wording import alert_url
# A metrics alert checks the latest value of each series, so it runs as often as the platform allows.
@@ -68,16 +66,11 @@ def _validate_edit(edit: PlatformAlertConfigurationEdit) -> None:
return None
-def _remove_destinations(*, team_id: int, configuration_id: UUID) -> None:
- soft_delete_all_alert_destinations(team_id=team_id, alert_id=str(configuration_id), allowed_event_ids=EVENT_IDS)
-
-
METRICS_ALERT_CONFIG: Final = SourceConfigSpec(
model=MetricsPlatformAlertConfig,
validate=_validate_edit,
- native=NativeAlertLifecycle(
- check_interval_minutes=CHECK_INTERVAL_MINUTES, remove_destinations=_remove_destinations
- ),
+ # No `remove_destinations`, so the alert's destinations are `AlertDestination` rows from the start.
+ native=NativeAlertLifecycle(check_interval_minutes=CHECK_INTERVAL_MINUTES),
incident_event_ids=EVENT_IDS_BY_INCIDENT_ACTION,
alert_url=alert_url,
rollout_flag="platform-alerts-source-metrics",
diff --git a/products/metrics/backend/facade/alerts.py b/products/metrics/backend/facade/alerts.py
new file mode 100644
index 000000000000..54d4c06082a7
--- /dev/null
+++ b/products/metrics/backend/facade/alerts.py
@@ -0,0 +1,5 @@
+"""Metrics alert destination vocabulary for the metrics presentation endpoints."""
+
+from products.metrics.backend.alerts.destinations import METRICS_ALERT_DESTINATION_TYPES
+
+__all__ = ["METRICS_ALERT_DESTINATION_TYPES"]
diff --git a/products/metrics/backend/presentation/alert_destinations_api.py b/products/metrics/backend/presentation/alert_destinations_api.py
new file mode 100644
index 000000000000..4f3741ffdd3f
--- /dev/null
+++ b/products/metrics/backend/presentation/alert_destinations_api.py
@@ -0,0 +1,338 @@
+"""Notification destinations of a metrics alert on the alerts platform.
+
+The alert itself is created, edited and deleted through the platform API (`platform_alerts`). Its
+destinations are `AlertDestination` rows the platform delivers to, managed here with the metrics
+access rules.
+"""
+
+from typing import Any, Literal, cast
+from uuid import UUID
+
+from django.db import models, transaction
+
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from rest_framework import serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
+from rest_framework.permissions import SAFE_METHODS
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.event_usage import report_user_action
+from posthog.exceptions import Conflict, as_drf_validation_error
+from posthog.integrations import IntegrationManager
+from posthog.models import User
+from posthog.models.integration import SLACK_INTEGRATION_KINDS
+from posthog.permissions import PostHogFeatureFlagPermission
+
+from products.alerts.backend.facade.destinations import (
+ MAX_DESTINATION_IDS_PER_DELETE_REQUEST,
+ MAX_DESTINATIONS_PER_ALERT,
+ redact_destination_data,
+ validate_destination_data,
+)
+from products.alerts_platform.backend.facade.api import (
+ create_alert_destinations,
+ delete_alert_destinations,
+ get_configuration,
+ list_alert_destinations,
+)
+from products.alerts_platform.backend.facade.contracts import (
+ AlertDestinationData,
+ AlertDestinationValidationError,
+ AlertEventKind,
+ DestinationType,
+ NewAlertDestination,
+ PagerDutyRegion,
+ PagerDutySeverity,
+ PlatformAlertConfigurationView,
+ SourceKind,
+ StoredAlertDestination,
+)
+from products.alerts_platform.backend.facade.delivery import refused_destination
+from products.alerts_platform.backend.facade.enums import PlatformAlertOwner
+from products.metrics.backend.facade.alerts import METRICS_ALERT_DESTINATION_TYPES
+
+METRICS_ALERT_KINDS = (SourceKind.METRICS.value,)
+# The metrics an alert queries are gated by the same resource as the metrics scene.
+METRICS_RESOURCE: Literal["metrics"] = "metrics"
+# What a destination hears when the request names no kinds. An incident manager hears the trigger and
+# resolve of every firing, which delivery sends it for firing and resolved.
+_DEFAULT_EVENT_KINDS: dict[DestinationType, tuple[AlertEventKind, ...]] = {
+ DestinationType.PAGERDUTY: (AlertEventKind.FIRING, AlertEventKind.RESOLVED),
+}
+_MESSAGE_EVENT_KINDS = (AlertEventKind.FIRING, AlertEventKind.RESOLVED, AlertEventKind.ERRORED, AlertEventKind.BROKEN)
+_WEBHOOK_FIELDS = ("webhook_url",)
+# The fields each type stores. Redaction knows only its own type's credential, so a field of another
+# type would be stored and then shown in full.
+_FIELDS_BY_TYPE: dict[DestinationType, tuple[str, ...]] = {
+ DestinationType.SLACK: ("slack_workspace_id", "slack_channel_id", "slack_channel_name"),
+ DestinationType.WEBHOOK: _WEBHOOK_FIELDS,
+ DestinationType.TEAMS: _WEBHOOK_FIELDS,
+ DestinationType.DISCORD: _WEBHOOK_FIELDS,
+ DestinationType.PAGERDUTY: ("pagerduty_routing_key", "pagerduty_severity", "pagerduty_region"),
+}
+# Choices classes for the serializers below. TextChoices supports this functional API at runtime, but
+# its type stubs only describe member construction. The destination types carry their display labels,
+# so the OpenAPI enum is named after this class (MetricsAlertDestinationTypeEnum). The others keep
+# label equal to value, so they share the names their ENUM_NAME_OVERRIDES entries give them.
+MetricsAlertDestinationType = cast(Any, models.TextChoices)(
+ "MetricsAlertDestinationType",
+ [(member.name, (member.value, member.label)) for member in METRICS_ALERT_DESTINATION_TYPES],
+)
+PagerDutySeverityChoices = cast(Any, models.TextChoices)(
+ "PagerDutySeverityChoices", [(member.name, (member.value, member.value)) for member in PagerDutySeverity]
+)
+PagerDutyRegionChoices = cast(Any, models.TextChoices)(
+ "PagerDutyRegionChoices", [(member.name, (member.value, member.value)) for member in PagerDutyRegion]
+)
+MetricsAlertDestinationEventKind = cast(Any, models.TextChoices)(
+ "MetricsAlertDestinationEventKind",
+ [(member.name, (member.value, member.value)) for member in _MESSAGE_EVENT_KINDS],
+)
+
+
+class MetricsAlertDestinationSerializer(serializers.Serializer):
+ id = serializers.UUIDField(help_text="ID of the destination. Send it to the delete endpoint to remove it.")
+ type = serializers.ChoiceField(
+ choices=MetricsAlertDestinationType.choices, help_text="Notification destination type."
+ )
+ enabled = serializers.BooleanField(help_text="Whether the destination is sent to.")
+ event_kinds = serializers.ListField(
+ child=serializers.ChoiceField(choices=MetricsAlertDestinationEventKind.choices),
+ help_text="The alert transitions the destination hears about. A PagerDuty destination hears the incident "
+ "trigger and resolve of every firing.",
+ )
+ slack_workspace_id = serializers.IntegerField(
+ required=False, help_text="Integration ID of the Slack workspace. Set when type=slack."
+ )
+ slack_channel_id = serializers.CharField(required=False, help_text="Slack channel ID. Set when type=slack.")
+ slack_channel_name = serializers.CharField(
+ required=False, help_text="Human-readable Slack channel name. Set when type=slack."
+ )
+ webhook_url = serializers.CharField(
+ required=False,
+ help_text="Webhook endpoint reduced to scheme and host. The path, query and userinfo carry the secret.",
+ )
+ pagerduty_routing_key = serializers.CharField(
+ required=False, help_text="PagerDuty integration key reduced to its last four characters."
+ )
+ pagerduty_severity = serializers.ChoiceField(
+ choices=PagerDutySeverityChoices.choices,
+ required=False,
+ help_text="Severity of the PagerDuty incident.",
+ )
+ pagerduty_region = serializers.ChoiceField(
+ choices=PagerDutyRegionChoices.choices,
+ required=False,
+ help_text="PagerDuty service region the events go to.",
+ )
+
+
+class MetricsAlertCreateDestinationSerializer(serializers.Serializer):
+ type = serializers.ChoiceField(
+ choices=MetricsAlertDestinationType.choices, help_text="Notification destination type."
+ )
+ slack_workspace_id = serializers.IntegerField(
+ required=False, help_text="Integration ID for the Slack workspace. Required when type=slack."
+ )
+ slack_channel_id = serializers.CharField(required=False, help_text="Slack channel ID. Required when type=slack.")
+ slack_channel_name = serializers.CharField(
+ required=False, allow_blank=True, help_text="Human-readable channel name for display."
+ )
+ webhook_url = serializers.URLField(
+ required=False, help_text="HTTPS endpoint to post to. Required for webhook, teams and discord."
+ )
+ pagerduty_routing_key = serializers.CharField(
+ required=False,
+ trim_whitespace=True,
+ help_text="Integration key of a PagerDuty Events API v2 integration. Required when type=pagerduty.",
+ )
+ pagerduty_severity = serializers.ChoiceField(
+ choices=PagerDutySeverityChoices.choices,
+ required=False,
+ default=PagerDutySeverity.CRITICAL.value,
+ help_text="Severity PagerDuty records on the incident. Used when type=pagerduty.",
+ )
+ pagerduty_region = serializers.ChoiceField(
+ choices=PagerDutyRegionChoices.choices,
+ required=False,
+ default=PagerDutyRegion.US.value,
+ help_text="PagerDuty service region of the account. Used when type=pagerduty.",
+ )
+ event_kinds = serializers.ListField(
+ child=serializers.ChoiceField(choices=MetricsAlertDestinationEventKind.choices),
+ required=False,
+ min_length=1,
+ help_text="The alert transitions to send about. Defaults to every kind, or to firing and resolved for "
+ "PagerDuty, which then hears each incident's trigger and resolve.",
+ )
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ destination_type = DestinationType(attrs["type"])
+ # The PagerDuty fields have defaults, so they arrive for every type. Each type keeps only its own.
+ data = cast(
+ AlertDestinationData,
+ {key: attrs[key] for key in _FIELDS_BY_TYPE[destination_type] if key in attrs},
+ )
+ data["type"] = destination_type
+ try:
+ validate_destination_data(data, allowed_destination_types=METRICS_ALERT_DESTINATION_TYPES)
+ except AlertDestinationValidationError as error:
+ raise as_drf_validation_error(error)
+ # A destination native delivery would refuse is saved and then never notifies, so refuse it here.
+ if refusal := refused_destination(data):
+ raise ValidationError({"webhook_url": refusal} if data.get("webhook_url") is not None else refusal)
+ kinds = attrs.get("event_kinds") or _DEFAULT_EVENT_KINDS.get(data["type"], _MESSAGE_EVENT_KINDS)
+ return {"data": data, "event_kinds": tuple(AlertEventKind(kind) for kind in kinds)}
+
+
+class MetricsAlertDeleteDestinationSerializer(serializers.Serializer):
+ destination_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ min_length=1,
+ max_length=MAX_DESTINATION_IDS_PER_DELETE_REQUEST,
+ help_text="IDs of the destinations to delete, as the list endpoint returns them.",
+ )
+
+
+def _serialized(destination: StoredAlertDestination) -> dict[str, Any]:
+ return {
+ "id": destination.id,
+ "enabled": destination.enabled,
+ "event_kinds": [kind.value for kind in destination.event_kinds],
+ **redact_destination_data(destination.data),
+ }
+
+
+class MetricsAlertDestinationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """Destinations of a metrics alert. The URL's ID is the alert's platform configuration ID."""
+
+ scope_object = "alert"
+ posthog_feature_flag = "platform-alerts"
+ permission_classes = [PostHogFeatureFlagPermission]
+
+ def dangerously_get_required_scopes(self, request: Request, view: APIView) -> list[str]:
+ # A destination exposes the metrics alert it belongs to, so a key needs the metrics scope too.
+ access = "read" if request.method in SAFE_METHODS else "write"
+ return [f"alert:{access}", f"{METRICS_RESOURCE}:{access}"]
+
+ def _alert(self, pk: str) -> PlatformAlertConfigurationView:
+ level: Literal["viewer", "editor"] = "viewer" if self.request.method in SAFE_METHODS else "editor"
+ if not self.user_access_control.check_access_level_for_resource(METRICS_RESOURCE, level):
+ raise PermissionDenied("You don't have access to metrics in this project.")
+ alert = get_configuration(
+ team_id=self.team_id,
+ source_kinds=METRICS_ALERT_KINDS,
+ configuration_id=serializers.UUIDField().run_validation(pk),
+ )
+ if alert is None:
+ raise NotFound()
+ if alert.owner != PlatformAlertOwner.PLATFORM:
+ raise Conflict("This alert has no destinations to manage here.")
+ return alert
+
+ @extend_schema(
+ responses={200: MetricsAlertDestinationSerializer(many=True)},
+ description="List the notification destinations of a metrics alert.",
+ )
+ @action(detail=True, methods=["GET"], url_path="destinations", pagination_class=None)
+ def destinations(self, request: Request, pk: str, **kwargs: Any) -> Response:
+ alert = self._alert(pk)
+ destinations = list_alert_destinations(team_id=self.team_id, configuration_id=alert.id)
+ return Response(MetricsAlertDestinationSerializer([_serialized(d) for d in destinations], many=True).data)
+
+ @extend_schema(
+ request=MetricsAlertCreateDestinationSerializer,
+ responses={
+ 201: MetricsAlertDestinationSerializer,
+ 400: OpenApiResponse(description="The destination settings are invalid."),
+ },
+ description=(
+ "Add a notification destination to a metrics alert. It hears the transitions in `event_kinds`. "
+ "A PagerDuty destination opens an incident when the alert fires and resolves it when the alert resolves."
+ ),
+ )
+ @destinations.mapping.post
+ def create_destination(self, request: Request, pk: str, **kwargs: Any) -> Response:
+ alert = self._alert(pk)
+ serializer = MetricsAlertCreateDestinationSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = cast(AlertDestinationData, serializer.validated_data["data"])
+ event_kinds: tuple[AlertEventKind, ...] = serializer.validated_data["event_kinds"]
+ # Native delivery looks the workspace up by team and kind, so a destination naming any other
+ # integration would be saved and never notify.
+ if data["type"] == DestinationType.SLACK and data["slack_workspace_id"] not in IntegrationManager.kinds(
+ *SLACK_INTEGRATION_KINDS, auth_types="any"
+ ).get_many(self.team_id, [data["slack_workspace_id"]]):
+ raise ValidationError({"slack_workspace_id": "Choose a Slack workspace connected to this project."})
+ try:
+ with transaction.atomic():
+ # The alert's row stays locked until the destinations commit. A delete that got there
+ # first leaves no row, and one that comes later waits, then removes these destinations too.
+ if (
+ get_configuration(
+ team_id=self.team_id,
+ source_kinds=METRICS_ALERT_KINDS,
+ configuration_id=alert.id,
+ lock=True,
+ )
+ is None
+ ):
+ raise NotFound()
+ # Each destination is another message every time the alert fires, so one alert has only a few.
+ existing = list_alert_destinations(team_id=self.team_id, configuration_id=alert.id)
+ if len(existing) >= MAX_DESTINATIONS_PER_ALERT:
+ raise ValidationError(
+ f"This alert already has {MAX_DESTINATIONS_PER_ALERT} destinations. Remove one to add another."
+ )
+ (created,) = create_alert_destinations(
+ team_id=self.team_id,
+ configuration_id=alert.id,
+ destinations=(NewAlertDestination(data=data, event_kinds=event_kinds),),
+ )
+ except AlertDestinationValidationError as error:
+ raise as_drf_validation_error(error)
+
+ # Robust, so an analytics failure, such as a malformed Referer, cannot fail a create that committed.
+ transaction.on_commit(
+ lambda: self._track(
+ "created",
+ {"alert_id": str(alert.id), "type": data["type"], "event_kinds": [kind.value for kind in event_kinds]},
+ ),
+ robust=True,
+ )
+ return Response(MetricsAlertDestinationSerializer(_serialized(created)).data, status=status.HTTP_201_CREATED)
+
+ @extend_schema(
+ request=MetricsAlertDeleteDestinationSerializer,
+ responses={
+ 204: OpenApiResponse(description="The destinations are deleted. An ID of another alert is ignored."),
+ },
+ description="Delete notification destinations of a metrics alert.",
+ )
+ @action(detail=True, methods=["POST"], url_path="destinations/delete")
+ def delete_destination(self, request: Request, pk: str, **kwargs: Any) -> Response:
+ alert = self._alert(pk)
+ serializer = MetricsAlertDeleteDestinationSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ destination_ids: list[UUID] = serializer.validated_data["destination_ids"]
+ deleted = delete_alert_destinations(
+ team_id=self.team_id, configuration_id=alert.id, destination_ids=destination_ids
+ )
+
+ transaction.on_commit(
+ lambda: self._track("deleted", {"alert_id": str(alert.id), "count": deleted}), robust=True
+ )
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+ def _track(self, action: Literal["created", "deleted"], properties: dict[str, Any]) -> None:
+ report_user_action(
+ cast(User, self.request.user),
+ f"metrics alert destination {action}",
+ properties,
+ team=self.team,
+ request=self.request,
+ )
diff --git a/products/metrics/backend/routes.py b/products/metrics/backend/routes.py
index bb87d3a53417..2d71543d9f44 100644
--- a/products/metrics/backend/routes.py
+++ b/products/metrics/backend/routes.py
@@ -1,5 +1,6 @@
from posthog.api.routing import RouterRegistry
+from products.metrics.backend.presentation.alert_destinations_api import MetricsAlertDestinationViewSet
from products.metrics.backend.presentation.api import MetricsViewSet
from products.metrics.backend.presentation.dashboard_import_api import MetricsDashboardImportViewSet
from products.metrics.backend.presentation.prometheus_api import PrometheusQueryViewSet
@@ -30,3 +31,4 @@ def register_routes(routers: RouterRegistry) -> None:
"project_metrics_dashboard_templates",
["team_id"],
)
+ routers.projects.register(r"metrics_alerts", MetricsAlertDestinationViewSet, "project_metrics_alerts", ["team_id"])
diff --git a/products/metrics/backend/tests/test_alerts.py b/products/metrics/backend/tests/test_alerts.py
index 0f4c764b8d51..2fe4b835c4e8 100644
--- a/products/metrics/backend/tests/test_alerts.py
+++ b/products/metrics/backend/tests/test_alerts.py
@@ -16,17 +16,25 @@ from pydantic import ValidationError
from rest_framework import status
from posthog.models import Team
+from posthog.models.integration import Integration
from posthog.models.scoping import team_scope
from posthog.temporal.alerts.admission import hold_evaluation_slot, release_evaluation_slot
from products.alerts_platform.backend.facade import testing as platform_testing
-from products.alerts_platform.backend.facade.api import create_configuration, record_outcomes, slot_of
+from products.alerts_platform.backend.facade.api import (
+ create_configuration,
+ list_alert_destinations,
+ record_outcomes,
+ slot_of,
+)
from products.alerts_platform.backend.facade.contracts import (
AlertEventKind,
Grouping,
GroupingMode,
+ IncidentAction,
PlatformAlertConfigurationEdit,
PlatformAlertOutcome,
+ SourceBatchEvaluation,
SourceKind,
)
from products.metrics.backend.alerts.evaluation import ABSENT_RESOLVE_AFTER, INFLIGHT_KEY, evaluate_metrics_alert_batch
@@ -154,6 +162,7 @@ class TestMetricsAlertEvaluation(APIBaseTest):
def setUp(self) -> None:
super().setUp()
self.cutoff = timezone.now().replace(second=0, microsecond=0) + timedelta(minutes=5)
+ self.enterContext(patch("posthoganalytics.feature_enabled", return_value=True))
self.snuffle = MagicMock()
self.enterContext(patch("products.metrics.backend.promql.snuffle_request", self.snuffle))
self.freshness = self.enterContext(
@@ -181,10 +190,12 @@ class TestMetricsAlertEvaluation(APIBaseTest):
def due_at(self) -> datetime:
return self.cutoff - timedelta(minutes=1)
- def _evaluate(self) -> PlatformAlertOutcome:
+ def _evaluate_batch(self) -> SourceBatchEvaluation:
with team_scope(self.team.id):
- evaluation = evaluate_metrics_alert_batch(self.team.id, slot_of(self.due_at, self.cutoff), self.cutoff)
- (outcome,) = evaluation.outcomes
+ return evaluate_metrics_alert_batch(self.team.id, slot_of(self.due_at, self.cutoff), self.cutoff)
+
+ def _evaluate(self) -> PlatformAlertOutcome:
+ (outcome,) = self._evaluate_batch().outcomes
return outcome
def _next_check(self, outcome: PlatformAlertOutcome) -> None:
@@ -293,3 +304,90 @@ class TestMetricsAlertEvaluation(APIBaseTest):
UUID(str(self.configuration_id)),
consecutive_failures,
)
+
+ def test_destinations_are_alert_destination_rows_that_the_firing_reaches(self) -> None:
+ workspace = Integration.objects.create(team=self.team, kind="slack", config={}, sensitive_config={})
+ destinations_url = f"/api/projects/{self.team.id}/metrics_alerts/{self.configuration_id}/destinations/"
+ slack = self.client.post(
+ destinations_url,
+ {
+ "type": "slack",
+ "slack_workspace_id": workspace.id,
+ "slack_channel_id": "C123",
+ "webhook_url": "https://example.com/hooks/secret-token",
+ },
+ format="json",
+ )
+ with self.captureOnCommitCallbacks(execute=True):
+ pagerduty = self.client.post(
+ destinations_url,
+ {"type": "pagerduty", "pagerduty_routing_key": "0123456789abcdef0123456789abcdef"},
+ format="json",
+ HTTP_REFERER="https://[",
+ )
+ assert slack.status_code == pagerduty.status_code == status.HTTP_201_CREATED, (slack.json(), pagerduty.json())
+ assert (slack.json()["event_kinds"], pagerduty.json()["event_kinds"]) == (
+ ["firing", "resolved", "errored", "broken"],
+ ["firing", "resolved"],
+ )
+ listed = self.client.get(destinations_url).json()
+ assert [d["id"] for d in listed] == [slack.json()["id"], pagerduty.json()["id"]]
+ with team_scope(self.team.id):
+ stored = list_alert_destinations(team_id=self.team.id, configuration_id=self.configuration_id)
+ assert [sorted(d.data) for d in stored] == [
+ ["slack_channel_id", "slack_workspace_id", "type"],
+ ["pagerduty_region", "pagerduty_routing_key", "pagerduty_severity", "type"],
+ ]
+
+ self.snuffle.return_value = _response(200, _vector(({"group": "a"}, "2000")))
+ (delivery,) = self._evaluate_batch().deliveries
+ assert delivery.sends_messages
+ assert list(delivery.incident_actions.values()) == [IncidentAction.TRIGGER]
+
+ removed = self.client.post(
+ f"{destinations_url}delete/", {"destination_ids": [slack.json()["id"]]}, format="json"
+ )
+ assert removed.status_code == status.HTTP_204_NO_CONTENT
+ assert [d["type"] for d in self.client.get(destinations_url).json()] == ["pagerduty"]
+ deleted = self.client.delete(f"/api/projects/{self.team.id}/platform_alerts/{self.configuration_id}/")
+ assert deleted.status_code == status.HTTP_204_NO_CONTENT
+ with team_scope(self.team.id):
+ assert list_alert_destinations(team_id=self.team.id, configuration_id=self.configuration_id) == ()
+
+ @parameterized.expand(
+ [
+ ("alert_only", ["alert:read"], status.HTTP_403_FORBIDDEN),
+ ("metrics_only", ["metrics:read"], status.HTTP_403_FORBIDDEN),
+ ("alert_and_metrics", ["alert:read", "metrics:read"], status.HTTP_200_OK),
+ ]
+ )
+ def test_reading_destinations_needs_both_alert_and_metrics_scopes(
+ self, _name: str, scopes: list[str], expected: int
+ ) -> None:
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {self.create_personal_api_key_with_scopes(scopes)}")
+
+ response = self.client.get(f"/api/projects/{self.team.id}/metrics_alerts/{self.configuration_id}/destinations/")
+
+ assert response.status_code == expected, response.json()
+
+ @parameterized.expand(
+ [
+ ("http_webhook", {"type": "webhook", "webhook_url": "http://example.com/alerts"}, "webhook_url"),
+ ("teams_url_not_from_teams", {"type": "teams", "webhook_url": "https://example.com/alerts"}, "webhook_url"),
+ (
+ "unconnected_slack_workspace",
+ {"type": "slack", "slack_workspace_id": 999999, "slack_channel_id": "C123"},
+ "slack_workspace_id",
+ ),
+ ]
+ )
+ def test_a_destination_that_could_never_deliver_is_refused(
+ self, _name: str, body: dict[str, object], field: str
+ ) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/metrics_alerts/{self.configuration_id}/destinations/", body, format="json"
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == field
diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.ts
index 9fd8b41dcd4c..7e6434799400 100644
--- a/products/metrics/frontend/generated/api.schemas.ts
+++ b/products/metrics/frontend/generated/api.schemas.ts
@@ -1310,6 +1310,152 @@ export interface _MetricVariableOptionsResponseApi {
results: string[]
}
+/**
+ * * `slack` - Slack
+ * * `webhook` - Webhook
+ * * `teams` - Microsoft Teams
+ * * `discord` - Discord
+ * * `pagerduty` - PagerDuty
+ */
+export type MetricsAlertDestinationTypeEnumApi =
+ (typeof MetricsAlertDestinationTypeEnumApi)[keyof typeof MetricsAlertDestinationTypeEnumApi]
+
+export const MetricsAlertDestinationTypeEnumApi = {
+ Slack: 'slack',
+ Webhook: 'webhook',
+ Teams: 'teams',
+ Discord: 'discord',
+ Pagerduty: 'pagerduty',
+} as const
+
+/**
+ * * `firing` - firing
+ * * `resolved` - resolved
+ * * `errored` - errored
+ * * `broken` - broken
+ */
+export type MetricsAlertDestinationEventKindEnumApi =
+ (typeof MetricsAlertDestinationEventKindEnumApi)[keyof typeof MetricsAlertDestinationEventKindEnumApi]
+
+export const MetricsAlertDestinationEventKindEnumApi = {
+ Firing: 'firing',
+ Resolved: 'resolved',
+ Errored: 'errored',
+ Broken: 'broken',
+} as const
+
+/**
+ * * `critical` - critical
+ * * `error` - error
+ * * `warning` - warning
+ * * `info` - info
+ */
+export type PagerDutySeverityEnumApi = (typeof PagerDutySeverityEnumApi)[keyof typeof PagerDutySeverityEnumApi]
+
+export const PagerDutySeverityEnumApi = {
+ Critical: 'critical',
+ Error: 'error',
+ Warning: 'warning',
+ Info: 'info',
+} as const
+
+/**
+ * * `us` - us
+ * * `eu` - eu
+ */
+export type PagerDutyRegionEnumApi = (typeof PagerDutyRegionEnumApi)[keyof typeof PagerDutyRegionEnumApi]
+
+export const PagerDutyRegionEnumApi = {
+ Us: 'us',
+ Eu: 'eu',
+} as const
+
+export interface MetricsAlertDestinationApi {
+ /** ID of the destination. Send it to the delete endpoint to remove it. */
+ id: string
+ /** Notification destination type.
+ *
+ * * `slack` - Slack
+ * * `webhook` - Webhook
+ * * `teams` - Microsoft Teams
+ * * `discord` - Discord
+ * * `pagerduty` - PagerDuty */
+ type: MetricsAlertDestinationTypeEnumApi
+ /** Whether the destination is sent to. */
+ enabled: boolean
+ /** The alert transitions the destination hears about. A PagerDuty destination hears the incident trigger and resolve of every firing. */
+ event_kinds: MetricsAlertDestinationEventKindEnumApi[]
+ /** Integration ID of the Slack workspace. Set when type=slack. */
+ slack_workspace_id?: number
+ /** Slack channel ID. Set when type=slack. */
+ slack_channel_id?: string
+ /** Human-readable Slack channel name. Set when type=slack. */
+ slack_channel_name?: string
+ /** Webhook endpoint reduced to scheme and host. The path, query and userinfo carry the secret. */
+ webhook_url?: string
+ /** PagerDuty integration key reduced to its last four characters. */
+ pagerduty_routing_key?: string
+ /** Severity of the PagerDuty incident.
+ *
+ * * `critical` - critical
+ * * `error` - error
+ * * `warning` - warning
+ * * `info` - info */
+ pagerduty_severity?: PagerDutySeverityEnumApi
+ /** PagerDuty service region the events go to.
+ *
+ * * `us` - us
+ * * `eu` - eu */
+ pagerduty_region?: PagerDutyRegionEnumApi
+}
+
+export interface MetricsAlertCreateDestinationApi {
+ /** Notification destination type.
+ *
+ * * `slack` - Slack
+ * * `webhook` - Webhook
+ * * `teams` - Microsoft Teams
+ * * `discord` - Discord
+ * * `pagerduty` - PagerDuty */
+ type: MetricsAlertDestinationTypeEnumApi
+ /** Integration ID for the Slack workspace. Required when type=slack. */
+ slack_workspace_id?: number
+ /** Slack channel ID. Required when type=slack. */
+ slack_channel_id?: string
+ /** Human-readable channel name for display. */
+ slack_channel_name?: string
+ /** HTTPS endpoint to post to. Required for webhook, teams and discord. */
+ webhook_url?: string
+ /** Integration key of a PagerDuty Events API v2 integration. Required when type=pagerduty. */
+ pagerduty_routing_key?: string
+ /** Severity PagerDuty records on the incident. Used when type=pagerduty.
+ *
+ * * `critical` - critical
+ * * `error` - error
+ * * `warning` - warning
+ * * `info` - info */
+ pagerduty_severity?: PagerDutySeverityEnumApi
+ /** PagerDuty service region of the account. Used when type=pagerduty.
+ *
+ * * `us` - us
+ * * `eu` - eu */
+ pagerduty_region?: PagerDutyRegionEnumApi
+ /**
+ * The alert transitions to send about. Defaults to every kind, or to firing and resolved for PagerDuty, which then hears each incident's trigger and resolve.
+ * @minItems 1
+ */
+ event_kinds?: MetricsAlertDestinationEventKindEnumApi[]
+}
+
+export interface MetricsAlertDeleteDestinationApi {
+ /**
+ * IDs of the destinations to delete, as the list endpoint returns them.
+ * @minItems 1
+ * @maxItems 100
+ */
+ destination_ids: string[]
+}
+
export type MetricsAttributeValuesRetrieveParams = {
/**
* Lower bound (inclusive) of the window values are suggested from. ISO 8601. Defaults to 24 hours ago.
diff --git a/products/metrics/frontend/generated/api.ts b/products/metrics/frontend/generated/api.ts
index 095bbba83ff8..d9a9bb97cc98 100644
--- a/products/metrics/frontend/generated/api.ts
+++ b/products/metrics/frontend/generated/api.ts
@@ -13,6 +13,9 @@ import type {
AppMetricsTotalsResponseApi,
DashboardImportApi,
DashboardImportCreateApi,
+ MetricsAlertCreateDestinationApi,
+ MetricsAlertDeleteDestinationApi,
+ MetricsAlertDestinationApi,
MetricsAttributeValuesRetrieveParams,
MetricsAttributesRetrieveParams,
MetricsCreatedDashboardApi,
@@ -661,3 +664,63 @@ export const metricsVariableOptionsCreate = async (
body: JSON.stringify(_metricVariableOptionsRequestApi),
})
}
+
+export const getMetricsAlertsDestinationsListUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/metrics_alerts/${id}/destinations/`
+}
+
+/**
+ * List the notification destinations of a metrics alert.
+ */
+export const metricsAlertsDestinationsList = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<MetricsAlertDestinationApi[]> => {
+ return apiMutator<MetricsAlertDestinationApi[]>(getMetricsAlertsDestinationsListUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getMetricsAlertsDestinationsCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/metrics_alerts/${id}/destinations/`
+}
+
+/**
+ * Add a notification destination to a metrics alert. It hears the transitions in `event_kinds`. A PagerDuty destination opens an incident when the alert fires and resolves it when the alert resolves.
+ */
+export const metricsAlertsDestinationsCreate = async (
+ projectId: string,
+ id: string,
+ metricsAlertCreateDestinationApi: MetricsAlertCreateDestinationApi,
+ options?: RequestInit
+): Promise<MetricsAlertDestinationApi> => {
+ return apiMutator<MetricsAlertDestinationApi>(getMetricsAlertsDestinationsCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(metricsAlertCreateDestinationApi),
+ })
+}
+
+export const getMetricsAlertsDestinationsDeleteCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/metrics_alerts/${id}/destinations/delete/`
+}
+
+/**
+ * Delete notification destinations of a metrics alert.
+ */
+export const metricsAlertsDestinationsDeleteCreate = async (
+ projectId: string,
+ id: string,
+ metricsAlertDeleteDestinationApi: MetricsAlertDeleteDestinationApi,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getMetricsAlertsDestinationsDeleteCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(metricsAlertDeleteDestinationApi),
+ })
+}
diff --git a/products/metrics/frontend/generated/api.zod.ts b/products/metrics/frontend/generated/api.zod.ts
index 40b7a1e4dd95..5b88d4524ed1 100644
--- a/products/metrics/frontend/generated/api.zod.ts
+++ b/products/metrics/frontend/generated/api.zod.ts
@@ -851,3 +851,69 @@ export const MetricsVariableOptionsCreateBody = /* @__PURE__ */ zod.object({
.nullish()
.describe('End of the window that options come from, in the same format as dateFrom. Defaults to now.'),
})
+
+/**
+ * Add a notification destination to a metrics alert. It hears the transitions in `event_kinds`. A PagerDuty destination opens an incident when the alert fires and resolves it when the alert resolves.
+ */
+export const metricsAlertsDestinationsCreateBodyPagerdutySeverityDefault = `critical`
+export const metricsAlertsDestinationsCreateBodyPagerdutyRegionDefault = `us`
+
+export const MetricsAlertsDestinationsCreateBody = /* @__PURE__ */ zod.object({
+ type: zod
+ .enum(['slack', 'webhook', 'teams', 'discord', 'pagerduty'])
+ .describe(
+ '\* `slack` - Slack\n\* `webhook` - Webhook\n\* `teams` - Microsoft Teams\n\* `discord` - Discord\n\* `pagerduty` - PagerDuty'
+ )
+ .describe(
+ 'Notification destination type.\n\n\* `slack` - Slack\n\* `webhook` - Webhook\n\* `teams` - Microsoft Teams\n\* `discord` - Discord\n\* `pagerduty` - PagerDuty'
+ ),
+ slack_workspace_id: zod
+ .number()
+ .optional()
+ .describe('Integration ID for the Slack workspace. Required when type=slack.'),
+ slack_channel_id: zod.string().optional().describe('Slack channel ID. Required when type=slack.'),
+ slack_channel_name: zod.string().optional().describe('Human-readable channel name for display.'),
+ webhook_url: zod.url().optional().describe('HTTPS endpoint to post to. Required for webhook, teams and discord.'),
+ pagerduty_routing_key: zod
+ .string()
+ .optional()
+ .describe('Integration key of a PagerDuty Events API v2 integration. Required when type=pagerduty.'),
+ pagerduty_severity: zod
+ .enum(['critical', 'error', 'warning', 'info'])
+ .describe('\* `critical` - critical\n\* `error` - error\n\* `warning` - warning\n\* `info` - info')
+ .default(metricsAlertsDestinationsCreateBodyPagerdutySeverityDefault)
+ .describe(
+ 'Severity PagerDuty records on the incident. Used when type=pagerduty.\n\n\* `critical` - critical\n\* `error` - error\n\* `warning` - warning\n\* `info` - info'
+ ),
+ pagerduty_region: zod
+ .enum(['us', 'eu'])
+ .describe('\* `us` - us\n\* `eu` - eu')
+ .default(metricsAlertsDestinationsCreateBodyPagerdutyRegionDefault)
+ .describe('PagerDuty service region of the account. Used when type=pagerduty.\n\n\* `us` - us\n\* `eu` - eu'),
+ event_kinds: zod
+ .array(
+ zod
+ .enum(['firing', 'resolved', 'errored', 'broken'])
+ .describe(
+ '\* `firing` - firing\n\* `resolved` - resolved\n\* `errored` - errored\n\* `broken` - broken'
+ )
+ )
+ .min(1)
+ .optional()
+ .describe(
+ "The alert transitions to send about. Defaults to every kind, or to firing and resolved for PagerDuty, which then hears each incident's trigger and resolve."
+ ),
+})
+
+/**
+ * Delete notification destinations of a metrics alert.
+ */
+export const metricsAlertsDestinationsDeleteCreateBodyDestinationIdsMax = 100
+
+export const MetricsAlertsDestinationsDeleteCreateBody = /* @__PURE__ */ zod.object({
+ destination_ids: zod
+ .array(zod.uuid())
+ .min(1)
+ .max(metricsAlertsDestinationsDeleteCreateBodyDestinationIdsMax)
+ .describe('IDs of the destinations to delete, as the list endpoint returns them.'),
+})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 61c73adc11d2..8e7aaa42f35d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -72951,6 +72951,126 @@ export namespace Schemas {
Textbox: 'textbox',
} as const;
+ /**
+ * * `slack` - Slack
+ * * `webhook` - Webhook
+ * * `teams` - Microsoft Teams
+ * * `discord` - Discord
+ * * `pagerduty` - PagerDuty
+ */
+ export type MetricsAlertDestinationTypeEnum = typeof MetricsAlertDestinationTypeEnum[keyof typeof MetricsAlertDestinationTypeEnum];
+
+
+ export const MetricsAlertDestinationTypeEnum = {
+ Slack: 'slack',
+ Webhook: 'webhook',
+ Teams: 'teams',
+ Discord: 'discord',
+ Pagerduty: 'pagerduty',
+ } as const;
+
+ /**
+ * * `firing` - firing
+ * * `resolved` - resolved
+ * * `errored` - errored
+ * * `broken` - broken
+ */
+ export type MetricsAlertDestinationEventKindEnum = typeof MetricsAlertDestinationEventKindEnum[keyof typeof MetricsAlertDestinationEventKindEnum];
+
+
+ export const MetricsAlertDestinationEventKindEnum = {
+ Firing: 'firing',
+ Resolved: 'resolved',
+ Errored: 'errored',
+ Broken: 'broken',
+ } as const;
+
+ export interface MetricsAlertCreateDestination {
+ /** Notification destination type.
+ *
+ * * `slack` - Slack
+ * * `webhook` - Webhook
+ * * `teams` - Microsoft Teams
+ * * `discord` - Discord
+ * * `pagerduty` - PagerDuty */
+ type: MetricsAlertDestinationTypeEnum;
+ /** Integration ID for the Slack workspace. Required when type=slack. */
+ slack_workspace_id?: number;
+ /** Slack channel ID. Required when type=slack. */
+ slack_channel_id?: string;
+ /** Human-readable channel name for display. */
+ slack_channel_name?: string;
+ /** HTTPS endpoint to post to. Required for webhook, teams and discord. */
+ webhook_url?: string;
+ /** Integration key of a PagerDuty Events API v2 integration. Required when type=pagerduty. */
+ pagerduty_routing_key?: string;
+ /** Severity PagerDuty records on the incident. Used when type=pagerduty.
+ *
+ * * `critical` - critical
+ * * `error` - error
+ * * `warning` - warning
+ * * `info` - info */
+ pagerduty_severity?: PagerDutySeverityEnum;
+ /** PagerDuty service region of the account. Used when type=pagerduty.
+ *
+ * * `us` - us
+ * * `eu` - eu */
+ pagerduty_region?: PagerDutyRegionEnum;
+ /**
+ * The alert transitions to send about. Defaults to every kind, or to firing and resolved for PagerDuty, which then hears each incident's trigger and resolve.
+ * @minItems 1
+ */
+ event_kinds?: MetricsAlertDestinationEventKindEnum[];
+ }
+
+ export interface MetricsAlertDeleteDestination {
+ /**
+ * IDs of the destinations to delete, as the list endpoint returns them.
+ * @minItems 1
+ * @maxItems 100
+ */
+ destination_ids: string[];
+ }
+
+ export interface MetricsAlertDestination {
+ /** ID of the destination. Send it to the delete endpoint to remove it. */
+ id: string;
+ /** Notification destination type.
+ *
+ * * `slack` - Slack
+ * * `webhook` - Webhook
+ * * `teams` - Microsoft Teams
+ * * `discord` - Discord
+ * * `pagerduty` - PagerDuty */
+ type: MetricsAlertDestinationTypeEnum;
+ /** Whether the destination is sent to. */
+ enabled: boolean;
+ /** The alert transitions the destination hears about. A PagerDuty destination hears the incident trigger and resolve of every firing. */
+ event_kinds: MetricsAlertDestinationEventKindEnum[];
+ /** Integration ID of the Slack workspace. Set when type=slack. */
+ slack_workspace_id?: number;
+ /** Slack channel ID. Set when type=slack. */
+ slack_channel_id?: string;
+ /** Human-readable Slack channel name. Set when type=slack. */
+ slack_channel_name?: string;
+ /** Webhook endpoint reduced to scheme and host. The path, query and userinfo carry the secret. */
+ webhook_url?: string;
+ /** PagerDuty integration key reduced to its last four characters. */
+ pagerduty_routing_key?: string;
+ /** Severity of the PagerDuty incident.
+ *
+ * * `critical` - critical
+ * * `error` - error
+ * * `warning` - warning
+ * * `info` - info */
+ pagerduty_severity?: PagerDutySeverityEnum;
+ /** PagerDuty service region the events go to.
+ *
+ * * `us` - us
+ * * `eu` - eu */
+ pagerduty_region?: PagerDutyRegionEnum;
+ }
+
export interface MetricsCreatedDashboard {
/** The id of the dashboard. */
dashboard_id: number;