Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(alerts): add the AlertDestination table and its write path (#119963)

Jimmy Zhufd6493977bd1
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 7f4ba49ea3b0..907b095708fb 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -419,6 +419,7 @@ rules:
|PlatformAlertConfiguration
|PlatformAlertDeliveryPath
|PlatformAlertThread
+ |AlertDestination
|Survey
|SurveyResponseArchive
|TableCertification
@@ -884,6 +885,7 @@ rules:
|PlatformAlertConfiguration
|PlatformAlertDeliveryPath
|PlatformAlertThread
+ |AlertDestination
|Survey
|SurveyResponseArchive
|TableCertification
diff --git a/products/alerts_platform/backend/delivery/addresses.py b/products/alerts_platform/backend/delivery/addresses.py
index f20551c52b72..15d0fbb2edbb 100644
--- a/products/alerts_platform/backend/delivery/addresses.py
+++ b/products/alerts_platform/backend/delivery/addresses.py
@@ -37,8 +37,10 @@ def refused_destination(data: AlertDestinationData) -> str | None:
return None
transport = _URL_TRANSPORTS.get(data["type"])
url = data.get("webhook_url")
- if transport is None or not isinstance(url, str):
+ if transport is None:
return None
+ if not isinstance(url, str):
+ return "This destination needs a web address."
try:
transport().check_url(url)
except DeliveryError as error:
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.py
index 671fbc098bf2..3e388ae4cf8e 100644
--- a/products/alerts_platform/backend/facade/api.py
+++ b/products/alerts_platform/backend/facade/api.py
@@ -14,6 +14,7 @@ from uuid import UUID
from products.alerts_platform.backend.facade.contracts import (
DestinationSend,
HandbackRefusal,
+ NewAlertDestination,
PlatformAlertCheckInput,
PlatformAlertConfigurationEdit,
PlatformAlertConfigurationPage,
@@ -27,8 +28,10 @@ from products.alerts_platform.backend.facade.contracts import (
PlatformHandback,
PlatformOwnershipHandover,
SourceKind,
+ StoredAlertDestination,
)
from products.alerts_platform.backend.logic import (
+ alert_destinations,
destination_sends,
platform_lifecycle,
platform_reads,
@@ -262,6 +265,26 @@ def close_owned_firings_now(*, team_id: int, legacy_configuration_id: UUID) -> N
platform_writes.close_owned_firings_now(team_id=team_id, legacy_configuration_id=legacy_configuration_id)
+def create_alert_destinations(
+ *, team_id: int, configuration_id: UUID, destinations: Sequence[NewAlertDestination]
+) -> tuple[StoredAlertDestination, ...]:
+ """Adds destinations to one alert, all or none. Raises `AlertDestinationValidationError` on a refused one."""
+ return alert_destinations.create_alert_destinations(
+ team_id=team_id, configuration_id=configuration_id, destinations=destinations
+ )
+
+
+def list_alert_destinations(*, team_id: int, configuration_id: UUID) -> tuple[StoredAlertDestination, ...]:
+ return alert_destinations.list_alert_destinations(team_id=team_id, configuration_id=configuration_id)
+
+
+def delete_alert_destinations(*, team_id: int, configuration_id: UUID, destination_ids: Collection[UUID]) -> int:
+ """Deletes the named destinations of one alert. An id of another alert is left alone."""
+ return alert_destinations.delete_alert_destinations(
+ team_id=team_id, configuration_id=configuration_id, destination_ids=destination_ids
+ )
+
+
def recent_destination_sends(
*, team_id: int, destination_ids: Collection[str], limit: int
) -> tuple[DestinationSend, ...]:
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index 175e2fa84ca6..e66a318644c2 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -1054,6 +1054,35 @@ class AlertDestinationData(TypedDict):
in_app_url: NotRequired[str]
+# The transitions a destination can send about. `CHECK` announces nothing, so no destination hears it.
+DESTINATION_EVENT_KINDS: Final = frozenset(
+ {AlertEventKind.FIRING, AlertEventKind.RESOLVED, AlertEventKind.ERRORED, AlertEventKind.BROKEN}
+)
+
+
+@frozen
+class NewAlertDestination:
+ """One destination to add to an alert the platform owns the destinations of."""
+
+ data: AlertDestinationData
+ event_kinds: tuple[AlertEventKind, ...]
+ enabled: bool = True
+ legacy_hog_function_ids: tuple[UUID, ...] = ()
+
+
+@frozen
+class StoredAlertDestination:
+ """One `AlertDestination` row, with its configuration decrypted."""
+
+ id: UUID
+ configuration_id: UUID
+ data: AlertDestinationData
+ event_kinds: tuple[AlertEventKind, ...]
+ enabled: bool
+ consecutive_failures: int
+ legacy_hog_function_ids: tuple[UUID, ...]
+
+
class AlertDestinationValidationError(Exception):
"""A destination payload the platform refuses. Callers at an HTTP boundary translate
this into their own framework's validation error."""
diff --git a/products/alerts_platform/backend/logic/alert_destinations.py b/products/alerts_platform/backend/logic/alert_destinations.py
new file mode 100644
index 000000000000..a4af08c7d54d
--- /dev/null
+++ b/products/alerts_platform/backend/logic/alert_destinations.py
@@ -0,0 +1,161 @@
+"""The destinations of an alert whose `destinations_owner` is the platform.
+
+The one write path for `AlertDestination`. Each source's alert page and the central page call it
+through the facade, so a destination is valid or refused the same way wherever it is edited.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Collection, Sequence
+from typing import Final, cast
+from uuid import UUID
+
+from django.db import transaction
+
+from products.alerts_platform.backend.delivery.addresses import refused_destination
+from products.alerts_platform.backend.facade.contracts import (
+ DESTINATION_EVENT_KINDS,
+ AlertDestinationData,
+ AlertDestinationValidationError,
+ AlertEventKind,
+ DestinationType,
+ NewAlertDestination,
+ StoredAlertDestination,
+)
+from products.alerts_platform.backend.models import AlertDestination, PlatformAlertConfiguration
+
+_REQUIRED_FIELDS: Final[dict[DestinationType, tuple[str, ...]]] = {
+ DestinationType.SLACK: ("slack_workspace_id", "slack_channel_id"),
+ DestinationType.WEBHOOK: ("webhook_url",),
+ DestinationType.TEAMS: ("webhook_url",),
+ DestinationType.DISCORD: ("webhook_url",),
+ DestinationType.PAGERDUTY: ("pagerduty_routing_key",),
+ DestinationType.EMAIL: ("email_addresses",),
+ DestinationType.IN_APP: ("in_app_user_ids",),
+}
+
+
+def _is_text(value: object) -> bool:
+ return isinstance(value, str)
+
+
+def _is_id(value: object) -> bool:
+ # A bool is an int in Python, but never a valid id.
+ return isinstance(value, int) and not isinstance(value, bool)
+
+
+def _is_list_of(check: Callable[[object], bool]) -> Callable[[object], bool]:
+ return lambda value: isinstance(value, list) and all(check(item) for item in value)
+
+
+_FIELD_CHECKS: Final[dict[str, Callable[[object], bool]]] = {
+ "slack_workspace_id": _is_id,
+ "slack_channel_id": _is_text,
+ "webhook_url": _is_text,
+ "pagerduty_routing_key": _is_text,
+ "email_addresses": _is_list_of(_is_text),
+ "in_app_user_ids": _is_list_of(_is_id),
+}
+
+# A label a person sees. Two destinations that differ only here send to the same place.
+_DISPLAY_ONLY_FIELDS: Final = frozenset({"slack_channel_name"})
+
+
+def create_alert_destinations(
+ *, team_id: int, configuration_id: UUID, destinations: Sequence[NewAlertDestination]
+) -> tuple[StoredAlertDestination, ...]:
+ """Adds the destinations to one configuration, all or none."""
+ for destination in destinations:
+ _validate(destination)
+ with transaction.atomic():
+ # Locked, so two adds of the same destination cannot both pass the duplicate check.
+ configuration = (
+ PlatformAlertConfiguration.objects.for_team(team_id).select_for_update().get(id=configuration_id)
+ )
+ _refuse_duplicates(team_id, configuration_id, destinations)
+ rows = [
+ AlertDestination.objects.for_team(team_id).create(
+ team_id=team_id,
+ configuration=configuration,
+ type=destination.data["type"],
+ config=dict(destination.data),
+ event_kinds=[kind.value for kind in destination.event_kinds],
+ enabled=destination.enabled,
+ legacy_hog_function_ids=list(destination.legacy_hog_function_ids),
+ )
+ for destination in destinations
+ ]
+ return tuple(_stored(row) for row in rows)
+
+
+def list_alert_destinations(*, team_id: int, configuration_id: UUID) -> tuple[StoredAlertDestination, ...]:
+ return tuple(
+ _stored(row)
+ for row in AlertDestination.objects.for_team(team_id)
+ .filter(configuration_id=configuration_id)
+ .order_by("created_at", "id")
+ )
+
+
+def delete_alert_destinations(*, team_id: int, configuration_id: UUID, destination_ids: Collection[UUID]) -> int:
+ """Deletes the named destinations of one configuration, and returns how many it deleted.
+
+ An id of another configuration is left alone, so a caller cannot reach past the alert it checked access to.
+ """
+ deleted, _ = (
+ AlertDestination.objects.for_team(team_id)
+ .filter(configuration_id=configuration_id, id__in=destination_ids)
+ .delete()
+ )
+ return deleted
+
+
+def _refuse_duplicates(team_id: int, configuration_id: UUID, destinations: Sequence[NewAlertDestination]) -> None:
+ """A second destination with the same address would send every message twice."""
+ seen = [
+ _receiver(stored.data) for stored in list_alert_destinations(team_id=team_id, configuration_id=configuration_id)
+ ]
+ for destination in destinations:
+ receiver = _receiver(destination.data)
+ if receiver in seen:
+ raise AlertDestinationValidationError("This alert already sends to this destination.", field="config")
+ seen.append(receiver)
+
+
+def _receiver(data: AlertDestinationData) -> dict[str, object]:
+ """What decides where and how a destination sends, without the fields that only label it."""
+ return {key: value for key, value in data.items() if key not in _DISPLAY_ONLY_FIELDS}
+
+
+def _validate(destination: NewAlertDestination) -> None:
+ destination_type = destination.data.get("type")
+ if destination_type not in DestinationType.values:
+ raise AlertDestinationValidationError("This destination type is not supported.", field="type")
+ required = _REQUIRED_FIELDS[DestinationType(destination_type)]
+ missing = [key for key in required if not destination.data.get(key)]
+ if missing:
+ raise AlertDestinationValidationError(f"This destination needs {', '.join(missing)}.", field="config")
+ malformed = [key for key in required if not _FIELD_CHECKS[key](destination.data.get(key))]
+ if malformed:
+ raise AlertDestinationValidationError(
+ f"This destination has an invalid {', '.join(malformed)}.", field="config"
+ )
+ if not destination.event_kinds:
+ raise AlertDestinationValidationError("Choose at least one event to send.", field="event_kinds")
+ if not set(destination.event_kinds) <= DESTINATION_EVENT_KINDS:
+ raise AlertDestinationValidationError("A destination cannot send about this event.", field="event_kinds")
+ refusal = refused_destination(destination.data)
+ if refusal is not None:
+ raise AlertDestinationValidationError(refusal, field="config")
+
+
+def _stored(row: AlertDestination) -> StoredAlertDestination:
+ return StoredAlertDestination(
+ id=row.id,
+ configuration_id=row.configuration_id,
+ data=cast(AlertDestinationData, row.config),
+ event_kinds=tuple(AlertEventKind(kind) for kind in row.event_kinds),
+ enabled=row.enabled,
+ consecutive_failures=row.consecutive_failures,
+ legacy_hog_function_ids=tuple(row.legacy_hog_function_ids),
+ )
diff --git a/products/alerts_platform/backend/migrations/0018_alert_destination.py b/products/alerts_platform/backend/migrations/0018_alert_destination.py
new file mode 100644
index 000000000000..3a546dc5daa7
--- /dev/null
+++ b/products/alerts_platform/backend/migrations/0018_alert_destination.py
@@ -0,0 +1,106 @@
+# Generated by Django 5.2.18 on 2026-10-21 18:19
+
+import django.db.models.deletion
+import django.contrib.postgres.fields
+from django.db import migrations, models
+
+import posthog.uuidt
+import posthog.helpers.encrypted_fields
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("alerts_platform", "0017_nest_logs_filters"),
+ ("posthog", "1405_user_onboarding_skipped_reason_connector"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="platformalertconfiguration",
+ name="destinations_owner",
+ field=models.CharField(
+ choices=[("source", "Source"), ("platform", "Platform")],
+ db_default="source",
+ default="source",
+ max_length=16,
+ ),
+ ),
+ migrations.CreateModel(
+ name="AlertDestination",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "type",
+ models.CharField(
+ choices=[
+ ("slack", "Slack"),
+ ("discord", "Discord"),
+ ("webhook", "Webhook"),
+ ("teams", "Microsoft Teams"),
+ ("pagerduty", "PagerDuty"),
+ ("email", "Email"),
+ ("in_app", "In-app notification"),
+ ],
+ max_length=32,
+ ),
+ ),
+ (
+ "config",
+ posthog.helpers.encrypted_fields.EncryptedJSONStringField(default=dict),
+ ),
+ (
+ "event_kinds",
+ django.contrib.postgres.fields.ArrayField(
+ base_field=models.CharField(max_length=16),
+ default=list,
+ size=None,
+ ),
+ ),
+ ("enabled", models.BooleanField(db_default=True, default=True)),
+ (
+ "consecutive_failures",
+ models.PositiveIntegerField(db_default=0, default=0),
+ ),
+ ("disabled_reason", models.TextField(blank=True, null=True)),
+ (
+ "legacy_hog_function_ids",
+ django.contrib.postgres.fields.ArrayField(
+ base_field=models.UUIDField(),
+ blank=True,
+ default=list,
+ size=None,
+ ),
+ ),
+ (
+ "configuration",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="destinations",
+ to="alerts_platform.platformalertconfiguration",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "alerts_platformalertdestination",
+ },
+ ),
+ ]
diff --git a/products/alerts_platform/backend/migrations/max_migration.txt b/products/alerts_platform/backend/migrations/max_migration.txt
index 89fdc222ffaf..b0b4c0094007 100644
--- a/products/alerts_platform/backend/migrations/max_migration.txt
+++ b/products/alerts_platform/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0017_nest_logs_filters
+0018_alert_destination
diff --git a/products/alerts_platform/backend/models/__init__.py b/products/alerts_platform/backend/models/__init__.py
index f9389a4daa6e..5ca17dc57461 100644
--- a/products/alerts_platform/backend/models/__init__.py
+++ b/products/alerts_platform/backend/models/__init__.py
@@ -1,6 +1,13 @@
-from .platform_alert import PlatformAlert, PlatformAlertConfiguration, PlatformAlertDeliveryPath, PlatformAlertThread
+from .platform_alert import (
+ AlertDestination,
+ PlatformAlert,
+ PlatformAlertConfiguration,
+ PlatformAlertDeliveryPath,
+ PlatformAlertThread,
+)
__all__ = [
+ "AlertDestination",
"PlatformAlert",
"PlatformAlertConfiguration",
"PlatformAlertDeliveryPath",
diff --git a/products/alerts_platform/backend/models/platform_alert.py b/products/alerts_platform/backend/models/platform_alert.py
index 3424ee1ae2a0..268b3c18b950 100644
--- a/products/alerts_platform/backend/models/platform_alert.py
+++ b/products/alerts_platform/backend/models/platform_alert.py
@@ -10,13 +10,15 @@ source configures on the shared platform, rather than one product's own table.
from typing import Any
+from django.contrib.postgres.fields import ArrayField
from django.db import models
+from posthog.helpers.encrypted_fields import EncryptedJSONStringField
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.utils import UUIDModel
-from products.alerts_platform.backend.facade.contracts import Grouping
+from products.alerts_platform.backend.facade.contracts import DestinationType, Grouping
from products.alerts_platform.backend.facade.enums import (
DeliveryPath,
PlatformAlertCheckStatus,
@@ -108,6 +110,11 @@ class PlatformAlertConfiguration(ModelActivityMixin, TeamScopedRootMixin, UUIDMo
max_length=16, choices=Owner.choices, default=Owner.SOURCE.value, db_default=Owner.SOURCE.value
)
owner_changed_at = models.DateTimeField(null=True, blank=True)
+ # Which rows an alert's destinations live in: the source's HogFunctions, or `AlertDestination`.
+ # Separate from `owner`, because an alert moves its evaluation first and its destinations later.
+ destinations_owner = models.CharField(
+ max_length=16, choices=Owner.choices, default=Owner.SOURCE.value, db_default=Owner.SOURCE.value
+ )
activity_logging_on_delete = True
@@ -257,3 +264,32 @@ class PlatformAlertDeliveryPath(TeamScopedRootMixin, UUIDModel):
name="platform_alert_delivery_path_one_per_episode",
)
]
+
+
+class AlertDestination(TeamScopedRootMixin, UUIDModel):
+ """Where an alert sends, for an alert whose `destinations_owner` is the platform.
+
+ One row is one destination a person sees on the alert's page. It sends through the platform's
+ transport for its type.
+ """
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")
+ configuration = models.ForeignKey(PlatformAlertConfiguration, on_delete=models.CASCADE, related_name="destinations")
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ type = models.CharField(max_length=32, choices=DestinationType.choices)
+ # Encrypted as one document so its value types survive a read. A webhook URL or a routing key is a credential.
+ config = EncryptedJSONStringField(default=dict)
+ # The transitions it sends about, as `AlertEventKind` values.
+ event_kinds = ArrayField(models.CharField(max_length=16), default=list)
+ enabled = models.BooleanField(default=True, db_default=True)
+
+ consecutive_failures = models.PositiveIntegerField(default=0, db_default=0)
+ disabled_reason = models.TextField(null=True, blank=True)
+
+ # The HogFunctions this replaced, so an id issued before the move still finds the destination.
+ legacy_hog_function_ids = ArrayField(models.UUIDField(), default=list, blank=True)
+
+ class Meta:
+ db_table = "alerts_platformalertdestination"
diff --git a/products/alerts_platform/backend/tests/test_alert_destinations.py b/products/alerts_platform/backend/tests/test_alert_destinations.py
new file mode 100644
index 000000000000..1e100886ede6
--- /dev/null
+++ b/products/alerts_platform/backend/tests/test_alert_destinations.py
@@ -0,0 +1,147 @@
+from typing import Any, cast
+from uuid import uuid4
+
+import pytest
+from posthog.test.base import BaseTest
+
+from django.db import connection
+
+from parameterized import parameterized
+
+from products.alerts_platform.backend.facade.api import (
+ create_alert_destinations,
+ delete_alert_destinations,
+ list_alert_destinations,
+)
+from products.alerts_platform.backend.facade.contracts import (
+ AlertDestinationData,
+ AlertDestinationValidationError,
+ AlertEventKind,
+ DestinationType,
+ NewAlertDestination,
+ SourceKind,
+)
+from products.alerts_platform.backend.models import PlatformAlertConfiguration
+
+WEBHOOK_URL = "https://example.com/hooks/secret-path"
+WEBHOOK = cast(AlertDestinationData, {"type": DestinationType.WEBHOOK, "webhook_url": WEBHOOK_URL})
+FIRING = (AlertEventKind.FIRING,)
+
+
+class TestAlertDestinations(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.configuration = self._configuration()
+
+ def _configuration(self) -> PlatformAlertConfiguration:
+ return PlatformAlertConfiguration.objects.for_team(self.team.id).create(
+ team=self.team, name="API errors", source_kind=SourceKind.LOGS, check_interval_minutes=5
+ )
+
+ def _create(self, *destinations: NewAlertDestination, configuration: Any = None) -> Any:
+ return create_alert_destinations(
+ team_id=self.team.id,
+ configuration_id=(configuration or self.configuration).id,
+ destinations=destinations,
+ )
+
+ def test_a_destination_reads_back_as_written_and_its_address_is_encrypted_at_rest(self) -> None:
+ legacy_id = uuid4()
+ created = self._create(
+ NewAlertDestination(data=WEBHOOK, event_kinds=FIRING, legacy_hog_function_ids=(legacy_id,)),
+ NewAlertDestination(
+ data=cast(AlertDestinationData, {**WEBHOOK, "webhook_url": "https://example.com/hooks/other"}),
+ event_kinds=(AlertEventKind.FIRING, AlertEventKind.RESOLVED),
+ enabled=False,
+ ),
+ )
+
+ assert list_alert_destinations(team_id=self.team.id, configuration_id=self.configuration.id) == created
+ assert [(d.enabled, d.legacy_hog_function_ids) for d in created] == [(True, (legacy_id,)), (False, ())]
+ assert created[0].data["webhook_url"] == WEBHOOK_URL
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT config::text FROM alerts_platformalertdestination")
+ assert all(WEBHOOK_URL not in row[0] for row in cursor.fetchall())
+
+ @parameterized.expand(
+ [
+ ("no_event", {"event_kinds": ()}, "event_kinds"),
+ ("check_event", {"event_kinds": (AlertEventKind.CHECK,)}, "event_kinds"),
+ (
+ "plain_http_address",
+ {"data": {"type": DestinationType.WEBHOOK, "webhook_url": "http://example.com/h"}},
+ "config",
+ ),
+ ("unknown_type", {"data": {"type": "opsgenie"}}, "type"),
+ ("webhook_without_its_url", {"data": {"type": DestinationType.WEBHOOK}}, "config"),
+ ("webhook_url_not_text", {"data": {"type": DestinationType.WEBHOOK, "webhook_url": 123}}, "config"),
+ (
+ "routing_key_not_text",
+ {"data": {"type": DestinationType.PAGERDUTY, "pagerduty_routing_key": 123}},
+ "config",
+ ),
+ (
+ "email_not_a_list",
+ {"data": {"type": DestinationType.EMAIL, "email_addresses": "[email protected]"}},
+ "config",
+ ),
+ ("user_id_not_a_number", {"data": {"type": DestinationType.IN_APP, "in_app_user_ids": ["1"]}}, "config"),
+ ]
+ )
+ def test_a_refused_destination_writes_nothing_of_its_batch(
+ self, _name: str, override: dict[str, Any], field: str
+ ) -> None:
+ valid = NewAlertDestination(data=WEBHOOK, event_kinds=FIRING)
+ refused = NewAlertDestination(**{"data": WEBHOOK, "event_kinds": FIRING, **override})
+
+ with pytest.raises(AlertDestinationValidationError) as error:
+ self._create(valid, refused)
+
+ assert error.value.field == field
+ assert list_alert_destinations(team_id=self.team.id, configuration_id=self.configuration.id) == ()
+
+ @parameterized.expand(
+ [
+ ("same_webhook", WEBHOOK, dict(WEBHOOK)),
+ (
+ "same_slack_channel_with_another_label",
+ {
+ "type": DestinationType.SLACK,
+ "slack_workspace_id": 7,
+ "slack_channel_id": "C1",
+ "slack_channel_name": "a",
+ },
+ {
+ "type": DestinationType.SLACK,
+ "slack_workspace_id": 7,
+ "slack_channel_id": "C1",
+ "slack_channel_name": "b",
+ },
+ ),
+ ]
+ )
+ def test_a_destination_the_alert_already_sends_to_is_refused(
+ self, _name: str, first: dict[str, Any], second: dict[str, Any]
+ ) -> None:
+ self._create(NewAlertDestination(data=cast(AlertDestinationData, first), event_kinds=FIRING))
+
+ with pytest.raises(AlertDestinationValidationError) as error:
+ self._create(
+ NewAlertDestination(data=cast(AlertDestinationData, second), event_kinds=(AlertEventKind.RESOLVED,))
+ )
+
+ assert error.value.field == "config"
+ assert len(list_alert_destinations(team_id=self.team.id, configuration_id=self.configuration.id)) == 1
+
+ def test_a_delete_reaches_only_the_alert_it_names(self) -> None:
+ other = self._configuration()
+ (mine,) = self._create(NewAlertDestination(data=WEBHOOK, event_kinds=FIRING))
+ (theirs,) = self._create(NewAlertDestination(data=WEBHOOK, event_kinds=FIRING), configuration=other)
+
+ deleted = delete_alert_destinations(
+ team_id=self.team.id, configuration_id=self.configuration.id, destination_ids=[mine.id, theirs.id]
+ )
+
+ assert deleted == 1
+ assert list_alert_destinations(team_id=self.team.id, configuration_id=self.configuration.id) == ()
+ assert list_alert_destinations(team_id=self.team.id, configuration_id=other.id) == (theirs,)