: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): manage alert destinations through the platform API (#130550)
Jimmy Zhu52fc0423194c
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.pyindex b9fd9555e176..235273c32530 100644--- a/products/alerts_platform/backend/facade/api.py+++ b/products/alerts_platform/backend/facade/api.py@@ -13,6 +13,7 @@ from uuid import UUIDfrom products.alerts_platform.backend.facade.contracts import (AlertDeliveryRequest,+ AlertDestinationData,DestinationSend,HandbackRefusal,HeldDeliveryAddress,@@ -448,6 +449,11 @@ def list_alert_destinations(*, team_id: int, configuration_id: UUID) -> tuple[Streturn alert_destinations.list_alert_destinations(team_id=team_id, configuration_id=configuration_id)+def redact_destination_data(data: AlertDestinationData) -> AlertDestinationData:+ """A destination's configuration without the parts that are a credential, for showing it."""+ return alert_destinations.redact_destination_data(data)++def has_incident_destination(*, team_id: int, configuration_id: UUID) -> bool:"""Whether an alert whose destinations the platform owns has an enabled incident manager."""return alert_destinations.has_incident_destination(team_id=team_id, configuration_id=configuration_id)diff --git a/products/alerts_platform/backend/logic/alert_destinations.py b/products/alerts_platform/backend/logic/alert_destinations.pyindex 2c80e53cbe40..7b384aa44f42 100644--- a/products/alerts_platform/backend/logic/alert_destinations.py+++ b/products/alerts_platform/backend/logic/alert_destinations.py@@ -8,6 +8,7 @@ from __future__ import annotationsfrom collections.abc import Callable, Collection, Sequencefrom typing import Final, cast+from urllib.parse import urlsplitfrom uuid import UUIDfrom django.db import transaction@@ -175,6 +176,31 @@ def _validate(destination: NewAlertDestination) -> None:raise AlertDestinationValidationError(refusal, field="config")+def redact_destination_data(data: AlertDestinationData) -> AlertDestinationData:+ """Drop the parts of a destination's configuration that are a credential."""+ redacted = cast(AlertDestinationData, {key: value for key, value in data.items() if key != "webhook_headers"})+ if (webhook_url := data.get("webhook_url")) is not None:+ redacted["webhook_url"] = _redact_url(webhook_url)+ if (routing_key := data.get("pagerduty_routing_key")) is not None:+ # Keep the tail a person needs to tell two integration keys apart.+ redacted["pagerduty_routing_key"] = f"••••{routing_key[-4:]}"+ return redacted+++def _redact_url(value: str) -> str:+ """Keep only the parts a person needs to tell two destinations apart. The path,+ query and userinfo carry the channel secret for every webhook-style provider."""+ try:+ parsed = urlsplit(value)+ scheme, hostname, port = parsed.scheme, parsed.hostname, parsed.port+ except ValueError:+ return "<redacted>"+ if not scheme or not hostname:+ return "<redacted>"+ authority = f"{hostname}:{port}" if port is not None else hostname+ return f"{scheme}://{authority}"++def _stored(row: AlertDestination) -> StoredAlertDestination:return StoredAlertDestination(id=row.id,diff --git a/products/alerts_platform/backend/presentation/views/platform_alert.py b/products/alerts_platform/backend/presentation/views/platform_alert.pyindex 506b22501e1c..a996ff613873 100644--- a/products/alerts_platform/backend/presentation/views/platform_alert.py+++ b/products/alerts_platform/backend/presentation/views/platform_alert.py@@ -19,7 +19,8 @@ from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.pagination import PrecountedLimitOffsetPaginationfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.event_usage import report_user_action-from posthog.exceptions import Conflict+from posthog.exceptions import Conflict, as_drf_validation_error+from posthog.integrations import IntegrationManager, IntegrationNotFoundfrom posthog.models import Team, Userfrom posthog.permissions import (FEATURE_FLAG_REQUIRED_ERROR_CODE,@@ -36,9 +37,14 @@ from products.alerts_platform.backend.facade.contracts import (MAX_EVALUATION_PERIODS,MAX_INSTANCES_CEILING,MAX_STORED_INTEGER,+ AlertDestinationData,+ AlertDestinationValidationError,+ AlertEventKind,+ DestinationType,Grouping,GroupingMode,InvalidPlatformAlertEdit,+ NewAlertDestination,OnOverflow,PlatformAlertConfigurationEdit,PlatformAlertConfigurationView,@@ -56,6 +62,13 @@ from products.alerts_platform.backend.facade.enums import (PlatformAlertState,)from products.alerts_platform.backend.facade.source_configs import editable_source_configs+from products.alerts_platform.backend.presentation.views.platform_alert_destinations import (+ MAX_DESTINATIONS_PER_ALERT,+ PlatformAlertCreateDestinationSerializer,+ PlatformAlertDeleteDestinationSerializer,+ PlatformAlertDestinationSerializer,+ serialized_destination,+)from products.alerts_platform.backend.presentation.views.schedule_restriction import ScheduleRestrictionFieldPLATFORM_ALERTS_FLAG: Final = "platform-alerts"@@ -450,6 +463,16 @@ class PlatformAlertsFlagPermission(BasePermission):class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "alert"+ scope_object_read_actions = ["list", "retrieve", "destinations"]+ scope_object_write_actions = [+ "create",+ "update",+ "partial_update",+ "patch",+ "destroy",+ "create_destination",+ "delete_destination",+ ]permission_classes = [PlatformAlertsFlagPermission]serializer_class = PlatformAlertConfigurationSerializerpagination_class = PrecountedLimitOffsetPagination@@ -539,14 +562,18 @@ class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.Genericdef _writable_source_kinds(self) -> list[str]:return self._source_kinds_with("editor", "write")- def _writable_configuration(- self, team_id: int, configuration_id: UUID, verb: str- ) -> PlatformAlertConfigurationView:+ def _readable_configuration(self, team_id: int, configuration_id: UUID) -> PlatformAlertConfigurationView:current = platform_api.get_configuration(team_id=team_id, source_kinds=self._readable_source_kinds(), configuration_id=configuration_id)if current is None:raise NotFound()+ return current++ def _writable_configuration(+ self, team_id: int, configuration_id: UUID, verb: str+ ) -> PlatformAlertConfigurationView:+ current = self._readable_configuration(team_id, configuration_id)if current.source_kind not in self._writable_source_kinds:raise PermissionDenied(f"You cannot {verb} {current.source_kind} alerts.")return current@@ -721,6 +748,165 @@ class PlatformAlertConfigurationViewSet(TeamAndOrgViewSetMixin, viewsets.Genericraise NotFound()return Response(PlatformAlertSerializer(group).data)+ def _destination_configuration(self, pk: str, *, write: bool) -> PlatformAlertConfigurationView:+ configuration_id = serializers.UUIDField().run_validation(pk)+ team_id = self._canonical_team_id()+ current = (+ self._writable_configuration(team_id, configuration_id, "change destinations of")+ if write+ else self._readable_configuration(team_id, configuration_id)+ )+ spec = editable_source_configs().get(SourceKind(current.source_kind))+ # Only a kind the platform creates natively keeps its destinations as `AlertDestination` rows.+ # Every other kind's destinations belong to its source product.+ if (+ current.owner != PlatformAlertOwner.PLATFORM+ or spec is None+ or spec.native is None+ or not spec.native.platform_destinations+ ):+ raise Conflict(f"The destinations of {current.source_kind} alerts are managed by that product.")+ return current++ @extend_schema(+ responses={+ 200: PlatformAlertDestinationSerializer(many=True),+ 404: OpenApiResponse(description="No alert with this id that the caller can read."),+ 409: OpenApiResponse(description="The alert's source product manages its destinations."),+ },+ description="List the notification destinations of an alert.",+ )+ @action(detail=True, methods=["GET"], url_path="destinations", pagination_class=None)+ def destinations(self, request: Request, pk: str, **kwargs: Any) -> Response:+ configuration = self._destination_configuration(pk, write=False)+ destinations = platform_api.list_alert_destinations(+ team_id=self._canonical_team_id(), configuration_id=configuration.id+ )+ return Response(+ PlatformAlertDestinationSerializer([serialized_destination(d) for d in destinations], many=True).data+ )++ @extend_schema(+ request=PlatformAlertCreateDestinationSerializer,+ responses={+ 201: PlatformAlertDestinationSerializer,+ 400: OpenApiResponse(description="The destination settings are invalid."),+ 403: OpenApiResponse(description="The caller cannot write alerts of this source kind."),+ 404: OpenApiResponse(description="No alert with this id that the caller can read."),+ 409: OpenApiResponse(description="The alert's source product manages its destinations."),+ },+ description=(+ "Add a notification destination to an 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:+ configuration = self._destination_configuration(pk, write=True)+ team_id = self._canonical_team_id()+ serializer = PlatformAlertCreateDestinationSerializer(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"]+ if data["type"] == DestinationType.SLACK:+ # The accessor native delivery sends through, so a destination it would refuse is never saved.+ try:+ IntegrationManager.slack.oauth.get(team_id, data["slack_workspace_id"])+ except IntegrationNotFound:+ 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 (+ platform_api.get_configuration(+ team_id=team_id,+ source_kinds=self._writable_source_kinds,+ configuration_id=configuration.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 = platform_api.list_alert_destinations(team_id=team_id, configuration_id=configuration.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,) = platform_api.create_alert_destinations(+ team_id=team_id,+ configuration_id=configuration.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_destination(+ "created",+ configuration,+ {"type": data["type"], "event_kinds": [kind.value for kind in event_kinds]},+ ),+ robust=True,+ )+ return Response(+ PlatformAlertDestinationSerializer(serialized_destination(created)).data, status=status.HTTP_201_CREATED+ )++ @extend_schema(+ request=PlatformAlertDeleteDestinationSerializer,+ responses={+ 204: OpenApiResponse(description="The destinations are deleted. An ID of another alert is ignored."),+ 403: OpenApiResponse(description="The caller cannot write alerts of this source kind."),+ 404: OpenApiResponse(description="No alert with this id that the caller can read."),+ 409: OpenApiResponse(+ description="The alert's source product manages its destinations, or a PagerDuty destination "+ "has an open incident."+ ),+ },+ description="Delete notification destinations of an alert.",+ )+ @action(detail=True, methods=["POST"], url_path="destinations/delete")+ def delete_destination(self, request: Request, pk: str, **kwargs: Any) -> Response:+ configuration = self._destination_configuration(pk, write=True)+ serializer = PlatformAlertDeleteDestinationSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ destination_ids: list[UUID] = serializer.validated_data["destination_ids"]+ # The resolve for an open incident goes to the destinations that remain when the firing ends,+ # so a removed incident manager would keep its incident open for good.+ if any(alert.state == PlatformAlertState.FIRING.value for alert in configuration.alerts) and any(+ destination.id in destination_ids+ and destination.enabled+ and destination.data["type"] == DestinationType.PAGERDUTY+ for destination in platform_api.list_alert_destinations(+ team_id=self._canonical_team_id(), configuration_id=configuration.id+ )+ ):+ raise Conflict("This PagerDuty destination has an open incident. Remove it once the alert resolves.")+ deleted = platform_api.delete_alert_destinations(+ team_id=self._canonical_team_id(), configuration_id=configuration.id, destination_ids=destination_ids+ )+ transaction.on_commit(+ lambda: self._track_destination("deleted", configuration, {"count": deleted}), robust=True+ )+ return Response(status=status.HTTP_204_NO_CONTENT)++ def _track_destination(+ self,+ action: Literal["created", "deleted"],+ configuration: PlatformAlertConfigurationView,+ properties: dict[str, Any],+ ) -> None:+ report_user_action(+ cast(User, self.request.user),+ f"alert destination {action}",+ {"alert_id": str(configuration.id), "source_kind": configuration.source_kind, **properties},+ team=self.team,+ request=self.request,+ )+@extend_schema(parameters=[PlatformAlertConfigurationListQuerySerializer])def list(self, request: Request, **kwargs) -> Response:query = PlatformAlertConfigurationListQuerySerializer(data=request.query_params)diff --git a/products/alerts_platform/backend/presentation/views/platform_alert_destinations.py b/products/alerts_platform/backend/presentation/views/platform_alert_destinations.pynew file mode 100644index 000000000000..64a31364c379--- /dev/null+++ b/products/alerts_platform/backend/presentation/views/platform_alert_destinations.py@@ -0,0 +1,203 @@+"""Serializers for the notification destinations of a platform-owned alert.++A kind whose alerts the platform creates natively keeps its destinations as `AlertDestination` rows.+The platform alert API lists, adds and deletes them for every such kind, with the kind's own access rules.+"""++import re+from typing import Any, Final, cast++from django.db import models++from rest_framework import serializers+from rest_framework.exceptions import ValidationError++from products.alerts_platform.backend.facade.api import redact_destination_data+from products.alerts_platform.backend.facade.contracts import (+ AlertDestinationData,+ AlertEventKind,+ DestinationType,+ PagerDutyRegion,+ PagerDutySeverity,+ StoredAlertDestination,+)+from products.alerts_platform.backend.facade.delivery import refused_destination++# Each destination is another message every time the alert fires, so one alert has only a few.+MAX_DESTINATIONS_PER_ALERT: Final = 5+# Stops a malformed request becoming a huge query.+MAX_DESTINATION_IDS_PER_DELETE_REQUEST: Final = 100+# The types native delivery sends to. Email and in-app have no native sender yet.+PLATFORM_DESTINATION_TYPES: Final = (+ DestinationType.SLACK,+ DestinationType.WEBHOOK,+ DestinationType.TEAMS,+ DestinationType.DISCORD,+ DestinationType.PAGERDUTY,+)+# 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: Final[dict[DestinationType, tuple[AlertEventKind, ...]]] = {+ DestinationType.PAGERDUTY: (AlertEventKind.FIRING, AlertEventKind.RESOLVED),+}+_MESSAGE_EVENT_KINDS: Final = (+ AlertEventKind.FIRING,+ AlertEventKind.RESOLVED,+ AlertEventKind.ERRORED,+ AlertEventKind.BROKEN,+)+_WEBHOOK_FIELDS: Final = ("webhook_url",)+_PAGERDUTY_ROUTING_KEY_RE: Final = re.compile(r"[A-Za-z0-9]{32}")+_REQUIRED_FIELDS: Final[dict[DestinationType, tuple[str, ...]]] = {+ DestinationType.SLACK: ("slack_workspace_id", "slack_channel_id"),+ DestinationType.WEBHOOK: _WEBHOOK_FIELDS,+ DestinationType.TEAMS: _WEBHOOK_FIELDS,+ DestinationType.DISCORD: _WEBHOOK_FIELDS,+ DestinationType.PAGERDUTY: ("pagerduty_routing_key",),+}+# 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: Final[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. The others keep label equal to value, so they share+# the names their ENUM_NAME_OVERRIDES entries give them.+PlatformAlertDestinationType = cast(Any, models.TextChoices)(+ "PlatformAlertDestinationType",+ [(member.name, (member.value, member.label)) for member in PLATFORM_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]+)+PlatformAlertDestinationEventKind = cast(Any, models.TextChoices)(+ "PlatformAlertDestinationEventKind",+ [(member.name, (member.value, member.value)) for member in _MESSAGE_EVENT_KINDS],+)+++class PlatformAlertDestinationSerializer(serializers.Serializer):+ id = serializers.UUIDField(help_text="ID of the destination. Send it to the delete endpoint to remove it.")+ type = serializers.ChoiceField(+ choices=PlatformAlertDestinationType.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=PlatformAlertDestinationEventKind.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 PlatformAlertCreateDestinationSerializer(serializers.Serializer):+ type = serializers.ChoiceField(+ choices=PlatformAlertDestinationType.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=PlatformAlertDestinationEventKind.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+ # Checked before the view reads them, so a missing field answers 400 with its name.+ if missing := [key for key in _REQUIRED_FIELDS[destination_type] if not data.get(key)]:+ raise ValidationError(dict.fromkeys(missing, f"Required for {destination_type.label} destinations."))+ routing_key = data.get("pagerduty_routing_key")+ if routing_key is not None and not _PAGERDUTY_ROUTING_KEY_RE.fullmatch(routing_key):+ raise ValidationError(+ {+ "pagerduty_routing_key": "Enter the 32-character integration key of a PagerDuty Events API v2 integration."+ }+ )+ # The platform's write path checks the rest. Refusing here names the field at fault.+ 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 PlatformAlertDeleteDestinationSerializer(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(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),+ }diff --git a/products/alerts_platform/backend/tests/api/test_platform_alert_destinations.py b/products/alerts_platform/backend/tests/api/test_platform_alert_destinations.pynew file mode 100644index 000000000000..e5877191271d--- /dev/null+++ b/products/alerts_platform/backend/tests/api/test_platform_alert_destinations.py@@ -0,0 +1,198 @@+from datetime import UTC, datetime++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized+from rest_framework import status++from posthog.models.integration import Integration+from posthog.models.integration.auth_types import ANY+from posthog.models.scoping import team_scope++from products.alerts_platform.backend.facade import testing as platform_testing+from products.alerts_platform.backend.facade.api import create_configuration, list_alert_destinations+from products.alerts_platform.backend.facade.contracts import Grouping, PlatformAlertConfigurationEdit, SourceKind+from products.alerts_platform.backend.models import PlatformAlertConfiguration++_ROUTING_KEY = "0123456789abcdef0123456789abcdef"+++class TestPlatformAlertDestinations(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.enterContext(patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True))+ self.enterContext(patch("posthoganalytics.feature_enabled", return_value=True))+ # Metrics is a kind the platform creates natively, with `AlertDestination` rows from the start.+ with team_scope(self.team.id):+ self.configuration_id = create_configuration(+ team_id=self.team.id,+ source_kind=SourceKind.METRICS,+ edit=PlatformAlertConfigurationEdit(+ name="Consumer lag",+ enabled=True,+ source_config={"query": "sum(lag)", "condition": {"operator": "gt", "threshold": 1000}},+ grouping=Grouping(),+ schedule_restriction=None,+ evaluation_periods=1,+ datapoints_to_alarm=1,+ cooldown_minutes=0,+ ),+ created_by_id=self.user.id,+ ).id+ self.url = f"/api/projects/{self.team.id}/platform_alerts/{self.configuration_id}/destinations/"++ def test_destinations_are_alert_destination_rows_that_go_with_the_alert(self) -> None:+ workspace = Integration.objects.create(team=self.team, kind="slack", config={}, sensitive_config={})+ slack = self.client.post(+ self.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(+ self.url, {"type": "pagerduty", "pagerduty_routing_key": _ROUTING_KEY}, format="json"+ )++ 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(self.url).json()+ assert [d["id"] for d in listed] == [slack.json()["id"], pagerduty.json()["id"]]+ assert listed[1]["pagerduty_routing_key"] == "••••cdef"+ 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"],+ ]++ removed = self.client.post(f"{self.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(self.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(+ [+ # The alert is hidden from a caller who cannot read its product.+ ("read_alert_only", "get", ["alert:read"], status.HTTP_404_NOT_FOUND),+ ("read_metrics_only", "get", ["metrics:read"], status.HTTP_403_FORBIDDEN),+ ("read_both", "get", ["alert:read", "metrics:read"], status.HTTP_200_OK),+ ("write_with_read_scopes", "post", ["alert:read", "metrics:read"], status.HTTP_403_FORBIDDEN),+ ("write_alert_without_metrics", "post", ["alert:write", "metrics:read"], status.HTTP_403_FORBIDDEN),+ ]+ )+ def test_destinations_need_the_alert_and_the_kinds_scope(+ self, _name: str, method: 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)}")++ if method == "get":+ response = self.client.get(self.url)+ else:+ response = self.client.post(+ self.url, {"type": "pagerduty", "pagerduty_routing_key": _ROUTING_KEY}, format="json"+ )++ 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",+ ),+ ("short_pagerduty_key", {"type": "pagerduty", "pagerduty_routing_key": "abc"}, "pagerduty_routing_key"),+ ("email", {"type": "email"}, "type"),+ ("slack_without_workspace", {"type": "slack", "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(self.url, body, format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == field++ def test_a_slack_workspace_delivery_cannot_send_through_is_refused(self) -> None:+ # Delivery sends only through an OAuth Slack integration, so a token one would never notify.+ workspace = Integration.objects._with_auth(ANY).create(+ team=self.team, kind="slack", config={"auth_type": "token"}, sensitive_config={}+ )++ response = self.client.post(+ self.url,+ {"type": "slack", "slack_workspace_id": workspace.id, "slack_channel_id": "C123"},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == "slack_workspace_id"++ def test_a_pagerduty_destination_with_an_open_incident_cannot_be_removed(self) -> None:+ created = self.client.post(+ self.url, {"type": "pagerduty", "pagerduty_routing_key": _ROUTING_KEY}, format="json"+ ).json()+ with team_scope(self.team.id):+ platform_testing.start_firing(+ self.configuration_id, team_id=self.team.id, at=datetime(2026, 11, 5, 12, 0, tzinfo=UTC)+ )++ refused = self.client.post(f"{self.url}delete/", {"destination_ids": [created["id"]]}, format="json")+ assert refused.status_code == status.HTTP_409_CONFLICT, refused.json()+ assert [d["id"] for d in self.client.get(self.url).json()] == [created["id"]]++ def test_a_webhook_secret_is_never_listed(self) -> None:+ created = self.client.post(+ self.url,+ {"type": "discord", "webhook_url": "https://discord.com/api/webhooks/123/secret-token"},+ format="json",+ )+ assert created.status_code == status.HTTP_201_CREATED, created.json()++ assert [d["webhook_url"] for d in self.client.get(self.url).json()] == ["https://discord.com"]++ @parameterized.expand([("duplicate", 1, 0), ("over_the_cap", 5, 5)])+ def test_a_destination_past_the_alerts_limits_is_refused(self, _name: str, existing: int, next_index: int) -> None:+ def discord(index: int) -> dict[str, str]:+ return {"type": "discord", "webhook_url": f"https://discord.com/api/webhooks/{index}/token"}++ for index in range(existing):+ assert self.client.post(self.url, discord(index), format="json").status_code == status.HTTP_201_CREATED++ response = self.client.post(self.url, discord(next_index), format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()++ def test_a_kind_whose_product_owns_its_destinations_is_refused(self) -> None:+ with team_scope(self.team.id):+ logs_alert = PlatformAlertConfiguration.objects.create(+ team=self.team,+ name="API errors",+ source_kind=PlatformAlertConfiguration.SourceKind.LOGS,+ source_config={+ "filters": {"serviceNames": ["api"]},+ "condition": {"threshold_count": 1, "threshold_operator": "above", "window_minutes": 5},+ },+ check_interval_minutes=10,+ owner=PlatformAlertConfiguration.Owner.PLATFORM,+ )++ response = self.client.get(f"/api/projects/{self.team.id}/platform_alerts/{logs_alert.id}/destinations/")++ assert response.status_code == status.HTTP_409_CONFLICT, response.json()diff --git a/products/alerts_platform/frontend/generated/api.schemas.ts b/products/alerts_platform/frontend/generated/api.schemas.tsindex ce8a78e0ecd4..5f18a53a22aa 100644--- a/products/alerts_platform/frontend/generated/api.schemas.ts+++ b/products/alerts_platform/frontend/generated/api.schemas.ts@@ -1736,6 +1736,152 @@ export type PatchedPlatformAlertConfigurationEditApi =| PatchedWarehouseDestinationPlatformAlertConfigurationEditApi| PatchedWarehouseSourcePlatformAlertConfigurationEditApi+/**+ * * `slack` - Slack+ * * `webhook` - Webhook+ * * `teams` - Microsoft Teams+ * * `discord` - Discord+ * * `pagerduty` - PagerDuty+ */+export type PlatformAlertDestinationTypeEnumApi =+ (typeof PlatformAlertDestinationTypeEnumApi)[keyof typeof PlatformAlertDestinationTypeEnumApi]++export const PlatformAlertDestinationTypeEnumApi = {+ Slack: 'slack',+ Webhook: 'webhook',+ Teams: 'teams',+ Discord: 'discord',+ Pagerduty: 'pagerduty',+} as const++/**+ * * `firing` - firing+ * * `resolved` - resolved+ * * `errored` - errored+ * * `broken` - broken+ */+export type PlatformAlertDestinationEventKindEnumApi =+ (typeof PlatformAlertDestinationEventKindEnumApi)[keyof typeof PlatformAlertDestinationEventKindEnumApi]++export const PlatformAlertDestinationEventKindEnumApi = {+ 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 PlatformAlertDestinationApi {+ /** 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: PlatformAlertDestinationTypeEnumApi+ /** 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: PlatformAlertDestinationEventKindEnumApi[]+ /** 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 PlatformAlertCreateDestinationApi {+ /** Notification destination type.+ *+ * * `slack` - Slack+ * * `webhook` - Webhook+ * * `teams` - Microsoft Teams+ * * `discord` - Discord+ * * `pagerduty` - PagerDuty */+ type: PlatformAlertDestinationTypeEnumApi+ /** 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?: PlatformAlertDestinationEventKindEnumApi[]+}++export interface PlatformAlertDeleteDestinationApi {+ /**+ * IDs of the destinations to delete, as the list endpoint returns them.+ * @minItems 1+ * @maxItems 100+ */+ destination_ids: string[]+}+export interface PlatformAlertGroupSnoozeApi {/*** Key of the group to snooze, as the grouping_key of one of the alert's instances.diff --git a/products/alerts_platform/frontend/generated/api.ts b/products/alerts_platform/frontend/generated/api.tsindex 5b1a4dfe8144..67c37dd5180a 100644--- a/products/alerts_platform/frontend/generated/api.ts+++ b/products/alerts_platform/frontend/generated/api.ts@@ -15,6 +15,9 @@ import type {PlatformAlertConfigurationApi,PlatformAlertConfigurationCreateApi,PlatformAlertConfigurationEditApi,+ PlatformAlertCreateDestinationApi,+ PlatformAlertDeleteDestinationApi,+ PlatformAlertDestinationApi,PlatformAlertGroupSnoozeApi,PlatformAlertsListParams,} from './api.schemas'@@ -125,6 +128,66 @@ export const platformAlertsDestroy = async (projectId: string, id: string, optio})}+export const getPlatformAlertsDestinationsListUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/platform_alerts/${id}/destinations/`+}++/**+ * List the notification destinations of an alert.+ */+export const platformAlertsDestinationsList = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<PlatformAlertDestinationApi[]> => {+ return apiMutator<PlatformAlertDestinationApi[]>(getPlatformAlertsDestinationsListUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getPlatformAlertsDestinationsCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/platform_alerts/${id}/destinations/`+}++/**+ * Add a notification destination to an 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 platformAlertsDestinationsCreate = async (+ projectId: string,+ id: string,+ platformAlertCreateDestinationApi: PlatformAlertCreateDestinationApi,+ options?: RequestInit+): Promise<PlatformAlertDestinationApi> => {+ return apiMutator<PlatformAlertDestinationApi>(getPlatformAlertsDestinationsCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(platformAlertCreateDestinationApi),+ })+}++export const getPlatformAlertsDestinationsDeleteCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/platform_alerts/${id}/destinations/delete/`+}++/**+ * Delete notification destinations of an alert.+ */+export const platformAlertsDestinationsDeleteCreate = async (+ projectId: string,+ id: string,+ platformAlertDeleteDestinationApi: PlatformAlertDeleteDestinationApi,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getPlatformAlertsDestinationsDeleteCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(platformAlertDeleteDestinationApi),+ })+}+export const getPlatformAlertsSnoozeGroupCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/platform_alerts/${id}/snooze_group/`}diff --git a/products/alerts_platform/frontend/generated/api.zod.ts b/products/alerts_platform/frontend/generated/api.zod.tsindex 18f11179a9e9..468e9a22bebe 100644--- a/products/alerts_platform/frontend/generated/api.zod.ts+++ b/products/alerts_platform/frontend/generated/api.zod.ts@@ -2236,6 +2236,72 @@ export const PlatformAlertsPartialUpdateBody = /* @__PURE__ */ zod.union([.describe('The settings an edit can change. Each source kind subclasses it with a typed `source_config`.'),])+/**+ * Add a notification destination to an 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 platformAlertsDestinationsCreateBodyPagerdutySeverityDefault = `critical`+export const platformAlertsDestinationsCreateBodyPagerdutyRegionDefault = `us`++export const PlatformAlertsDestinationsCreateBody = /* @__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(platformAlertsDestinationsCreateBodyPagerdutySeverityDefault)+ .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(platformAlertsDestinationsCreateBodyPagerdutyRegionDefault)+ .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 an alert.+ */+export const platformAlertsDestinationsDeleteCreateBodyDestinationIdsMax = 100++export const PlatformAlertsDestinationsDeleteCreateBody = /* @__PURE__ */ zod.object({+ destination_ids: zod+ .array(zod.uuid())+ .min(1)+ .max(platformAlertsDestinationsDeleteCreateBodyDestinationIdsMax)+ .describe('IDs of the destinations to delete, as the list endpoint returns them.'),+})+/*** @summary Snooze one group of a grouped alert*/diff --git a/products/metrics/backend/alerts/destinations.py b/products/metrics/backend/alerts/destinations.pyindex d3232b66f042..cdd93c4ebade 100644--- a/products/metrics/backend/alerts/destinations.py+++ b/products/metrics/backend/alerts/destinations.py@@ -1,4 +1,4 @@-"""The event ids of a metrics alert's transitions, and the destination types it sends to.+"""The event ids of a metrics alert's transitions.A metrics alert's destinations are `AlertDestination` rows. Delivery maps each event id back to thetransition it announces, so it knows which rows hear it, and words the message itself.@@ -6,15 +6,7 @@ transition it announces, so it knows which rows hear it, and words the message ifrom typing import Final-from products.alerts_platform.backend.facade.contracts import AlertEventKind, DestinationType, IncidentAction--METRICS_ALERT_DESTINATION_TYPES: Final = (- DestinationType.SLACK,- DestinationType.WEBHOOK,- DestinationType.TEAMS,- DestinationType.DISCORD,- DestinationType.PAGERDUTY,-)+from products.alerts_platform.backend.facade.contracts import AlertEventKind, IncidentAction# The event id each announced kind travels under. Resolved here because the platform imports no source.EVENT_IDS_BY_KIND: Final[dict[str, str]] = {diff --git a/products/metrics/backend/facade/alerts.py b/products/metrics/backend/facade/alerts.pydeleted file mode 100644index 54d4c06082a7..000000000000--- a/products/metrics/backend/facade/alerts.py+++ /dev/null@@ -1,5 +0,0 @@-"""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.pydeleted file mode 100644index 4f3741ffdd3f..000000000000--- a/products/metrics/backend/presentation/alert_destinations_api.py+++ /dev/null@@ -1,338 +0,0 @@-"""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.pyindex 2d71543d9f44..bb87d3a53417 100644--- a/products/metrics/backend/routes.py+++ b/products/metrics/backend/routes.py@@ -1,6 +1,5 @@from posthog.api.routing import RouterRegistry-from products.metrics.backend.presentation.alert_destinations_api import MetricsAlertDestinationViewSetfrom products.metrics.backend.presentation.api import MetricsViewSetfrom products.metrics.backend.presentation.dashboard_import_api import MetricsDashboardImportViewSetfrom products.metrics.backend.presentation.prometheus_api import PrometheusQueryViewSet@@ -31,4 +30,3 @@ 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.pyindex 09b239ca6397..a0f72b0cdc96 100644--- a/products/metrics/backend/tests/test_alerts.py+++ b/products/metrics/backend/tests/test_alerts.py@@ -392,7 +392,7 @@ class TestMetricsAlertEvaluation(APIBaseTest):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/"+ destinations_url = f"/api/projects/{self.team.id}/platform_alerts/{self.configuration_id}/destinations/"slack = self.client.post(destinations_url,{@@ -438,41 +438,3 @@ class TestMetricsAlertEvaluation(APIBaseTest):assert deleted.status_code == status.HTTP_204_NO_CONTENTwith 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"] == fielddiff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.tsindex b22e3bcfee9a..8133fe7990e9 100644--- a/products/metrics/frontend/generated/api.schemas.ts+++ b/products/metrics/frontend/generated/api.schemas.ts@@ -1330,152 +1330,6 @@ 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.tsindex 4deda2089217..c4c5d6df0399 100644--- a/products/metrics/frontend/generated/api.ts+++ b/products/metrics/frontend/generated/api.ts@@ -13,9 +13,6 @@ import type {AppMetricsTotalsResponseApi,DashboardImportApi,DashboardImportCreateApi,- MetricsAlertCreateDestinationApi,- MetricsAlertDeleteDestinationApi,- MetricsAlertDestinationApi,MetricsAttributeValuesRetrieveParams,MetricsAttributesRetrieveParams,MetricsCreatedDashboardApi,@@ -696,63 +693,3 @@ 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.tsindex 47aa3c8620d9..a1e7f7c52565 100644--- a/products/metrics/frontend/generated/api.zod.ts+++ b/products/metrics/frontend/generated/api.zod.ts@@ -859,69 +859,3 @@ 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.tsindex 30d724973059..b4a5f387c383 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -66847,126 +66847,6 @@ 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;@@ -91376,6 +91256,126 @@ export namespace Schemas {export type PlatformAlertConfigurationEdit = InsightPlatformAlertConfigurationEdit | LogsPlatformAlertConfigurationEdit | MetricsPlatformAlertConfigurationEdit | WarehouseDestinationPlatformAlertConfigurationEdit | WarehouseSourcePlatformAlertConfigurationEdit;+ /**+ * * `slack` - Slack+ * * `webhook` - Webhook+ * * `teams` - Microsoft Teams+ * * `discord` - Discord+ * * `pagerduty` - PagerDuty+ */+ export type PlatformAlertDestinationTypeEnum = typeof PlatformAlertDestinationTypeEnum[keyof typeof PlatformAlertDestinationTypeEnum];+++ export const PlatformAlertDestinationTypeEnum = {+ Slack: 'slack',+ Webhook: 'webhook',+ Teams: 'teams',+ Discord: 'discord',+ Pagerduty: 'pagerduty',+ } as const;++ /**+ * * `firing` - firing+ * * `resolved` - resolved+ * * `errored` - errored+ * * `broken` - broken+ */+ export type PlatformAlertDestinationEventKindEnum = typeof PlatformAlertDestinationEventKindEnum[keyof typeof PlatformAlertDestinationEventKindEnum];+++ export const PlatformAlertDestinationEventKindEnum = {+ Firing: 'firing',+ Resolved: 'resolved',+ Errored: 'errored',+ Broken: 'broken',+ } as const;++ export interface PlatformAlertCreateDestination {+ /** Notification destination type.+ *+ * * `slack` - Slack+ * * `webhook` - Webhook+ * * `teams` - Microsoft Teams+ * * `discord` - Discord+ * * `pagerduty` - PagerDuty */+ type: PlatformAlertDestinationTypeEnum;+ /** 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?: PlatformAlertDestinationEventKindEnum[];+ }++ export interface PlatformAlertDeleteDestination {+ /**+ * IDs of the destinations to delete, as the list endpoint returns them.+ * @minItems 1+ * @maxItems 100+ */+ destination_ids: string[];+ }++ export interface PlatformAlertDestination {+ /** 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: PlatformAlertDestinationTypeEnum;+ /** 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: PlatformAlertDestinationEventKindEnum[];+ /** 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 PlatformAlertGroupSnooze {/*** Key of the group to snooze, as the grouping_key of one of the alert's instances.