From 692fea71d426e995dc8f3a3af47d75262e64e15f Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:18:40 +0000 Subject: [PATCH 1/2] ref(releases): Remove unused release threshold code Release thresholds have no UI, and their endpoints are experimental. The last caller was the getsentry canary deploy check, which getsentry/getsentry#22979 removed. Remove the endpoints, serializer, health-check helpers, and tests, and move the ReleaseThreshold model to pending deletion. A follow-up migration drops the table after this deploys. Refs ISWF-3793 Co-Authored-By: Athena Moghaddam <132939361+sentaur-athena@users.noreply.github.com> --- .github/CODEOWNERS | 2 - migrations_lockfile.txt | 2 +- .../endpoints/release_thresholds/__init__.py | 0 .../endpoints/release_thresholds/constants.py | 2 - .../health_checks/__init__.py | 3 - .../is_crash_free_rate_healthy.py | 134 ---- .../health_checks/is_error_count_healthy.py | 64 -- .../is_new_issues_count_healthy.py | 23 - .../release_thresholds/release_threshold.py | 87 --- .../release_threshold_details.py | 103 --- .../release_threshold_index.py | 72 -- .../release_threshold_status_index.py | 475 ------------ .../api/endpoints/release_thresholds/types.py | 65 -- .../release_thresholds/utils/__init__.py | 3 - .../utils/fetch_sessions_data.py | 50 -- .../utils/get_errors_counts_timeseries.py | 213 ------ .../utils/get_new_issue_counts.py | 44 -- src/sentry/api/serializers/models/__init__.py | 1 - .../serializers/models/release_threshold.py | 48 -- src/sentry/api/urls.py | 31 - .../examples/release_threshold_examples.py | 36 - .../api_pagination_allowlist_do_not_modify.py | 1 - src/sentry/db/router.py | 1 + src/sentry/deletions/defaults/project.py | 2 - .../1264_remove_release_threshold.py | 56 ++ src/sentry/models/__init__.py | 1 - .../models/release_threshold/__init__.py | 3 - .../models/release_threshold/constants.py | 108 --- .../release_threshold/release_threshold.py | 34 - src/sentry/web/urls.py | 5 - .../utils/api/knownSentryApiUrls.generated.ts | 4 - .../endpoints/release_thresholds/__init__.py | 0 .../health_checks/__init__.py | 0 .../health_checks/test_fixtures.py | 157 ---- .../test_is_crash_free_rate_healthy.py | 355 --------- .../test_is_error_count_healthy.py | 684 ------------------ .../test_is_new_issue_count_healthy.py | 169 ----- .../test_release_threshold.py | 237 ------ .../test_release_threshold_details.py | 329 --------- .../test_release_threshold_status.py | 650 ----------------- .../test_release_thresholds_index.py | 175 ----- .../utils/test_fetch_sessions_data.py | 8 - .../test_get_errors_counts_timeseries.py | 220 ------ .../utils/test_get_new_issue_counts.py | 143 ---- .../test_organization_agent_token.py | 6 - 45 files changed, 58 insertions(+), 4748 deletions(-) delete mode 100644 src/sentry/api/endpoints/release_thresholds/__init__.py delete mode 100644 src/sentry/api/endpoints/release_thresholds/constants.py delete mode 100644 src/sentry/api/endpoints/release_thresholds/health_checks/__init__.py delete mode 100644 src/sentry/api/endpoints/release_thresholds/health_checks/is_crash_free_rate_healthy.py delete mode 100644 src/sentry/api/endpoints/release_thresholds/health_checks/is_error_count_healthy.py delete mode 100644 src/sentry/api/endpoints/release_thresholds/health_checks/is_new_issues_count_healthy.py delete mode 100644 src/sentry/api/endpoints/release_thresholds/release_threshold.py delete mode 100644 src/sentry/api/endpoints/release_thresholds/release_threshold_details.py delete mode 100644 src/sentry/api/endpoints/release_thresholds/release_threshold_index.py delete mode 100644 src/sentry/api/endpoints/release_thresholds/release_threshold_status_index.py delete mode 100644 src/sentry/api/endpoints/release_thresholds/types.py delete mode 100644 src/sentry/api/endpoints/release_thresholds/utils/__init__.py delete mode 100644 src/sentry/api/endpoints/release_thresholds/utils/fetch_sessions_data.py delete mode 100644 src/sentry/api/endpoints/release_thresholds/utils/get_errors_counts_timeseries.py delete mode 100644 src/sentry/api/endpoints/release_thresholds/utils/get_new_issue_counts.py delete mode 100644 src/sentry/api/serializers/models/release_threshold.py delete mode 100644 src/sentry/apidocs/examples/release_threshold_examples.py create mode 100644 src/sentry/migrations/1264_remove_release_threshold.py delete mode 100644 src/sentry/models/release_threshold/__init__.py delete mode 100644 src/sentry/models/release_threshold/constants.py delete mode 100644 src/sentry/models/release_threshold/release_threshold.py delete mode 100644 tests/sentry/api/endpoints/release_thresholds/__init__.py delete mode 100644 tests/sentry/api/endpoints/release_thresholds/health_checks/__init__.py delete mode 100644 tests/sentry/api/endpoints/release_thresholds/health_checks/test_fixtures.py delete mode 100644 tests/sentry/api/endpoints/release_thresholds/health_checks/test_is_crash_free_rate_healthy.py delete mode 100644 tests/sentry/api/endpoints/release_thresholds/health_checks/test_is_error_count_healthy.py delete mode 100644 tests/sentry/api/endpoints/release_thresholds/health_checks/test_is_new_issue_count_healthy.py delete mode 100644 tests/sentry/api/endpoints/release_thresholds/test_release_threshold.py delete mode 100644 tests/sentry/api/endpoints/release_thresholds/test_release_threshold_details.py delete mode 100644 tests/sentry/api/endpoints/release_thresholds/test_release_threshold_status.py delete mode 100644 tests/sentry/api/endpoints/release_thresholds/test_release_thresholds_index.py delete mode 100644 tests/sentry/api/endpoints/release_thresholds/utils/test_fetch_sessions_data.py delete mode 100644 tests/sentry/api/endpoints/release_thresholds/utils/test_get_errors_counts_timeseries.py delete mode 100644 tests/sentry/api/endpoints/release_thresholds/utils/test_get_new_issue_counts.py diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 1febc19389e9..6e1520fb08d8 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -607,11 +607,9 @@ tests/sentry/api/endpoints/test_organization_attribute_mappings.py @get /src/sentry/api/endpoints/organization_auditlogs.py @getsentry/foundations /src/sentry/core/endpoints/organization_projects.py @getsentry/foundations /src/sentry/api/endpoints/organization_stats*.py @getsentry/foundations -/src/sentry/api/endpoints/release_threshold*.py @getsentry/replay /src/sentry/api/endpoints/user_social_identity* @getsentry/foundations /src/sentry/auth/staff.py @getsentry/foundations @getsentry/owners-auth /src/sentry/auth/superuser.py @getsentry/foundations @getsentry/owners-auth -/src/sentry/models/release_threshold/ @getsentry/replay /src/sentry/scim/ @getsentry/foundations /src/sentry/integrations/github/ @getsentry/foundations @getsentry/scm /src/sentry/web/frontend/auth_login.py @getsentry/foundations @getsentry/owners-auth diff --git a/migrations_lockfile.txt b/migrations_lockfile.txt index 6e749f71030a..2c8aca600a2b 100644 --- a/migrations_lockfile.txt +++ b/migrations_lockfile.txt @@ -41,7 +41,7 @@ seer: 0048_remove_seer_workflow_trigger_binding seer_workflow_outputs: 0001_initial -sentry: 1263_add_groupsearchview_non_user_creator +sentry: 1264_remove_release_threshold service_accounts: 0008_add_owner_kind diff --git a/src/sentry/api/endpoints/release_thresholds/__init__.py b/src/sentry/api/endpoints/release_thresholds/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/src/sentry/api/endpoints/release_thresholds/constants.py b/src/sentry/api/endpoints/release_thresholds/constants.py deleted file mode 100644 index 9188a8b1f48e..000000000000 --- a/src/sentry/api/endpoints/release_thresholds/constants.py +++ /dev/null @@ -1,2 +0,0 @@ -CRASH_SESSIONS_DISPLAY: str = "sessions" -CRASH_USERS_DISPLAY: str = "users" diff --git a/src/sentry/api/endpoints/release_thresholds/health_checks/__init__.py b/src/sentry/api/endpoints/release_thresholds/health_checks/__init__.py deleted file mode 100644 index e1ab8d12b01e..000000000000 --- a/src/sentry/api/endpoints/release_thresholds/health_checks/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .is_crash_free_rate_healthy import * # noqa: F401,F403 -from .is_error_count_healthy import * # noqa: F401,F403 -from .is_new_issues_count_healthy import * # noqa: F401,F403 diff --git a/src/sentry/api/endpoints/release_thresholds/health_checks/is_crash_free_rate_healthy.py b/src/sentry/api/endpoints/release_thresholds/health_checks/is_crash_free_rate_healthy.py deleted file mode 100644 index d8e38821d3fd..000000000000 --- a/src/sentry/api/endpoints/release_thresholds/health_checks/is_crash_free_rate_healthy.py +++ /dev/null @@ -1,134 +0,0 @@ -from __future__ import annotations - -import logging -from datetime import datetime -from typing import TYPE_CHECKING, Any - -from dateutil import parser - -from sentry.models.release_threshold.constants import TriggerType - -from ..constants import CRASH_USERS_DISPLAY - -logger = logging.getLogger("sentry.release_threshold_status.is_crash_free_rate_healthy") - -if TYPE_CHECKING: - from sentry.api.endpoints.release_thresholds.types import EnrichedThreshold - - -def get_groups_totals( - sessions_data: dict[str, Any], - release_version: str, - project_id: int, - field: str, - start_idx: int, - end_idx: int, - environment: str | None = None, - status: str | None = None, -) -> int: - group_series: list[dict[str, Any]] = [ - g.get("series", {}) - for g in sessions_data.get("groups", []) - if g.get("by", {}).get("release") == release_version - and g.get("by", {}).get("project") == project_id - and (g.get("by", {}).get("environment") == environment if environment else True) - and (g.get("by", {}).get("session.status") == status if status else True) - ] - total = 0 - for group in group_series: - series = group.get(field, []) - if len(series) < start_idx or len(series) < end_idx: - logger.warning( - "Error calculating session totals", - extra={"start_idx": start_idx, "end_idx": end_idx, "series_length": len(series)}, - ) - raise IndexError("Start/End indexes are out of range for series") - total += sum(series[start_idx : end_idx + 1]) - return total - - -def get_interval_indexes(intervals: list[str], start: datetime, end: datetime) -> tuple[int, int]: - """ - :param intervals: if timestamps from fetched sessions data - :param start: timestamp - :param end: timestamp - - :return: If any subsection of the intervals fall within the given start/end, return the indexes of both the start and the end - - TODO: raise if start/end not contained within intervals? - """ - start_idx = len(intervals) - end_idx = 0 - - for idx, i in enumerate(intervals): - interval_date = parser.parse(i).replace(tzinfo=None) - if start <= interval_date < end: - if idx < start_idx: - start_idx = idx - if end_idx < idx: - end_idx = idx - - return start_idx, end_idx - - -def is_crash_free_rate_healthy_check( - ethreshold: EnrichedThreshold, - sessions_data: dict[str, Any], - display: str, -) -> tuple[bool, float]: # (is_healthy, metric_value) - """ - Derives percent from crash total over total count - - NOTE: Logic mirrors Frontend views/releases/list/releasesRequest::getCrashFreeRate - NOTE: if 'environment' not provided, will tally sums for _all_ sessions data as opposed to only sessions with environment of 'None' - """ - field = "count_unique(user)" if display == CRASH_USERS_DISPLAY else "sum(session)" - release_version = ethreshold["release"] - project_id = ethreshold["project_id"] - environment = ethreshold["environment"] - intervals = sessions_data.get("intervals", []) - try: - start_idx, end_idx = get_interval_indexes( - intervals=intervals, start=ethreshold["start"], end=ethreshold["end"] - ) - if start_idx > end_idx: - logger.warning("Threshold window not within provided session data") - raise ValueError("Threshold window not within provided session data") - except ValueError: - return False, -1 - - try: - crash_count = get_groups_totals( - end_idx=end_idx, - environment=environment.get("name") if environment else None, - field=field, - project_id=project_id, - release_version=release_version, - sessions_data=sessions_data, - start_idx=start_idx, - status="crashed", - ) - except IndexError: - return False, -1 - - try: - total_count = get_groups_totals( - end_idx=end_idx, - environment=environment.get("name") if environment else None, - field=field, - project_id=project_id, - release_version=release_version, - sessions_data=sessions_data, - start_idx=start_idx, - ) - except IndexError: - return False, -1 - - crash_free_percent = (1 - (crash_count / max(total_count, 1))) * 100 - - if ethreshold["trigger_type"] == TriggerType.OVER_STR: - # we're healthy as long as we're under the threshold - return crash_free_percent < ethreshold["value"], crash_free_percent - - # we're healthy as long as we're over the threshold - return crash_free_percent > ethreshold["value"], crash_free_percent diff --git a/src/sentry/api/endpoints/release_thresholds/health_checks/is_error_count_healthy.py b/src/sentry/api/endpoints/release_thresholds/health_checks/is_error_count_healthy.py deleted file mode 100644 index e20a616324c8..000000000000 --- a/src/sentry/api/endpoints/release_thresholds/health_checks/is_error_count_healthy.py +++ /dev/null @@ -1,64 +0,0 @@ -from __future__ import annotations - -import logging -from typing import TYPE_CHECKING, Any - -from dateutil import parser - -from sentry.models.release_threshold.constants import TriggerType -from sentry.utils import metrics - -logger = logging.getLogger("sentry.release_threshold_status.is_error_count_healthy") - -if TYPE_CHECKING: - from sentry.api.endpoints.release_thresholds.types import EnrichedThreshold - - -def is_error_count_healthy( - ethreshold: EnrichedThreshold, timeseries: list[dict[str, Any]] -) -> tuple[bool, int]: - """ - Iterate through timeseries given threshold window and determine health status - enriched threshold (ethreshold) includes `start`, `end`, and a constructed `key` identifier - """ - total_count = 0 - threshold_environment: str | None = ( - ethreshold["environment"]["name"] if ethreshold["environment"] else None - ) - sorted_series = sorted(timeseries, key=lambda x: x["time"]) - for i in sorted_series: - if parser.parse(i["time"]) > ethreshold["end"]: - # timeseries are ordered chronologically - # So if we're past our threshold.end, we can skip the rest - logger.info("Reached end of threshold window. Breaking") - metrics.incr("release.threshold_health_status.is_error_count_healthy.break_loop") - break - if ( - parser.parse(i["time"]) <= ethreshold["start"] # ts is before our threshold start - or parser.parse(i["time"]) > ethreshold["end"] # ts is after our threshold end - or i["release"] != ethreshold["release"] # ts is not our the right release - or i["project_id"] != ethreshold["project_id"] # ts is not the right project - or i["environment"] != threshold_environment # ts is not the right environment - ): - metrics.incr("release.threshold_health_status.is_error_count_healthy.skip") - continue - # else ethreshold.start < i.time <= ethreshold.end - metrics.incr("release.threshold_health_status.is_error_count_healthy.aggregate_total") - total_count += i["count()"] - - logger.info( - "check", - extra={ - "threshold": ethreshold, - "total_count": total_count, - "error_count_data": timeseries, - "threshold_environment": threshold_environment, - }, - ) - - if ethreshold["trigger_type"] == TriggerType.OVER_STR: - # If total is under/equal the threshold value, then it is healthy - return total_count <= ethreshold["value"], total_count - - # Else, if total is over/equal the threshold value, then it is healthy - return total_count >= ethreshold["value"], total_count diff --git a/src/sentry/api/endpoints/release_thresholds/health_checks/is_new_issues_count_healthy.py b/src/sentry/api/endpoints/release_thresholds/health_checks/is_new_issues_count_healthy.py deleted file mode 100644 index eae8534efee6..000000000000 --- a/src/sentry/api/endpoints/release_thresholds/health_checks/is_new_issues_count_healthy.py +++ /dev/null @@ -1,23 +0,0 @@ -from __future__ import annotations - -import logging -from typing import TYPE_CHECKING, Any - -from sentry.models.release_threshold.constants import TriggerType - -logger = logging.getLogger("sentry.release_threshold_status.is_new_issues_count_healthy") - -if TYPE_CHECKING: - from sentry.api.endpoints.release_thresholds.types import EnrichedThreshold - - -def is_new_issue_count_healthy( - ethreshold: EnrichedThreshold, new_issue_counts: dict[str, Any] -) -> tuple[bool, int]: - new_issue_count = new_issue_counts.get(str(ethreshold["id"]), 0) - if ethreshold["trigger_type"] == TriggerType.OVER_STR: - # If total is under/equal the threshold value, then it is healthy - return new_issue_count <= ethreshold["value"], new_issue_count - - # Else, if total is over/equal the threshold value, then it is healthy - return new_issue_count >= ethreshold["value"], new_issue_count diff --git a/src/sentry/api/endpoints/release_thresholds/release_threshold.py b/src/sentry/api/endpoints/release_thresholds/release_threshold.py deleted file mode 100644 index 6812711fbb36..000000000000 --- a/src/sentry/api/endpoints/release_thresholds/release_threshold.py +++ /dev/null @@ -1,87 +0,0 @@ -from typing import TypedDict - -from django.http import HttpResponse -from rest_framework import serializers -from rest_framework.request import Request -from rest_framework.response import Response - -from sentry.api.api_owners import ApiOwner -from sentry.api.api_publish_status import ApiPublishStatus -from sentry.api.base import cell_silo_endpoint -from sentry.api.bases.project import ProjectEndpoint, ProjectReleasePermission -from sentry.api.serializers import serialize -from sentry.api.serializers.rest_framework.environment import EnvironmentField -from sentry.models.project import Project -from sentry.models.release_threshold.constants import ( - THRESHOLD_TYPE_STR_TO_INT, - TRIGGER_TYPE_STRING_TO_INT, - ReleaseThresholdType, -) -from sentry.models.release_threshold.constants import TriggerType as ReleaseThresholdTriggerType -from sentry.models.release_threshold.release_threshold import ReleaseThreshold - - -class ReleaseThresholdPOSTData(TypedDict, total=False): - threshold_type: int - trigger_type: int - value: int - window_in_seconds: int - environment: object - - -class ReleaseThresholdPOSTSerializer(serializers.Serializer[ReleaseThresholdPOSTData]): - threshold_type = serializers.ChoiceField(choices=ReleaseThresholdType.as_str_choices()) - trigger_type = serializers.ChoiceField(choices=ReleaseThresholdTriggerType.as_str_choices()) - value = serializers.IntegerField(required=True, min_value=0) - window_in_seconds = serializers.IntegerField(required=True, min_value=0) - environment = EnvironmentField(required=False, allow_null=True) - - def validate_threshold_type(self, threshold_type: str) -> int: - if threshold_type not in THRESHOLD_TYPE_STR_TO_INT: - raise serializers.ValidationError("Invalid threshold type") - return THRESHOLD_TYPE_STR_TO_INT[threshold_type] - - def validate_trigger_type(self, trigger_type: str) -> int: - if trigger_type not in TRIGGER_TYPE_STRING_TO_INT: - raise serializers.ValidationError("Invalid trigger type") - return TRIGGER_TYPE_STRING_TO_INT[trigger_type] - - -@cell_silo_endpoint -class ReleaseThresholdEndpoint(ProjectEndpoint): - permission_classes = (ProjectReleasePermission,) - owner: ApiOwner = ApiOwner.REPLAY - publish_status = { - "GET": ApiPublishStatus.EXPERIMENTAL, - "POST": ApiPublishStatus.EXPERIMENTAL, - } - - def post(self, request: Request, project: Project) -> HttpResponse: - serializer = ReleaseThresholdPOSTSerializer( - data=request.data, - context={ - "organization": project.organization, - "access": request.access, - }, - ) - if not serializer.is_valid(): - return Response(serializer.errors, status=400) - result = serializer.validated_data - - release_threshold = ReleaseThreshold.objects.create( - threshold_type=result.get("threshold_type"), - trigger_type=result.get("trigger_type"), - value=result.get("value"), - window_in_seconds=result.get("window_in_seconds"), - project=project, - environment=result.get("environment"), - ) - return Response(serialize(release_threshold, request.user), status=201) - - def get(self, request: Request, project: Project) -> HttpResponse: - release_thresholds = ReleaseThreshold.objects.filter(project=project) - environment_name: str | None = request.GET.get("environment") - - if environment_name: - release_thresholds = release_thresholds.filter(environment__name=environment_name) - return Response(serialize(list(release_thresholds), request.user), status=200) diff --git a/src/sentry/api/endpoints/release_thresholds/release_threshold_details.py b/src/sentry/api/endpoints/release_thresholds/release_threshold_details.py deleted file mode 100644 index c2b1a595a8bf..000000000000 --- a/src/sentry/api/endpoints/release_thresholds/release_threshold_details.py +++ /dev/null @@ -1,103 +0,0 @@ -import logging -from typing import Any, TypedDict - -from django.http import HttpResponse -from rest_framework import serializers -from rest_framework.request import Request -from rest_framework.response import Response - -from sentry.api.api_owners import ApiOwner -from sentry.api.api_publish_status import ApiPublishStatus -from sentry.api.base import cell_silo_endpoint -from sentry.api.bases.project import ProjectEndpoint, ProjectReleasePermission -from sentry.api.exceptions import ResourceDoesNotExist -from sentry.api.serializers import serialize -from sentry.api.utils import to_valid_int_id -from sentry.models.project import Project -from sentry.models.release_threshold.constants import ( - THRESHOLD_TYPE_STR_TO_INT, - TRIGGER_TYPE_STRING_TO_INT, - ReleaseThresholdType, -) -from sentry.models.release_threshold.constants import TriggerType as ReleaseThresholdTriggerType -from sentry.models.release_threshold.release_threshold import ReleaseThreshold - - -class ReleaseThresholdPUTData(TypedDict): - threshold_type: int - trigger_type: int - value: int - window_in_seconds: int - - -logger = logging.getLogger("sentry.release_thresholds") - - -class ReleaseThresholdPUTSerializer(serializers.Serializer[ReleaseThresholdPUTData]): - threshold_type = serializers.ChoiceField(choices=ReleaseThresholdType.as_str_choices()) - trigger_type = serializers.ChoiceField(choices=ReleaseThresholdTriggerType.as_str_choices()) - value = serializers.IntegerField(required=True, min_value=0) - window_in_seconds = serializers.IntegerField(required=True, min_value=0) - - def validate_threshold_type(self, threshold_type: str) -> int: - if threshold_type not in THRESHOLD_TYPE_STR_TO_INT: - raise serializers.ValidationError("Invalid threshold type") - return THRESHOLD_TYPE_STR_TO_INT[threshold_type] - - def validate_trigger_type(self, trigger_type: str) -> int: - if trigger_type not in TRIGGER_TYPE_STRING_TO_INT: - raise serializers.ValidationError("Invalid trigger type") - return TRIGGER_TYPE_STRING_TO_INT[trigger_type] - - -@cell_silo_endpoint -class ReleaseThresholdDetailsEndpoint(ProjectEndpoint): - permission_classes = (ProjectReleasePermission,) - owner: ApiOwner = ApiOwner.REPLAY - publish_status = { - "DELETE": ApiPublishStatus.EXPERIMENTAL, - "GET": ApiPublishStatus.EXPERIMENTAL, - "PUT": ApiPublishStatus.EXPERIMENTAL, - } - - def convert_args( - self, - request: Request, - *args: Any, - **kwargs: Any, - ) -> tuple[tuple[Any, ...], dict[str, Any]]: - parsed_args, parsed_kwargs = super().convert_args(request, *args, **kwargs) - validated_id = to_valid_int_id( - "release_threshold", kwargs["release_threshold"], raise_404=True - ) - try: - parsed_kwargs["release_threshold"] = ReleaseThreshold.objects.get( - id=validated_id, - project=parsed_kwargs["project"], - ) - except ReleaseThreshold.DoesNotExist: - raise ResourceDoesNotExist - return parsed_args, parsed_kwargs - - def get( - self, request: Request, project: Project, release_threshold: ReleaseThreshold - ) -> HttpResponse: - return Response(serialize(release_threshold, request.user), status=200) - - def put( - self, request: Request, project: Project, release_threshold: ReleaseThreshold - ) -> HttpResponse: - serializer = ReleaseThresholdPUTSerializer(data=request.data) - - if not serializer.is_valid(): - return Response(serializer.errors, status=400) - - validated_data = serializer.validated_data - release_threshold.update(**validated_data) - return Response(serialize(release_threshold, request.user), status=200) - - def delete( - self, request: Request, project: Project, release_threshold: ReleaseThreshold - ) -> HttpResponse: - release_threshold.delete() - return Response(status=204) diff --git a/src/sentry/api/endpoints/release_thresholds/release_threshold_index.py b/src/sentry/api/endpoints/release_thresholds/release_threshold_index.py deleted file mode 100644 index b6d1827dd233..000000000000 --- a/src/sentry/api/endpoints/release_thresholds/release_threshold_index.py +++ /dev/null @@ -1,72 +0,0 @@ -from typing import TypedDict - -from django.db.models import Q -from django.http import HttpResponse -from rest_framework import serializers -from rest_framework.request import Request -from rest_framework.response import Response - -from sentry.api.api_owners import ApiOwner -from sentry.api.api_publish_status import ApiPublishStatus -from sentry.api.base import cell_silo_endpoint -from sentry.api.bases.organization import OrganizationEndpoint -from sentry.api.helpers.projects import ProjectIdOrSlug, ProjectIdOrSlugField -from sentry.api.paginator import OffsetPaginator -from sentry.api.serializers import serialize -from sentry.constants import ALL_ACCESS_PROJECTS_SLUG -from sentry.models.organization import Organization -from sentry.models.release_threshold.release_threshold import ReleaseThreshold - - -class ReleaseThresholdIndexGETData(TypedDict, total=False): - environment: list[str] - project: list[ProjectIdOrSlug] - - -class ReleaseThresholdIndexGETValidator(serializers.Serializer[ReleaseThresholdIndexGETData]): - environment = serializers.ListField( - required=False, allow_empty=True, child=serializers.CharField() - ) - project = serializers.ListField(required=True, allow_empty=False, child=ProjectIdOrSlugField()) - - def validate_project(self, value: list[ProjectIdOrSlug]) -> list[ProjectIdOrSlug]: - if ALL_ACCESS_PROJECTS_SLUG in value: - raise serializers.ValidationError("Invalid project") - return value - - -@cell_silo_endpoint -class ReleaseThresholdIndexEndpoint(OrganizationEndpoint): - owner: ApiOwner = ApiOwner.REPLAY - publish_status = { - "GET": ApiPublishStatus.EXPERIMENTAL, - } - - def get(self, request: Request, organization: Organization) -> HttpResponse: - validator = ReleaseThresholdIndexGETValidator( - data=self.get_query_params_without_empty_project_params(request), - ) - if not validator.is_valid(): - return Response(validator.errors, status=400) - - environments_list = self.get_environments(request, organization) - projects_list = self.get_projects(request, organization) - - # `projects_list` is already organization-scoped by `get_projects`, so - # `project__in=projects_list` both narrows to the caller's projects and - # prevents cross-tenant reads. An empty list yields zero rows. - release_query = Q(project__in=projects_list) - if environments_list: - release_query &= Q( - environment__in=environments_list, - ) - - queryset = ReleaseThreshold.objects.filter(release_query) - - return self.paginate( - request=request, - queryset=queryset, - order_by="date_added", - paginator_cls=OffsetPaginator, - on_results=lambda x: serialize(x, request.user), - ) diff --git a/src/sentry/api/endpoints/release_thresholds/release_threshold_status_index.py b/src/sentry/api/endpoints/release_thresholds/release_threshold_status_index.py deleted file mode 100644 index 32e2a6230da6..000000000000 --- a/src/sentry/api/endpoints/release_thresholds/release_threshold_status_index.py +++ /dev/null @@ -1,475 +0,0 @@ -from __future__ import annotations - -import logging -from collections import defaultdict -from datetime import datetime, timedelta, timezone -from typing import TYPE_CHECKING, Any, TypedDict - -from django.db.models import F, Q -from drf_spectacular.utils import extend_schema -from rest_framework import serializers -from rest_framework.request import Request -from rest_framework.response import Response - -from sentry.api.api_owners import ApiOwner -from sentry.api.api_publish_status import ApiPublishStatus -from sentry.api.base import cell_silo_endpoint -from sentry.api.bases import NoProjects -from sentry.api.bases.organization import OrganizationReleasesBaseEndpoint -from sentry.api.endpoints.release_thresholds.constants import CRASH_SESSIONS_DISPLAY -from sentry.api.endpoints.release_thresholds.health_checks import ( - is_crash_free_rate_healthy_check, - is_error_count_healthy, - is_new_issue_count_healthy, -) -from sentry.api.endpoints.release_thresholds.types import EnrichedThreshold -from sentry.api.endpoints.release_thresholds.utils import ( - fetch_sessions_data, - get_errors_counts_timeseries_by_project_and_release, - get_new_issue_counts, -) -from sentry.api.helpers.projects import ( - ProjectIdOrSlug, - ProjectIdOrSlugField, - parse_id_or_slug_params, -) -from sentry.api.serializers import serialize -from sentry.apidocs.constants import RESPONSE_BAD_REQUEST -from sentry.apidocs.examples.release_threshold_examples import ReleaseThresholdExamples -from sentry.apidocs.parameters import GlobalParams -from sentry.apidocs.response_types import ValidationErrorResponse, as_validation_errors -from sentry.apidocs.utils import inline_sentry_response_serializer -from sentry.models.release import Release -from sentry.models.release_threshold.constants import ReleaseThresholdType -from sentry.organizations.services.organization import RpcOrganization -from sentry.release_health.base import SessionsQueryResult -from sentry.utils import metrics - -logger = logging.getLogger("sentry.release_threshold_status") - -if TYPE_CHECKING: - from sentry.models.deploy import Deploy - from sentry.models.organization import Organization - from sentry.models.project import Project - from sentry.models.release_threshold.release_threshold import ReleaseThreshold - from sentry.models.releaseprojectenvironment import ReleaseProjectEnvironment - - -class ReleaseThresholdStatusIndexData(TypedDict, total=False): - start: datetime - end: datetime - environment: list[str] - projectSlug: list[str] - release: list[str] - project: list[ProjectIdOrSlug] - - -class ReleaseThresholdStatusIndexSerializer( - serializers.Serializer[ReleaseThresholdStatusIndexData] -): - start = serializers.DateTimeField( - help_text="The start of the time series range as an explicit datetime, either in UTC ISO8601 or epoch seconds. " - "Use along with `end`.", - required=True, - ) - end = serializers.DateTimeField( - help_text=( - "The inclusive end of the time series range as an explicit datetime, either in UTC ISO8601 or epoch seconds. " - "Use along with `start`." - ), - required=True, - ) - environment = serializers.ListField( - required=False, - allow_empty=True, - child=serializers.CharField(), - help_text=("A list of environment names to filter your results by."), - ) - projectSlug = serializers.ListField( - required=False, - allow_empty=True, - child=serializers.CharField(allow_blank=True), - help_text=("A list of project slugs to filter your results by."), - ) - release = serializers.ListField( - required=False, - allow_empty=True, - child=serializers.CharField(), - help_text=("A list of release versions to filter your results by."), - ) - project = serializers.ListField( - required=False, - allow_empty=True, - child=ProjectIdOrSlugField(), - help_text=("A list of project IDs or slugs to filter your results by."), - ) - - def validate(self, data: ReleaseThresholdStatusIndexData) -> ReleaseThresholdStatusIndexData: - if data["start"] >= data["end"]: - raise serializers.ValidationError("Start datetime must be after End") - return data - - -@cell_silo_endpoint -@extend_schema(tags=["Releases"]) -class ReleaseThresholdStatusIndexEndpoint(OrganizationReleasesBaseEndpoint): - owner: ApiOwner = ApiOwner.REPLAY - publish_status = { - "GET": ApiPublishStatus.PUBLIC_EXPERIMENTAL, - } - - @extend_schema( - operation_id="listOrganizationReleaseThresholdStatuses", - summary="Retrieve Statuses of Release Thresholds (Alpha)", - parameters=[GlobalParams.ORG_ID_OR_SLUG, ReleaseThresholdStatusIndexSerializer], - request=None, - responses={ - 200: inline_sentry_response_serializer( - "ReleaseThresholdStatusResponse", dict[str, list[EnrichedThreshold]] - ), - 400: RESPONSE_BAD_REQUEST, - }, - examples=ReleaseThresholdExamples.THRESHOLD_STATUS_RESPONSE, - ) - def get( - self, request: Request, organization: Organization | RpcOrganization - ) -> Response[dict[str, list[EnrichedThreshold]]] | Response[ValidationErrorResponse]: - r""" - List all derived statuses of releases that fall within the provided start/end datetimes. - - Constructs a response key'd off \{`release_version`\}-\{`project_slug`\} that lists thresholds with their status for *specified* projects. - Each returned enriched threshold will contain the full serialized `release_threshold` instance as well as it's derived health statuses. - """ - # TODO: We should limit/paginate results (this could get really bulky) - # ======================================================================== - # STEP 1: Validate request data - # - # NOTE: start/end parameters determine window to query for releases - # This is NOT the window to query snuba for event data - nor the individual threshold windows - # ======================================================================== - query_params = self.get_query_params_with_project_slug_precedence(request) - - serializer = ReleaseThresholdStatusIndexSerializer(data=query_params) - if not serializer.is_valid(): - return Response(as_validation_errors(serializer), status=400) - - validated_data = serializer.validated_data - environments_list = validated_data.get("environment") # list of environment names - releases_list = validated_data.get("release") # list of release versions - - project_ids: set[int] | None = None - project_slugs = {slug for slug in validated_data.get("projectSlug", []) if slug} or None - if project_slugs is None: - requested_project = parse_id_or_slug_params(validated_data.get("project", [])) - project_ids = requested_project.ids or None - project_slugs = requested_project.slugs or None - - try: - filter_params = self.get_filter_params( - request, - organization, - date_filter_optional=True, - project_ids=project_ids, - project_slugs=project_slugs, - ) - except NoProjects: - raise NoProjects("No projects available") - - # Use project IDs from get_filter_params instead of raw project filters so - # project access is checked before fetching threshold data. - validated_project_ids = set(filter_params["project_id"]) - - start: datetime | None = filter_params["start"] - end: datetime | None = filter_params["end"] - logger.info( - "Checking release status health", - extra={ - "start": start, - "end": end, - }, - ) - metrics.incr("release.threshold_health_status.attempt") - - # ======================================================================== - # Step 2: Fetch releases, prefetch projects & release_thresholds - # ======================================================================== - release_query = Q(organization=organization, date_added__gte=start, date_added__lte=end) - if environments_list: - release_query &= Q( - releaseprojectenvironment__environment__name__in=environments_list, - ) - release_query &= Q( - projects__id__in=validated_project_ids, - ) - if releases_list: - release_query &= Q( - version__in=releases_list, - ) - - queryset = ( - Release.objects.filter(release_query) - .annotate( - date=F("date_added"), # transforms date_added into 'date' - ) - .order_by("-date") - .distinct() - # prefetch the release_thresholds via the projects model - .prefetch_related( - "projects__release_thresholds__environment", - "releaseprojectenvironment_set", - "deploy_set", - ) - ) - - logger.info( - "Fetched releases", - extra={ - "results": len(queryset), - "project_slugs": project_slugs, - "releases": releases_list, - "environments": environments_list, - }, - ) - - # ======================================================================== - # Step 3: flatten thresholds and compile projects/release-thresholds by type - # ======================================================================== - thresholds_by_type: defaultdict[int, dict[str, list[Any]]] = defaultdict() - query_windows_by_type: defaultdict[int, dict[str, datetime]] = defaultdict() - for release in queryset: - # TODO: - # We should update release model to preserve threshold states. - # if release.failed_thresholds/passed_thresholds exists - then skip calculating and just return thresholds - project_list = [p for p in release.projects.all() if p.id in validated_project_ids] - - for project in project_list: - thresholds_list: list[ReleaseThreshold] = [ - t - for t in project.release_thresholds.all() - if ( - environments_list - and t.environment - and t.environment.name in environments_list - ) - or (not environments_list) - ] - - for threshold in thresholds_list: - if threshold.threshold_type not in thresholds_by_type: - thresholds_by_type[threshold.threshold_type] = { - "project_ids": [], - "releases": [], - "thresholds": [], - } - thresholds_by_type[threshold.threshold_type]["project_ids"].append(project.id) - thresholds_by_type[threshold.threshold_type]["releases"].append(release.version) - if threshold.threshold_type not in query_windows_by_type: - query_windows_by_type[threshold.threshold_type] = { - "start": datetime.now(tz=timezone.utc), - "end": datetime.now(tz=timezone.utc), - } - - latest_deploy: Deploy | None = None - if threshold.environment: - # NOTE: if a threshold has no environment set, we monitor from start of the release creation - # If a deploy does not exist for the thresholds environment, we monitor from start of release creation - # ReleaseProjectEnvironment model - rpe_entry: ReleaseProjectEnvironment | None = next( - ( - rpe - for rpe in release.releaseprojectenvironment_set.all() - if rpe.environment == threshold.environment - and rpe.project == project - ), - None, - ) - if rpe_entry: - last_deploy_id = rpe_entry.last_deploy_id - latest_deploy = next( - ( - deploy - for deploy in release.deploy_set.all() - if deploy.id == last_deploy_id - ), - None, - ) - - # NOTE: query window starts at the earliest release up until the latest threshold window - if latest_deploy: - threshold_start = latest_deploy.date_finished - else: - threshold_start = release.date - - query_windows_by_type[threshold.threshold_type]["start"] = min( - threshold_start, query_windows_by_type[threshold.threshold_type]["start"] - ) - query_windows_by_type[threshold.threshold_type]["end"] = max( - threshold_start + timedelta(seconds=threshold.window_in_seconds), - query_windows_by_type[threshold.threshold_type]["end"], - ) - # NOTE: enriched threshold is SERIALIZED - # meaning project and environment models are dictionaries - enriched_threshold: EnrichedThreshold = serialize(threshold) - # NOTE: start/end for a threshold are different than start/end for querying data - enriched_threshold.update( - { - "key": self.construct_threshold_key(release=release, project=project), - "start": threshold_start, - "end": threshold_start - + timedelta( - seconds=threshold.window_in_seconds - ), # start + threshold.window - "release": release.version, - "project_slug": project.slug, - "project_id": project.id, - "is_healthy": False, - } - ) - thresholds_by_type[threshold.threshold_type]["thresholds"].append( - enriched_threshold - ) - - # ======================================================================== - # Step 4: Determine threshold status per threshold type and return results - # ======================================================================== - release_threshold_health: dict[str, list[EnrichedThreshold]] = defaultdict(list) - for threshold_type, filter_list in thresholds_by_type.items(): - project_id_list = [proj_id for proj_id in filter_list["project_ids"]] - release_value_list = [release_version for release_version in filter_list["releases"]] - category_thresholds: list[EnrichedThreshold] = filter_list["thresholds"] - query_window = query_windows_by_type[threshold_type] - if threshold_type == ReleaseThresholdType.TOTAL_ERROR_COUNT: - metrics.incr("release.threshold_health_status.check.error_count") - """ - Fetch errors timeseries for all projects with an error_count threshold in desired releases - Iterate through timeseries given threshold window and determine health status - - NOTE: Timeseries query start & end are determined by API param window (_not_ threshold window) - derived from fetched releases (earliest start & latest end) - IF the param window doesn't cover the full threshold window, results will be inaccurate - - TODO: If too many results, then throw an error and request user to narrow their search window - """ - error_counts = get_errors_counts_timeseries_by_project_and_release( - end=query_window["end"], - environments_list=environments_list, - organization_id=organization.id, - project_id_list=project_id_list, - release_value_list=release_value_list, - start=query_window["start"], - ) - logger.info( - "querying error counts", - extra={ - "start": query_window["start"], - "end": query_window["end"], - "project_ids": project_id_list, - "releases": release_value_list, - "environments": environments_list, - "error_count_data": error_counts, - }, - ) - for ethreshold in category_thresholds: - is_healthy, metric_count = is_error_count_healthy(ethreshold, error_counts) - ethreshold.update({"is_healthy": is_healthy, "metric_value": metric_count}) - release_threshold_health[ethreshold["key"]].append( - ethreshold - ) # so we can fill all thresholds under the same key - elif threshold_type == ReleaseThresholdType.NEW_ISSUE_COUNT: - metrics.incr("release.threshold_health_status.check.new_issue_count") - """ - Query new issue counts for all projects with a new_issue_count threshold in desired releases - """ - new_issue_counts = get_new_issue_counts( - organization_id=organization.id, - thresholds=category_thresholds, - ) - logger.info( - "querying new issue counts", - extra={ - "start": query_window["start"], - "end": query_window["end"], - "project_ids": project_id_list, - "releases": release_value_list, - "environments": environments_list, - "new_issue_counts_data": new_issue_counts, - }, - ) - for ethreshold in category_thresholds: - is_healthy, metric_count = is_new_issue_count_healthy( - ethreshold, new_issue_counts - ) - ethreshold.update({"is_healthy": is_healthy, "metric_value": metric_count}) - release_threshold_health[ethreshold["key"]].append( - ethreshold - ) # so we can fill all thresholds under the same key - elif threshold_type == ReleaseThresholdType.UNHANDLED_ISSUE_COUNT: - metrics.incr("release.threshold_health_status.check.unhandled_issue_count") - for ethreshold in category_thresholds: - release_threshold_health[ethreshold["key"]].append( - ethreshold - ) # so we can fill all thresholds under the same key - elif threshold_type == ReleaseThresholdType.REGRESSED_ISSUE_COUNT: - metrics.incr("release.threshold_health_status.check.regressed_issue_count") - for ethreshold in category_thresholds: - release_threshold_health[ethreshold["key"]].append( - ethreshold - ) # so we can fill all thresholds under the same key - elif threshold_type == ReleaseThresholdType.FAILURE_RATE: - metrics.incr("release.threshold_health_status.check.failure_rate") - for ethreshold in category_thresholds: - release_threshold_health[ethreshold["key"]].append( - ethreshold - ) # so we can fill all thresholds under the same key - elif threshold_type == ReleaseThresholdType.CRASH_FREE_SESSION_RATE: - metrics.incr("release.threshold_health_status.check.crash_free_session_rate") - query_window = query_windows_by_type[threshold_type] - sessions_data: SessionsQueryResult | None = None - try: - sessions_data = fetch_sessions_data( - end=query_window["end"], - request=request, - organization=organization, - params=filter_params, - start=query_window["start"], - ) - except Exception as exc: - # TODO: handle InvalidPararms - # sentry.exceptions.InvalidParams: Your interval and date range would create too many results. Use a larger interval, or a smaller date range. - logger.exception(str(exc)) - logger.info( - "fetching sessions data", - extra={ - "start": query_window["start"], - "end": query_window["end"], - "project_ids": project_id_list, - "releases": release_value_list, - "environments": environments_list, - "error_count_data": error_counts, - }, - ) - if sessions_data: - for ethreshold in category_thresholds: - is_healthy, rate = is_crash_free_rate_healthy_check( - ethreshold, dict(sessions_data), CRASH_SESSIONS_DISPLAY - ) - ethreshold.update({"is_healthy": is_healthy, "metric_value": rate}) - release_threshold_health[ethreshold["key"]].append(ethreshold) - elif threshold_type == ReleaseThresholdType.CRASH_FREE_USER_RATE: - metrics.incr("release.threshold_health_status.check.crash_free_user_rate") - for ethreshold in category_thresholds: - release_threshold_health[ethreshold["key"]].append( - ethreshold - ) # so we can fill all thresholds under the same key - - return Response(release_threshold_health, status=200) - - def construct_threshold_key(self, project: Project, release: Release) -> str: - """ - Consistent key helps to determine which thresholds can be grouped together. - project_slug - release_version - - NOTE: release versions can contain special characters... `-` delimiter may not be appropriate - TODO: move this into a separate helper? - """ - return f"{project.slug}-{release.version}" diff --git a/src/sentry/api/endpoints/release_thresholds/types.py b/src/sentry/api/endpoints/release_thresholds/types.py deleted file mode 100644 index 755e92028565..000000000000 --- a/src/sentry/api/endpoints/release_thresholds/types.py +++ /dev/null @@ -1,65 +0,0 @@ -from __future__ import annotations - -from datetime import datetime -from typing import TYPE_CHECKING, Annotated, TypedDict - -from sentry.apidocs.descriptions import ApiDescription -from sentry.models.release_threshold.constants import ThresholdTypeName, TriggerTypeName - -if TYPE_CHECKING: - from sentry.api.serializers.models.environment import EnvironmentSerializerResponse - from sentry.api.serializers.models.project import ProjectSerializerResponse - - -class SerializedThreshold(TypedDict, total=False): - id: Annotated[str, ApiDescription("ID of the threshold")] - date_added: Annotated[datetime, ApiDescription("When the threshold was created (ISO 8601)")] - environment: Annotated[ - EnvironmentSerializerResponse | None, - ApiDescription("Environment the threshold applies to. Null for all environments"), - ] - project: Annotated[ - ProjectSerializerResponse, ApiDescription("Project the threshold applies to") - ] - release: Annotated[ - str, ApiDescription("Version of the release the threshold was checked against") - ] - threshold_type: Annotated[ - ThresholdTypeName, - ApiDescription( - "Metric the threshold checks: total_error_count, new_issue_count, unhandled_issue_count, regressed_issue_count, failure_rate, crash_free_session_rate or crash_free_user_rate" - ), - ] - trigger_type: Annotated[ - TriggerTypeName, - ApiDescription("Whether the threshold fails when the metric goes over or under value"), - ] - value: Annotated[int, ApiDescription("Value the metric is compared with")] - window_in_seconds: Annotated[ - int, - ApiDescription( - "Time after the release or deploy during which the threshold is checked, in seconds" - ), - ] - - -class EnrichedThreshold(SerializedThreshold): - end: Annotated[ - datetime, ApiDescription("End of the window the threshold was checked in (ISO 8601)") - ] - is_healthy: Annotated[bool, ApiDescription("Whether the metric stayed within the threshold")] - key: Annotated[ - str, ApiDescription("Key that groups thresholds of the same project and release") - ] - project_slug: Annotated[str, ApiDescription("Slug of the project")] - project_id: Annotated[int, ApiDescription("ID of the project")] - start: Annotated[ - datetime, - ApiDescription( - "Start of the window the threshold was checked in: the latest deploy, or the release date (ISO 8601)" - ), - ] - metric_value: Annotated[ - int | float | None, - ApiDescription("Value of the metric in the window. Null when it couldn't be computed"), - ] diff --git a/src/sentry/api/endpoints/release_thresholds/utils/__init__.py b/src/sentry/api/endpoints/release_thresholds/utils/__init__.py deleted file mode 100644 index 72bbf2fe05f7..000000000000 --- a/src/sentry/api/endpoints/release_thresholds/utils/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .fetch_sessions_data import * # noqa: F403, F401 -from .get_errors_counts_timeseries import * # noqa: F403, F401 -from .get_new_issue_counts import * # noqa: F403, F401 diff --git a/src/sentry/api/endpoints/release_thresholds/utils/fetch_sessions_data.py b/src/sentry/api/endpoints/release_thresholds/utils/fetch_sessions_data.py deleted file mode 100644 index d3a19d8a80ff..000000000000 --- a/src/sentry/api/endpoints/release_thresholds/utils/fetch_sessions_data.py +++ /dev/null @@ -1,50 +0,0 @@ -from __future__ import annotations - -from datetime import datetime - -from rest_framework.request import Request - -from sentry import release_health -from sentry.api.bases import FilterParams -from sentry.api.utils import handle_query_errors -from sentry.models.organization import Organization -from sentry.organizations.services.organization.model import RpcOrganization -from sentry.release_health.base import SessionsQueryResult -from sentry.snuba.sessions_v2 import QueryDefinition - - -def fetch_sessions_data( - request: Request, - organization: Organization | RpcOrganization, - params: FilterParams, - end: datetime, - start: datetime, - field: str | None = "sum(session)", # alternatively count_unique(user) -) -> SessionsQueryResult: - """ - This implementation was derived from organization_sessions GET endpoint - NOTE: Params are derived from the request query and pulls the relevant project/environment objects - TODO: make fetch generic for other session types - TODO: capture potential issues with `interval` returning too many results - """ - with handle_query_errors(): - query_params = request.GET.copy() - query_params.setlist("groupBy", ["project", "release", "session.status", "environment"]) - query_params.setlist("field", [field] if field is not None else []) - query_params["query"] = " OR ".join( - [f"release:{version}" for version in query_params.getlist("release")] - ) - interval = "1hr" - query_params["interval"] = interval - query_params["start"] = start.isoformat() - query_params["end"] = end.isoformat() - - # NOTE: params start/end are overwritten by query start/end - query = QueryDefinition( - query=query_params, - params=params, - ) - - return release_health.backend.run_sessions_query( - organization.id, query, span_op="release_thresholds.endpoint" - ) diff --git a/src/sentry/api/endpoints/release_thresholds/utils/get_errors_counts_timeseries.py b/src/sentry/api/endpoints/release_thresholds/utils/get_errors_counts_timeseries.py deleted file mode 100644 index c0a9ba9f2b92..000000000000 --- a/src/sentry/api/endpoints/release_thresholds/utils/get_errors_counts_timeseries.py +++ /dev/null @@ -1,213 +0,0 @@ -from __future__ import annotations - -import logging -from datetime import datetime, timezone -from typing import Any - -from snuba_sdk import Request as SnubaRequest -from snuba_sdk.column import Column -from snuba_sdk.conditions import Condition, Op -from snuba_sdk.entity import Entity -from snuba_sdk.expressions import Granularity -from snuba_sdk.function import Function -from snuba_sdk.orderby import Direction, OrderBy -from snuba_sdk.query import Query - -from sentry.search.eap.occurrences.query_utils import ( - build_escaped_term_filter, - build_snuba_params_from_ids, - keyed_counts_subset_match, -) -from sentry.search.eap.occurrences.rollout_utils import EAPOccurrencesComparator -from sentry.search.eap.types import SearchResolverConfig -from sentry.snuba.dataset import Dataset -from sentry.snuba.occurrences_rpc import OccurrenceCategory, Occurrences -from sentry.snuba.referrer import Referrer -from sentry.utils import snuba - -logger = logging.getLogger(__name__) - - -def get_errors_counts_timeseries_by_project_and_release( - end: datetime, - organization_id: int, - project_id_list: list[int], - release_value_list: list[str], - start: datetime, - environments_list: list[str] | None = None, -) -> list[dict[str, Any]]: - snuba_results = _get_errors_counts_timeseries_snuba( - end=end, - organization_id=organization_id, - project_id_list=project_id_list, - release_value_list=release_value_list, - start=start, - environments_list=environments_list, - ) - results = snuba_results - - if EAPOccurrencesComparator.should_check_experiment( - "release_thresholds.get_errors_counts_timeseries" - ): - eap_results = _get_errors_counts_timeseries_eap( - end=end, - organization_id=organization_id, - project_id_list=project_id_list, - release_value_list=release_value_list, - start=start, - environments_list=environments_list, - ) - results = EAPOccurrencesComparator.check_and_choose( - snuba_results, - eap_results, - "release_thresholds.get_errors_counts_timeseries", - is_experimental_data_nullish=len(eap_results) == 0, - reasonable_match_comparator=lambda snuba_rows, eap_rows: keyed_counts_subset_match( - snuba_rows, - eap_rows, - key_fn=lambda row: ( - row["release"], - int(row["project_id"]), - row["environment"], - row["time"], - ), - ), - debug_context={ - "organization_id": organization_id, - "project_ids": project_id_list, - "releases": release_value_list, - "environments": environments_list, - "start": start.isoformat(), - "end": end.isoformat(), - "snuba_result_count": len(snuba_results), - "eap_result_count": len(eap_results), - }, - ) - - return results - - -def _get_errors_counts_timeseries_snuba( - end: datetime, - organization_id: int, - project_id_list: list[int], - release_value_list: list[str], - start: datetime, - environments_list: list[str] | None = None, -) -> list[dict[str, Any]]: - additional_conditions = [] - if environments_list: - additional_conditions.append(Condition(Column("environment"), Op.IN, environments_list)) - query = Query( - match=Entity("events"), # synonymous w/ discover dataset - select=[Function("count", [])], - groupby=[ - Column("release"), - Column("project_id"), - Column("environment"), - Column("time"), # groupby 'time' gives us a timeseries - ], - orderby=[ - OrderBy(Column("time"), Direction.DESC), - ], - granularity=Granularity(60), - where=[ - Condition(Column("type"), Op.EQ, "error"), - Condition(Column("timestamp"), Op.GTE, start), - Condition(Column("timestamp"), Op.LT, end), - Condition(Column("project_id"), Op.IN, project_id_list), - Condition(Column("release"), Op.IN, release_value_list), - *additional_conditions, - ], - ) - request = SnubaRequest( - dataset=Dataset.Events.value, - app_id="default", - query=query, - tenant_ids={"organization_id": organization_id}, - ) - data = snuba.raw_snql_query( - request=request, referrer=Referrer.SNUBA_SESSIONS_CHECK_RELEASES_HAVE_HEALTH_DATA - )["data"] - - return data - - -def _get_errors_counts_timeseries_eap( - end: datetime, - organization_id: int, - project_id_list: list[int], - release_value_list: list[str], - start: datetime, - environments_list: list[str] | None = None, -) -> list[dict[str, Any]]: - if not release_value_list: - return [] - - snuba_params = build_snuba_params_from_ids( - organization_id=organization_id, - project_ids=project_id_list, - start=start, - end=end, - granularity_secs=60, - ) - if snuba_params is None: - logger.warning( - "Organization or projects not found for EAP error counts timeseries query", - extra={"organization_id": organization_id, "project_ids": project_id_list}, - ) - return [] - - try: - query_parts: list[str] = [] - - release_filter = build_escaped_term_filter("release", release_value_list) - if release_filter: - query_parts.append(release_filter) - - environment_filter = build_escaped_term_filter("environment", environments_list or []) - if environment_filter: - query_parts.append(environment_filter) - - query_string = " ".join(query_parts) - - timeseries_results = Occurrences.run_grouped_timeseries_query( - params=snuba_params, - query_string=query_string, - y_axes=["count()"], - groupby=["release", "project_id", "environment"], - referrer=Referrer.SNUBA_SESSIONS_CHECK_RELEASES_HAVE_HEALTH_DATA.value, - config=SearchResolverConfig(), - occurrence_category=OccurrenceCategory.ERROR, - ) - - # Transform to match Snuba response format - transformed: list[dict[str, Any]] = [] - for row in timeseries_results: - count = row.get("count()", 0) - if count > 0: - bucket_dt = datetime.fromtimestamp(row["time"], tz=timezone.utc) - transformed.append( - { - "release": row.get("release"), - "project_id": int(row["project_id"]), - "environment": row.get("environment"), - "time": bucket_dt.isoformat(), - "count()": int(count), - } - ) - - transformed.sort(key=lambda row: row["time"], reverse=True) - - return transformed - - except Exception: - logger.exception( - "Fetching error counts timeseries from EAP failed", - extra={ - "organization_id": organization_id, - "project_ids": project_id_list, - "releases": release_value_list, - }, - ) - return [] diff --git a/src/sentry/api/endpoints/release_thresholds/utils/get_new_issue_counts.py b/src/sentry/api/endpoints/release_thresholds/utils/get_new_issue_counts.py deleted file mode 100644 index c24f7a523e29..000000000000 --- a/src/sentry/api/endpoints/release_thresholds/utils/get_new_issue_counts.py +++ /dev/null @@ -1,44 +0,0 @@ -from __future__ import annotations - -from typing import TYPE_CHECKING, Any - -from django.db.models import CharField, Count, Q, QuerySet, Value - -from sentry.models.group import Group - -if TYPE_CHECKING: - from sentry.api.endpoints.release_thresholds.types import EnrichedThreshold - - -def get_new_issue_counts( - organization_id: int, thresholds: list[EnrichedThreshold] -) -> dict[str, int]: - """ - constructs a query for each threshold, filtering on project - NOTE: group messages are guaranteed to have a related groupenvironment - """ - queryset: QuerySet[Group, dict[str, Any]] | None = None - for t in thresholds: - env = t.get("environment") - query = Q( - project__organization__id=organization_id, - project__id=t["project_id"], - groupenvironment__first_release__version=t["release"], - groupenvironment__first_seen__range=(t["start"], t["end"]), - groupenvironment__environment__name=env["name"] if env else "", - ) - qs = ( - Group.objects.filter(query) - .values("first_release__version") - .annotate( - count=Count("*"), - threshold_id=Value(t["id"], output_field=CharField()), - ) - ) - - if queryset is None: - queryset = qs - else: - queryset = queryset.union(qs) - - return {x["threshold_id"]: x["count"] for x in queryset} if queryset else {} diff --git a/src/sentry/api/serializers/models/__init__.py b/src/sentry/api/serializers/models/__init__.py index 182cef13ef6e..744a85c96ab1 100644 --- a/src/sentry/api/serializers/models/__init__.py +++ b/src/sentry/api/serializers/models/__init__.py @@ -45,7 +45,6 @@ from .relayusage import * # noqa: F401,F403 from .release import * # noqa: F401,F403 from .release_file import * # noqa: F401,F403 -from .release_threshold import * # noqa: F401,F403 from .repository import * # noqa: F401,F403 from .role import * # noqa: F401,F403 from .tagvalue import * # noqa: F401,F403 diff --git a/src/sentry/api/serializers/models/release_threshold.py b/src/sentry/api/serializers/models/release_threshold.py deleted file mode 100644 index 2772e0da59f9..000000000000 --- a/src/sentry/api/serializers/models/release_threshold.py +++ /dev/null @@ -1,48 +0,0 @@ -from collections.abc import Mapping -from datetime import datetime -from typing import TypedDict - -from django.contrib.auth.models import AnonymousUser - -from sentry.api.serializers import Serializer, register, serialize -from sentry.models.release_threshold.constants import ( - THRESHOLD_TYPE_INT_TO_STR, - TRIGGER_TYPE_INT_TO_STR, - ThresholdTypeName, - TriggerTypeName, -) -from sentry.models.release_threshold.release_threshold import ReleaseThreshold -from sentry.users.models.user import User -from sentry.users.services.user.model import RpcUser - - -class ReleaseThresholdSerializerResponse(TypedDict): - id: str - threshold_type: ThresholdTypeName - trigger_type: TriggerTypeName - value: int - window_in_seconds: int - project: object - environment: object | None - date_added: datetime - - -@register(ReleaseThreshold) -class ReleaseThresholdSerializer(Serializer[ReleaseThresholdSerializerResponse]): - def serialize( - self, - obj: ReleaseThreshold, - attrs: Mapping[object, object], - user: User | RpcUser | AnonymousUser, - **kwargs: object, - ) -> ReleaseThresholdSerializerResponse: - return { - "id": str(obj.id), - "threshold_type": THRESHOLD_TYPE_INT_TO_STR[obj.threshold_type], - "trigger_type": TRIGGER_TYPE_INT_TO_STR[obj.trigger_type], - "value": obj.value, - "window_in_seconds": obj.window_in_seconds, - "project": serialize(obj.project), - "environment": serialize(obj.environment) if obj.environment else None, - "date_added": obj.date_added, - } diff --git a/src/sentry/api/urls.py b/src/sentry/api/urls.py index 90ebbfb16a19..c3ecf31a5263 100644 --- a/src/sentry/api/urls.py +++ b/src/sentry/api/urls.py @@ -80,16 +80,6 @@ ) from sentry.api.endpoints.project_overview import ProjectOverviewEndpoint from sentry.api.endpoints.project_statistical_detectors import ProjectStatisticalDetectors -from sentry.api.endpoints.release_thresholds.release_threshold import ReleaseThresholdEndpoint -from sentry.api.endpoints.release_thresholds.release_threshold_details import ( - ReleaseThresholdDetailsEndpoint, -) -from sentry.api.endpoints.release_thresholds.release_threshold_index import ( - ReleaseThresholdIndexEndpoint, -) -from sentry.api.endpoints.release_thresholds.release_threshold_status_index import ( - ReleaseThresholdStatusIndexEndpoint, -) from sentry.api.endpoints.secret_scanning.github import SecretScanningGitHubEndpoint from sentry.api.endpoints.source_map_debug import SourceMapDebugEndpoint from sentry.auth_v2.urls import AUTH_V2_URLS @@ -2345,17 +2335,6 @@ def create_group_urls( OrganizationReleasesEndpoint.as_view(), name="sentry-api-0-organization-releases", ), - re_path( - r"^(?P[^/]+)/release-thresholds/$", - ReleaseThresholdIndexEndpoint.as_view(), - name="sentry-api-0-organization-release-thresholds", - ), - # TODO: also integrate release threshold status into the releases response? - re_path( - r"^(?P[^/]+)/release-threshold-statuses/$", - ReleaseThresholdStatusIndexEndpoint.as_view(), - name="sentry-api-0-organization-release-threshold-statuses", - ), re_path( r"^(?P[^/]+)/releases/stats/$", OrganizationReleasesStatsEndpoint.as_view(), @@ -3219,16 +3198,6 @@ def create_group_urls( ProjectReleasesEndpoint.as_view(), name="sentry-api-0-project-releases", ), - re_path( - r"^(?P[^/]+)/(?P[^/]+)/release-thresholds/$", - ReleaseThresholdEndpoint.as_view(), - name="sentry-api-0-project-release-thresholds", - ), - re_path( - r"^(?P[^/]+)/(?P[^/]+)/release-thresholds/(?P[^/]+)/$", - ReleaseThresholdDetailsEndpoint.as_view(), - name="sentry-api-0-project-release-thresholds-details", - ), re_path( r"^(?P[^/]+)/(?P[^/]+)/commits/$", ProjectCommitsEndpoint.as_view(), diff --git a/src/sentry/apidocs/examples/release_threshold_examples.py b/src/sentry/apidocs/examples/release_threshold_examples.py deleted file mode 100644 index 87c4add22904..000000000000 --- a/src/sentry/apidocs/examples/release_threshold_examples.py +++ /dev/null @@ -1,36 +0,0 @@ -from drf_spectacular.utils import OpenApiExample - -from .project_examples import BASE_PROJECT - - -class ReleaseThresholdExamples: - THRESHOLD_STATUS_RESPONSE = [ - OpenApiExample( - "Client key with rate limiting", - value={ - f"{BASE_PROJECT['slug']}-v1.0.0": [ - { - "project_id": 0, - "project_slug": BASE_PROJECT["slug"], - "environment": { - "id": "1", - "name": "production", - }, - "project": BASE_PROJECT, - "threshold_type": "total_error_count", - "trigger_type": "over", - "value": 100, - "window_in_seconds": 600, - "key": "foobar-v1.0.0", - "release": f"{BASE_PROJECT['slug']}-v1.0.0", - "is_healthy": True, - "start": "2022-02-14T19:00:00Z", - "end": "2022-02-28T18:03:00Z", - "metric_value": 0.1, - }, - ], - }, - status_codes=["200"], - response_only=True, - ), - ] diff --git a/src/sentry/conf/api_pagination_allowlist_do_not_modify.py b/src/sentry/conf/api_pagination_allowlist_do_not_modify.py index 16b86b845ad7..066adff85065 100644 --- a/src/sentry/conf/api_pagination_allowlist_do_not_modify.py +++ b/src/sentry/conf/api_pagination_allowlist_do_not_modify.py @@ -77,7 +77,6 @@ "ProjectSymbolSourcesEndpoint", "ProjectTagsEndpoint", "ProjectUsersEndpoint", - "ReleaseThresholdEndpoint", "SentryAppInstallationServiceHookProjectsEndpoint", "SentryAppRequestsEndpoint", "SentryAppWebhookRequestsEndpoint", diff --git a/src/sentry/db/router.py b/src/sentry/db/router.py index e5b683ae9c04..39f8672f389d 100644 --- a/src/sentry/db/router.py +++ b/src/sentry/db/router.py @@ -125,6 +125,7 @@ class SiloRouter: "sentry_scheduledjob": SiloMode.CONTROL, "sentry_projecttemplate": SiloMode.CELL, "sentry_projecttemplateoption": SiloMode.CELL, + "sentry_releasethreshold": SiloMode.CELL, "sentry_neglectedrule": SiloMode.CELL, "sentry_ruleactivity": SiloMode.CELL, "sentry_rulefirehistory": SiloMode.CELL, diff --git a/src/sentry/deletions/defaults/project.py b/src/sentry/deletions/defaults/project.py index bc3f0b607276..d79f037de314 100644 --- a/src/sentry/deletions/defaults/project.py +++ b/src/sentry/deletions/defaults/project.py @@ -37,7 +37,6 @@ def get_child_relations(self, instance: Project) -> list[BaseRelation]: from sentry.models.projectrepository import ProjectRepository from sentry.models.projectteam import ProjectTeam from sentry.models.promptsactivity import PromptsActivity - from sentry.models.release_threshold import ReleaseThreshold from sentry.models.releaseprojectenvironment import ReleaseProjectEnvironment from sentry.models.releases.release_project import ReleaseProject from sentry.models.transaction_threshold import ProjectTransactionThreshold @@ -73,7 +72,6 @@ def get_child_relations(self, instance: Project) -> list[BaseRelation]: ProjectBookmark, ProjectKey, WeeklyReportProjectExclusion, - ReleaseThreshold, ProjectTeam, PromptsActivity, # order matters, ProjectCodeOwners to be deleted before RepositoryProjectPathConfig diff --git a/src/sentry/migrations/1264_remove_release_threshold.py b/src/sentry/migrations/1264_remove_release_threshold.py new file mode 100644 index 000000000000..8340ecb84a91 --- /dev/null +++ b/src/sentry/migrations/1264_remove_release_threshold.py @@ -0,0 +1,56 @@ +# Generated by Django 5.2.17 on 2026-11-20 00:51 + +import django.db.models.deletion +import sentry.db.models.fields.foreignkey +from django.db import migrations + +from sentry.new_migrations.migrations import CheckedMigration +from sentry.new_migrations.monkey.models import SafeDeleteModel +from sentry.new_migrations.monkey.state import DeletionAction + + +class Migration(CheckedMigration): + # This flag is used to mark that a migration shouldn't be automatically run in production. + # This should only be used for operations where it's safe to run the migration after your + # code has deployed. So this should not be used for most operations that alter the schema + # of a table. + # Here are some things that make sense to mark as post deployment: + # - Large data migrations. Typically we want these to be run manually so that they can be + # monitored and not block the deploy for a long period of time while they run. + # - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to + # run this outside deployments so that we don't block them. Note that while adding an index + # is a schema change, it's completely safe to run the operation after the code has deployed. + # Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment + + is_post_deployment = False + + dependencies = [ + ("sentry", "1263_add_groupsearchview_non_user_creator"), + ] + + operations = [ + migrations.AlterField( + model_name="releasethreshold", + name="environment", + field=sentry.db.models.fields.foreignkey.FlexibleForeignKey( + db_constraint=False, + null=True, + on_delete=django.db.models.deletion.CASCADE, + to="sentry.environment", + ), + ), + migrations.AlterField( + model_name="releasethreshold", + name="project", + field=sentry.db.models.fields.foreignkey.FlexibleForeignKey( + db_constraint=False, + on_delete=django.db.models.deletion.CASCADE, + related_name="release_thresholds", + to="sentry.project", + ), + ), + SafeDeleteModel( + name="ReleaseThreshold", + deletion_action=DeletionAction.MOVE_TO_PENDING, + ), + ] diff --git a/src/sentry/models/__init__.py b/src/sentry/models/__init__.py index ef83e198a344..e24e853a6b79 100644 --- a/src/sentry/models/__init__.py +++ b/src/sentry/models/__init__.py @@ -98,7 +98,6 @@ from .recentsearch import * # NOQA from .relay import * # NOQA from .release import * # NOQA -from .release_threshold import * # NOQA from .releaseactivity import * # NOQA from .releasecommit import * # NOQA from .releaseenvironment import * # NOQA diff --git a/src/sentry/models/release_threshold/__init__.py b/src/sentry/models/release_threshold/__init__.py deleted file mode 100644 index ab449eab63b6..000000000000 --- a/src/sentry/models/release_threshold/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .release_threshold import ReleaseThreshold - -__all__ = ("ReleaseThreshold",) diff --git a/src/sentry/models/release_threshold/constants.py b/src/sentry/models/release_threshold/constants.py deleted file mode 100644 index f9cb8402b7f9..000000000000 --- a/src/sentry/models/release_threshold/constants.py +++ /dev/null @@ -1,108 +0,0 @@ -from typing import Final, Literal - -# The threshold/trigger type names as serialized in API responses. -ThresholdTypeName = Literal[ - "total_error_count", - "new_issue_count", - "unhandled_issue_count", - "regressed_issue_count", - "failure_rate", - "crash_free_session_rate", - "crash_free_user_rate", -] -TriggerTypeName = Literal["over", "under"] - - -class ReleaseThresholdType: - TOTAL_ERROR_COUNT = 0 - NEW_ISSUE_COUNT = 1 - UNHANDLED_ISSUE_COUNT = 2 - REGRESSED_ISSUE_COUNT = 3 - FAILURE_RATE = 4 - CRASH_FREE_SESSION_RATE = 5 - CRASH_FREE_USER_RATE = 6 - - TOTAL_ERROR_COUNT_STR: Final = "total_error_count" - NEW_ISSUE_COUNT_STR: Final = "new_issue_count" - UNHANDLED_ISSUE_COUNT_STR: Final = "unhandled_issue_count" - REGRESSED_ISSUE_COUNT_STR: Final = "regressed_issue_count" - FAILURE_RATE_STR: Final = "failure_rate" - CRASH_FREE_SESSION_RATE_STR: Final = "crash_free_session_rate" - CRASH_FREE_USER_RATE_STR: Final = "crash_free_user_rate" - - @classmethod - def as_choices(cls) -> tuple[tuple[str, int], ...]: - return ( - (cls.TOTAL_ERROR_COUNT_STR, cls.TOTAL_ERROR_COUNT), - (cls.NEW_ISSUE_COUNT_STR, cls.NEW_ISSUE_COUNT), - (cls.UNHANDLED_ISSUE_COUNT_STR, cls.UNHANDLED_ISSUE_COUNT), - (cls.REGRESSED_ISSUE_COUNT_STR, cls.REGRESSED_ISSUE_COUNT), - (cls.FAILURE_RATE_STR, cls.FAILURE_RATE), - (cls.CRASH_FREE_SESSION_RATE_STR, cls.CRASH_FREE_SESSION_RATE), - (cls.CRASH_FREE_USER_RATE_STR, cls.CRASH_FREE_USER_RATE), - ) - - @classmethod - def as_str_choices(cls) -> tuple[tuple[str, str], ...]: - return ( - (cls.TOTAL_ERROR_COUNT_STR, cls.TOTAL_ERROR_COUNT_STR), - (cls.NEW_ISSUE_COUNT_STR, cls.NEW_ISSUE_COUNT_STR), - (cls.UNHANDLED_ISSUE_COUNT_STR, cls.UNHANDLED_ISSUE_COUNT_STR), - (cls.REGRESSED_ISSUE_COUNT_STR, cls.REGRESSED_ISSUE_COUNT_STR), - (cls.FAILURE_RATE_STR, cls.FAILURE_RATE_STR), - (cls.CRASH_FREE_SESSION_RATE_STR, cls.CRASH_FREE_SESSION_RATE_STR), - (cls.CRASH_FREE_USER_RATE_STR, cls.CRASH_FREE_USER_RATE_STR), - ) - - -class TriggerType: - OVER = 0 - UNDER = 1 - - OVER_STR: Final = "over" - UNDER_STR: Final = "under" - - @classmethod - def as_choices(cls) -> tuple[tuple[str, int], ...]: # choices for model column - return ( - (cls.OVER_STR, cls.OVER), - (cls.UNDER_STR, cls.UNDER), - ) - - @classmethod - def as_str_choices(cls) -> tuple[tuple[str, str], ...]: # choices for serializer - return ( - (cls.OVER_STR, cls.OVER_STR), - (cls.UNDER_STR, cls.UNDER_STR), - ) - - -THRESHOLD_TYPE_INT_TO_STR: dict[int, ThresholdTypeName] = { - ReleaseThresholdType.TOTAL_ERROR_COUNT: ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, - ReleaseThresholdType.NEW_ISSUE_COUNT: ReleaseThresholdType.NEW_ISSUE_COUNT_STR, - ReleaseThresholdType.UNHANDLED_ISSUE_COUNT: ReleaseThresholdType.UNHANDLED_ISSUE_COUNT_STR, - ReleaseThresholdType.REGRESSED_ISSUE_COUNT: ReleaseThresholdType.REGRESSED_ISSUE_COUNT_STR, - ReleaseThresholdType.FAILURE_RATE: ReleaseThresholdType.FAILURE_RATE_STR, - ReleaseThresholdType.CRASH_FREE_SESSION_RATE: ReleaseThresholdType.CRASH_FREE_SESSION_RATE_STR, - ReleaseThresholdType.CRASH_FREE_USER_RATE: ReleaseThresholdType.CRASH_FREE_USER_RATE_STR, -} - -THRESHOLD_TYPE_STR_TO_INT = { - ReleaseThresholdType.TOTAL_ERROR_COUNT_STR: ReleaseThresholdType.TOTAL_ERROR_COUNT, - ReleaseThresholdType.NEW_ISSUE_COUNT_STR: ReleaseThresholdType.NEW_ISSUE_COUNT, - ReleaseThresholdType.UNHANDLED_ISSUE_COUNT_STR: ReleaseThresholdType.UNHANDLED_ISSUE_COUNT, - ReleaseThresholdType.REGRESSED_ISSUE_COUNT_STR: ReleaseThresholdType.REGRESSED_ISSUE_COUNT, - ReleaseThresholdType.FAILURE_RATE_STR: ReleaseThresholdType.FAILURE_RATE, - ReleaseThresholdType.CRASH_FREE_SESSION_RATE_STR: ReleaseThresholdType.CRASH_FREE_SESSION_RATE, - ReleaseThresholdType.CRASH_FREE_USER_RATE_STR: ReleaseThresholdType.CRASH_FREE_USER_RATE, -} - -TRIGGER_TYPE_INT_TO_STR: dict[int, TriggerTypeName] = { - TriggerType.OVER: TriggerType.OVER_STR, - TriggerType.UNDER: TriggerType.UNDER_STR, -} - -TRIGGER_TYPE_STRING_TO_INT = { - TriggerType.OVER_STR: TriggerType.OVER, - TriggerType.UNDER_STR: TriggerType.UNDER, -} diff --git a/src/sentry/models/release_threshold/release_threshold.py b/src/sentry/models/release_threshold/release_threshold.py deleted file mode 100644 index 1c25e937d34e..000000000000 --- a/src/sentry/models/release_threshold/release_threshold.py +++ /dev/null @@ -1,34 +0,0 @@ -from django.db import models -from django.utils import timezone - -from sentry.backup.scopes import RelocationScope -from sentry.db.models import FlexibleForeignKey, Model, cell_silo_model -from sentry.db.models.fields.bounded import BoundedPositiveIntegerField -from sentry.models.release_threshold.constants import ReleaseThresholdType -from sentry.models.release_threshold.constants import TriggerType as ReleaseThresholdTriggerType - - -@cell_silo_model -class ReleaseThreshold(Model): - """ - NOTE: - To transition to utilizing AlertRules, there are some duplicated attrs we'll want to dedup. - AlertRule model should house metadata on the AlertRule itself (eg. type of alert rule) - DataCondition can represent the threshold requirements (eg. value, over/under comparison). - - TODO: Will need to determine how this translates to release_threshold evaluation - QuerySubscription model subscribes the AlertRule to specific query in Snuba - SnubaQuery model represents the actual query run in Snuba - - TODO: replace query constructed in release_thresholds api with activated SnubaQuery / determine whether we're constructing the same query or not - """ - - __relocation_scope__ = RelocationScope.Excluded - - threshold_type = BoundedPositiveIntegerField(choices=ReleaseThresholdType.as_choices()) - trigger_type = BoundedPositiveIntegerField(choices=ReleaseThresholdTriggerType.as_choices()) - - value = models.IntegerField() - window_in_seconds = models.PositiveIntegerField() - - project = FlexibleForeignKey("sentry.Project", db_index=True, related_name="release_thresholds") - environment = FlexibleForeignKey("sentry.Environment", null=True, db_index=True) - date_added = models.DateTimeField(default=timezone.now) diff --git a/src/sentry/web/urls.py b/src/sentry/web/urls.py index a43cd4e27a64..561a45da1616 100644 --- a/src/sentry/web/urls.py +++ b/src/sentry/web/urls.py @@ -992,11 +992,6 @@ react_page_view, name="releases", ), - re_path( - r"^release-thresholds/", - react_page_view, - name="release-thresholds", - ), # User Feedback re_path( r"^user-feedback/", diff --git a/static/app/utils/api/knownSentryApiUrls.generated.ts b/static/app/utils/api/knownSentryApiUrls.generated.ts index 2899404aaeb9..20090a5e4410 100644 --- a/static/app/utils/api/knownSentryApiUrls.generated.ts +++ b/static/app/utils/api/knownSentryApiUrls.generated.ts @@ -336,8 +336,6 @@ export type KnownSentryApiUrls = | '/organizations/$organizationIdOrSlug/pull-requests/$pullRequestId/files/' | '/organizations/$organizationIdOrSlug/recent-searches/' | '/organizations/$organizationIdOrSlug/relay_usage/' - | '/organizations/$organizationIdOrSlug/release-threshold-statuses/' - | '/organizations/$organizationIdOrSlug/release-thresholds/' | '/organizations/$organizationIdOrSlug/releases/' | '/organizations/$organizationIdOrSlug/releases/$version/' | '/organizations/$organizationIdOrSlug/releases/$version/assemble/' @@ -530,8 +528,6 @@ export type KnownSentryApiUrls = | '/projects/$organizationIdOrSlug/$projectIdOrSlug/profiling/profiles/$profileId/' | '/projects/$organizationIdOrSlug/$projectIdOrSlug/profiling/raw_chunks/$profilerId/$chunkId/' | '/projects/$organizationIdOrSlug/$projectIdOrSlug/profiling/raw_profiles/$profileId/' - | '/projects/$organizationIdOrSlug/$projectIdOrSlug/release-thresholds/' - | '/projects/$organizationIdOrSlug/$projectIdOrSlug/release-thresholds/$releaseThreshold/' | '/projects/$organizationIdOrSlug/$projectIdOrSlug/releases/' | '/projects/$organizationIdOrSlug/$projectIdOrSlug/releases/$version/' | '/projects/$organizationIdOrSlug/$projectIdOrSlug/releases/$version/commits/' diff --git a/tests/sentry/api/endpoints/release_thresholds/__init__.py b/tests/sentry/api/endpoints/release_thresholds/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tests/sentry/api/endpoints/release_thresholds/health_checks/__init__.py b/tests/sentry/api/endpoints/release_thresholds/health_checks/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/tests/sentry/api/endpoints/release_thresholds/health_checks/test_fixtures.py b/tests/sentry/api/endpoints/release_thresholds/health_checks/test_fixtures.py deleted file mode 100644 index c3c6ec4a3b6c..000000000000 --- a/tests/sentry/api/endpoints/release_thresholds/health_checks/test_fixtures.py +++ /dev/null @@ -1,157 +0,0 @@ -mock_sessions_data = { - "groups": [ - { - "by": { - "project": 1, - "release": "version1", - "session.status": "healthy", - "environment": "production", - }, - "totals": {"sum(session)": 10}, - "series": { - "sum(session)": [ - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - ] - }, - }, - { - "by": { - "project": 1, - "release": "version1", - "session.status": "crashed", - "environment": "production", - }, - "totals": {"sum(session)": 1}, - "series": { - "sum(session)": [ - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - ] - }, - }, - { - "by": { - "project": 1, - "release": "version2", - "session.status": "healthy", - "environment": "canary", - }, - "totals": {"sum(session)": 10}, - "series": { - "sum(session)": [ - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - ] - }, - }, - { - "by": { - "project": 1, - "release": "version2", - "session.status": "crashed", - "environment": "canary", - }, - "totals": {"sum(session)": 5}, - "series": { - "sum(session)": [ - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 0, - 0, - ] - }, - }, - { - "by": { - "project": 2, - "release": "version1", - "session.status": "healthy", - "environment": "production", - }, - "totals": {"sum(session)": 0}, - "series": { - "sum(session)": [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - ] - }, - }, - { - "by": { - "project": 2, - "release": "version2", - "session.status": "healthy", - "environment": "production", - }, - "totals": {"sum(session)": 5}, - "series": { - "sum(session)": [ - 0, - 0, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - ] - }, - }, - ], - "start": "2024-01-08T22:00:00Z", - "end": "2024-01-09T23:00:00Z", - "intervals": [ - "2024-01-08T22:00:00Z", - "2024-01-08T23:00:00Z", - "2024-01-09T00:00:00Z", - "2024-01-09T01:00:00Z", - "2024-01-09T02:00:00Z", - "2024-01-09T03:00:00Z", - "2024-01-09T04:00:00Z", - "2024-01-09T05:00:00Z", - "2024-01-09T06:00:00Z", - "2024-01-09T07:00:00Z", - ], - "query": "release:version1 OR release:version2", -} diff --git a/tests/sentry/api/endpoints/release_thresholds/health_checks/test_is_crash_free_rate_healthy.py b/tests/sentry/api/endpoints/release_thresholds/health_checks/test_is_crash_free_rate_healthy.py deleted file mode 100644 index 0c18cf2d8874..000000000000 --- a/tests/sentry/api/endpoints/release_thresholds/health_checks/test_is_crash_free_rate_healthy.py +++ /dev/null @@ -1,355 +0,0 @@ -from datetime import datetime, timedelta -from typing import NoReturn -from unittest.mock import MagicMock, patch - -import pytest - -from sentry.api.endpoints.release_thresholds.constants import CRASH_SESSIONS_DISPLAY -from sentry.api.endpoints.release_thresholds.health_checks.is_crash_free_rate_healthy import ( - get_groups_totals, - get_interval_indexes, - is_crash_free_rate_healthy_check, -) -from sentry.api.endpoints.release_thresholds.types import EnrichedThreshold -from sentry.api.serializers import serialize -from sentry.models.release import Release -from sentry.models.release_threshold.constants import ReleaseThresholdType, TriggerType -from sentry.testutils.cases import TestCase - -from .test_fixtures import mock_sessions_data - - -class TestGetIntervalIndexes: - def setup_method(self) -> None: - # d.strftime('%Y-%m-%dT%H:%M:%SZ') - # construct timestamps in iso utc format - self.now = datetime.utcnow() - self.intervals = [ - (self.now + timedelta(hours=x)).strftime("%Y-%m-%dT%H:%M:%SZ") for x in range(-5, 5) - ] - - def test_gets_indexes_range_in_intervals(self) -> None: - start = self.now - timedelta(hours=1) - end = self.now + timedelta(hours=1) - start_idx, end_idx = get_interval_indexes(intervals=self.intervals, start=start, end=end) - - assert start_idx == 5 - assert end_idx == 6 - - def test_gets_indexes_range_overlaps_intervals(self) -> None: - start = self.now - end = self.now + timedelta(hours=10) - start_idx, end_idx = get_interval_indexes(intervals=self.intervals, start=start, end=end) - - assert start_idx == 6 - assert end_idx == 9 - - start = self.now - timedelta(hours=10) - end = self.now - start_idx, end_idx = get_interval_indexes(intervals=self.intervals, start=start, end=end) - - assert start_idx == 0 - assert end_idx == 5 - - def test_returns_bad_idxs_when_not_within_intervals(self) -> None: - start = self.now - timedelta(15) - end = self.now - timedelta(hours=11) - start_idx, end_idx = get_interval_indexes(intervals=self.intervals, start=start, end=end) - - assert start_idx > end_idx - - -class TestGetGroupTotals: - def test_filters_groups_and_sums_total_success(self) -> None: - total_v1 = get_groups_totals( - sessions_data=mock_sessions_data, - release_version="version1", - project_id=1, - field="sum(session)", - start_idx=0, - end_idx=9, - ) - assert total_v1 == 11 - # filters via release version - total_v2 = get_groups_totals( - sessions_data=mock_sessions_data, - release_version="version2", - project_id=1, - field="sum(session)", - start_idx=0, - end_idx=9, - ) - assert total_v2 == 15 - - def test_filters_group_by_project(self) -> None: - total_p2_v1 = get_groups_totals( - sessions_data=mock_sessions_data, - release_version="version1", - project_id=2, - field="sum(session)", - start_idx=0, - end_idx=9, - ) - assert total_p2_v1 == 0 - - total_p2_v2 = get_groups_totals( - sessions_data=mock_sessions_data, - release_version="version2", - project_id=2, - field="sum(session)", - start_idx=0, - end_idx=9, - ) - assert total_p2_v2 == 5 - - def test_filters_group_by_environment(self) -> None: - total_canary = get_groups_totals( - sessions_data=mock_sessions_data, - release_version="version1", - project_id=1, - field="sum(session)", - start_idx=0, - end_idx=9, - environment="canary", - ) - assert total_canary == 0 - total_production = get_groups_totals( - sessions_data=mock_sessions_data, - release_version="version1", - project_id=1, - field="sum(session)", - start_idx=0, - end_idx=9, - environment="production", - ) - assert total_production == 11 - - def test_filters_group_by_status(self) -> None: - crashed = get_groups_totals( - sessions_data=mock_sessions_data, - release_version="version1", - project_id=1, - field="sum(session)", - start_idx=0, - end_idx=9, - status="crashed", - ) - assert crashed == 1 - - def test_sums_group_via_indexes(self) -> None: - total_5_9 = get_groups_totals( - sessions_data=mock_sessions_data, - release_version="version1", - project_id=1, - field="sum(session)", - start_idx=5, - end_idx=9, - ) - assert total_5_9 == 5 - - def test_raises_errors_with_bad_indexes(self) -> None: - with pytest.raises(IndexError): - get_groups_totals( - sessions_data=mock_sessions_data, - release_version="version1", - project_id=1, - field="sum(session)", - start_idx=11, - end_idx=20, - ) - - with pytest.raises(IndexError): - get_groups_totals( - sessions_data=mock_sessions_data, - release_version="version1", - project_id=1, - field="sum(session)", - start_idx=1, - end_idx=20, - ) - - -class CrashFreeRateThresholdCheckTest(TestCase): - def setUp(self) -> None: - self.project1 = self.create_project(name="foo", organization=self.organization) - self.release1 = Release.objects.create(version="v1", organization=self.organization) - self.sessions_data = mock_sessions_data - - @patch( - "sentry.api.endpoints.release_thresholds.health_checks.is_crash_free_rate_healthy.get_interval_indexes" - ) - @patch( - "sentry.api.endpoints.release_thresholds.health_checks.is_crash_free_rate_healthy.get_groups_totals" - ) - def test_is_crash_free_rate_success( - self, mock_get_groups_totals: MagicMock, mock_get_interval_indexes: MagicMock - ) -> None: - now = datetime.utcnow() - - mock_get_interval_indexes.return_value = 0, 10 - mock_get_groups_totals.side_effect = [0, 10] - - # current threshold within series - mock_threshold: EnrichedThreshold = { - "id": "1", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.CRASH_FREE_SESSION_RATE_STR, - "trigger_type": TriggerType.UNDER_STR, - "value": 99, # crash free rate - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_value = is_crash_free_rate_healthy_check( - ethreshold=mock_threshold, - sessions_data=self.sessions_data, - display=CRASH_SESSIONS_DISPLAY, - ) - - assert mock_get_interval_indexes.call_count == 1 - assert mock_get_groups_totals.call_count == 2 - assert is_healthy - assert metric_value == 100 - - @patch( - "sentry.api.endpoints.release_thresholds.health_checks.is_crash_free_rate_healthy.get_interval_indexes" - ) - @patch( - "sentry.api.endpoints.release_thresholds.health_checks.is_crash_free_rate_healthy.get_groups_totals" - ) - def test_is_crash_free_rate_failure( - self, mock_get_groups_totals: MagicMock, mock_get_interval_indexes: MagicMock - ) -> None: - now = datetime.utcnow() - - mock_get_interval_indexes.return_value = 0, 10 - mock_get_groups_totals.side_effect = [5, 10] # 5 crashes, 10 total - - # current threshold within series - mock_threshold: EnrichedThreshold = { - "id": "1", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.CRASH_FREE_SESSION_RATE_STR, - "trigger_type": TriggerType.UNDER_STR, - "value": 99, # crash free rate - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_value = is_crash_free_rate_healthy_check( - ethreshold=mock_threshold, - sessions_data=self.sessions_data, - display=CRASH_SESSIONS_DISPLAY, - ) - - assert mock_get_interval_indexes.call_count == 1 - assert mock_get_groups_totals.call_count == 2 - assert not is_healthy - assert metric_value == 50 - - @patch( - "sentry.api.endpoints.release_thresholds.health_checks.is_crash_free_rate_healthy.get_interval_indexes" - ) - @patch( - "sentry.api.endpoints.release_thresholds.health_checks.is_crash_free_rate_healthy.get_groups_totals" - ) - def test_is_crash_free_rate_catches_interval_idx_error( - self, mock_get_groups_totals: MagicMock, mock_get_interval_indexes: MagicMock - ) -> None: - now = datetime.utcnow() - - mock_get_interval_indexes.return_value = 0, 10 - - def side_effect(**kwargs: object) -> NoReturn: - raise IndexError - - mock_get_groups_totals.side_effect = side_effect - - # current threshold within series - mock_threshold: EnrichedThreshold = { - "id": "1", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.CRASH_FREE_SESSION_RATE_STR, - "trigger_type": TriggerType.UNDER_STR, - "value": 99, # crash free rate - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_value = is_crash_free_rate_healthy_check( - ethreshold=mock_threshold, - sessions_data=self.sessions_data, - display=CRASH_SESSIONS_DISPLAY, - ) - - assert mock_get_interval_indexes.call_count == 1 - assert mock_get_groups_totals.call_count == 1 - assert not is_healthy - assert metric_value == -1 - - @patch( - "sentry.api.endpoints.release_thresholds.health_checks.is_crash_free_rate_healthy.get_interval_indexes" - ) - @patch( - "sentry.api.endpoints.release_thresholds.health_checks.is_crash_free_rate_healthy.get_groups_totals" - ) - def test_get_group_catches_totals_errors( - self, mock_get_groups_totals: MagicMock, mock_get_interval_indexes: MagicMock - ) -> None: - now = datetime.utcnow() - - mock_get_interval_indexes.return_value = 10, 0 - - # current threshold within series - mock_threshold: EnrichedThreshold = { - "id": "1", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.CRASH_FREE_SESSION_RATE_STR, - "trigger_type": TriggerType.UNDER_STR, - "value": 99, # crash free rate - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_value = is_crash_free_rate_healthy_check( - ethreshold=mock_threshold, - sessions_data=self.sessions_data, - display=CRASH_SESSIONS_DISPLAY, - ) - - assert mock_get_interval_indexes.call_count == 1 - assert mock_get_groups_totals.call_count == 0 - assert not is_healthy - assert metric_value == -1 diff --git a/tests/sentry/api/endpoints/release_thresholds/health_checks/test_is_error_count_healthy.py b/tests/sentry/api/endpoints/release_thresholds/health_checks/test_is_error_count_healthy.py deleted file mode 100644 index 8f1e28e918ce..000000000000 --- a/tests/sentry/api/endpoints/release_thresholds/health_checks/test_is_error_count_healthy.py +++ /dev/null @@ -1,684 +0,0 @@ -from datetime import timedelta - -from django.utils import timezone - -from sentry.api.endpoints.release_thresholds.health_checks.is_error_count_healthy import ( - is_error_count_healthy, -) -from sentry.api.endpoints.release_thresholds.types import EnrichedThreshold -from sentry.api.serializers import serialize -from sentry.models.environment import Environment -from sentry.models.release import Release -from sentry.models.release_threshold.constants import ReleaseThresholdType, TriggerType -from sentry.testutils.cases import TestCase - - -class ErrorCountThresholdCheckTest(TestCase): - def setUp(self) -> None: - # 3 projects - self.project1 = self.create_project(name="foo", organization=self.organization) - self.project2 = self.create_project(name="bar", organization=self.organization) - - self.canary_environment = Environment.objects.create( - organization_id=self.organization.id, name="canary" - ) - - # release created for proj1, and proj2 - self.release1 = Release.objects.create(version="v1", organization=self.organization) - # add_project get_or_creates a ReleaseProject - self.release1.add_project(self.project1) - self.release1.add_project(self.project2) - - # release created for proj1 - self.release2 = Release.objects.create(version="v2", organization=self.organization) - # add_project get_or_creates a ReleaseProject - self.release2.add_project(self.project1) - - def test_threshold_within_timeseries(self) -> None: - """ - construct a timeseries with: - - a single release - - a single project - - no environment - - multiple timestamps both before and after our threshold window - """ - now = timezone.now() - timeseries = [ - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=3)).isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=2)).isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=1)).isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": now.isoformat(), - "environment": None, - "count()": 1, - }, - ] - - # current threshold within series - current_threshold_healthy: EnrichedThreshold = { - "id": "1", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 4, # error counts _not_ be over threshold value - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_count = is_error_count_healthy( - ethreshold=current_threshold_healthy, timeseries=timeseries - ) - assert is_healthy - - # threshold equal to count - threshold_at_limit_healthy: EnrichedThreshold = { - "id": "2", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 1, # error counts equal to threshold limit value - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_count = is_error_count_healthy( - ethreshold=threshold_at_limit_healthy, timeseries=timeseries - ) - assert is_healthy - - # past healthy threshold within series - past_threshold_healthy: EnrichedThreshold = { - "id": "3", - "date_added": now, - "start": now - timedelta(minutes=2), - "end": now - timedelta(minutes=1), - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 2, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_count = is_error_count_healthy( - ethreshold=past_threshold_healthy, timeseries=timeseries - ) - assert is_healthy - - # threshold within series but trigger is under - threshold_under_unhealthy: EnrichedThreshold = { - "id": "4", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, - "trigger_type": TriggerType.UNDER_STR, - "value": 4, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_count = is_error_count_healthy( - ethreshold=threshold_under_unhealthy, timeseries=timeseries - ) - assert not is_healthy - - # threshold within series but end is in future - threshold_unfinished: EnrichedThreshold = { - "id": "5", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now + timedelta(minutes=5), - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 4, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_count = is_error_count_healthy( - ethreshold=threshold_unfinished, timeseries=timeseries - ) - assert is_healthy - - def test_multiple_releases_within_timeseries(self) -> None: - now = timezone.now() - timeseries = [ - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=3)).isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release2.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=3)).isoformat(), - "environment": None, - "count()": 2, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=2)).isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release2.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=2)).isoformat(), - "environment": None, - "count()": 2, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=1)).isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release2.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=1)).isoformat(), - "environment": None, - "count()": 2, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": now.isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release2.version, - "project_id": self.project1.id, - "time": now.isoformat(), - "environment": None, - "count()": 2, - }, - ] - - # base threshold within series - threshold_healthy: EnrichedThreshold = { - "id": "1", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 4, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_count = is_error_count_healthy( - ethreshold=threshold_healthy, timeseries=timeseries - ) - assert is_healthy - - # threshold within series but separate unhealthy release - threshold_unhealthy: EnrichedThreshold = { - "id": "2", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release2.version, - "threshold_type": ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 1, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_count = is_error_count_healthy( - ethreshold=threshold_unhealthy, timeseries=timeseries - ) - assert not is_healthy - - def test_multiple_projects_within_timeseries(self) -> None: - now = timezone.now() - timeseries = [ - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=3)).isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release1.version, - "project_id": self.project2.id, - "time": (now - timedelta(minutes=3)).isoformat(), - "environment": None, - "count()": 2, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=2)).isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release1.version, - "project_id": self.project2.id, - "time": (now - timedelta(minutes=2)).isoformat(), - "environment": None, - "count()": 2, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=1)).isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release1.version, - "project_id": self.project2.id, - "time": (now - timedelta(minutes=1)).isoformat(), - "environment": None, - "count()": 2, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": now.isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release1.version, - "project_id": self.project2.id, - "time": now.isoformat(), - "environment": None, - "count()": 2, - }, - ] - - # base threshold within series - # unhealthy means error count OVER 4 over 1m window - threshold_healthy: EnrichedThreshold = { - "id": "1", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 4, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_count = is_error_count_healthy( - ethreshold=threshold_healthy, timeseries=timeseries - ) - assert is_healthy - - # threshold within series but separate unhealthy project - threshold_unhealthy: EnrichedThreshold = { - "id": "2", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project2), - "project_id": self.project2.id, - "project_slug": self.project2.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 1, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_count = is_error_count_healthy( - ethreshold=threshold_unhealthy, timeseries=timeseries - ) - assert not is_healthy - - def test_multiple_environments_within_timeseries(self) -> None: - now = timezone.now() - timeseries = [ - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=3)).isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=3)).isoformat(), - "environment": "canary", - "count()": 2, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=2)).isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=2)).isoformat(), - "environment": "canary", - "count()": 2, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=1)).isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=1)).isoformat(), - "environment": "canary", - "count()": 2, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": now.isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": now.isoformat(), - "environment": "canary", - "count()": 2, - }, - ] - - # base threshold within series - threshold_healthy: EnrichedThreshold = { - "id": "1", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 2, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_count = is_error_count_healthy( - ethreshold=threshold_healthy, timeseries=timeseries - ) - assert is_healthy - - # threshold within series but separate unhealthy environment - threshold_unhealthy: EnrichedThreshold = { - "id": "2", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": serialize(self.canary_environment), - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 1, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_count = is_error_count_healthy( - ethreshold=threshold_unhealthy, timeseries=timeseries - ) - assert not is_healthy - - def test_unordered_timeseries(self) -> None: - """ - construct a timeseries with: - - a single release - - a single project - - no environment - - multiple timestamps both before and after our threshold window - - all disorganized - """ - now = timezone.now() - timeseries = [ - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=3)).isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": now.isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=1)).isoformat(), - "environment": None, - "count()": 1, - }, - { - "release": self.release1.version, - "project_id": self.project1.id, - "time": (now - timedelta(minutes=2)).isoformat(), - "environment": None, - "count()": 1, - }, - ] - - # current threshold within series - current_threshold_healthy: EnrichedThreshold = { - "id": "1", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 4, # error counts _not_ be over threshold value - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_count = is_error_count_healthy( - ethreshold=current_threshold_healthy, timeseries=timeseries - ) - assert is_healthy - - # threshold equal to count - threshold_at_limit_healthy: EnrichedThreshold = { - "id": "2", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 1, # error counts equal to threshold limit value - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_count = is_error_count_healthy( - ethreshold=threshold_at_limit_healthy, timeseries=timeseries - ) - assert is_healthy - - # past healthy threshold within series - past_threshold_healthy: EnrichedThreshold = { - "id": "3", - "date_added": now, - "start": now - timedelta(minutes=2), - "end": now - timedelta(minutes=1), - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 2, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_count = is_error_count_healthy( - ethreshold=past_threshold_healthy, timeseries=timeseries - ) - assert is_healthy - - # threshold within series but trigger is under - threshold_under_unhealthy: EnrichedThreshold = { - "id": "4", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, - "trigger_type": TriggerType.UNDER_STR, - "value": 4, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_count = is_error_count_healthy( - ethreshold=threshold_under_unhealthy, timeseries=timeseries - ) - assert not is_healthy - - # threshold within series but end is in future - threshold_unfinished: EnrichedThreshold = { - "id": "5", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now + timedelta(minutes=5), - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 4, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - is_healthy, metric_count = is_error_count_healthy( - ethreshold=threshold_unfinished, timeseries=timeseries - ) - assert is_healthy diff --git a/tests/sentry/api/endpoints/release_thresholds/health_checks/test_is_new_issue_count_healthy.py b/tests/sentry/api/endpoints/release_thresholds/health_checks/test_is_new_issue_count_healthy.py deleted file mode 100644 index 4647f8390e2b..000000000000 --- a/tests/sentry/api/endpoints/release_thresholds/health_checks/test_is_new_issue_count_healthy.py +++ /dev/null @@ -1,169 +0,0 @@ -from datetime import timedelta -from typing import Any - -from django.utils import timezone - -from sentry.api.endpoints.release_thresholds.health_checks import is_new_issue_count_healthy -from sentry.api.endpoints.release_thresholds.types import EnrichedThreshold -from sentry.api.serializers import serialize -from sentry.models.release import Release -from sentry.models.release_threshold.constants import ReleaseThresholdType, TriggerType -from sentry.testutils.cases import TestCase - - -class NewIssueCountThresholdCheckTest(TestCase): - def setUp(self) -> None: - self.project1 = self.create_project(name="foo", organization=self.organization) - self.release1 = Release.objects.create(version="v1", organization=self.organization) - - def test_success(self) -> None: - now = timezone.now() - mock_threshold: EnrichedThreshold = { - "id": "1", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.NEW_ISSUE_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 10, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - mock_new_issue_counts = { - "1": 0, - } - is_healthy, metric_value = is_new_issue_count_healthy(mock_threshold, mock_new_issue_counts) - assert is_healthy - assert metric_value == 0 - - def test_multiple_thresholds(self) -> None: - now = timezone.now() - threshold: EnrichedThreshold = { - "id": "1", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.NEW_ISSUE_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 10, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - threshold2: EnrichedThreshold = { - "id": "2", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.NEW_ISSUE_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 10, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - threshold3: EnrichedThreshold = { - "id": "3", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.NEW_ISSUE_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 10, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - mock_new_issue_counts = { - "1": 0, - "2": 10, - "3": 100, - } - is_healthy, metric_value = is_new_issue_count_healthy(threshold, mock_new_issue_counts) - assert is_healthy - assert metric_value == 0 - - is_healthy, metric_value = is_new_issue_count_healthy(threshold2, mock_new_issue_counts) - assert is_healthy - assert metric_value == 10 - - is_healthy, metric_value = is_new_issue_count_healthy(threshold3, mock_new_issue_counts) - assert not is_healthy - assert metric_value == 100 - - def test_success_under(self) -> None: - now = timezone.now() - mock_threshold: EnrichedThreshold = { - "id": "1", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.NEW_ISSUE_COUNT_STR, - "trigger_type": TriggerType.UNDER_STR, - "value": 10, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - mock_new_issue_counts = { - "1": 0, - } - is_healthy, metric_value = is_new_issue_count_healthy(mock_threshold, mock_new_issue_counts) - assert not is_healthy - assert metric_value == 0 - - def test_no_new_issues(self) -> None: - now = timezone.now() - mock_threshold: EnrichedThreshold = { - "id": "1", - "date_added": now, - "start": now - timedelta(minutes=1), - "end": now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_id": self.project1.id, - "project_slug": self.project1.slug, - "release": self.release1.version, - "threshold_type": ReleaseThresholdType.NEW_ISSUE_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 10, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - mock_new_issue_counts: dict[str, Any] = {} - is_healthy, metric_value = is_new_issue_count_healthy(mock_threshold, mock_new_issue_counts) - assert is_healthy - assert metric_value == 0 diff --git a/tests/sentry/api/endpoints/release_thresholds/test_release_threshold.py b/tests/sentry/api/endpoints/release_thresholds/test_release_threshold.py deleted file mode 100644 index 08798bd4f00d..000000000000 --- a/tests/sentry/api/endpoints/release_thresholds/test_release_threshold.py +++ /dev/null @@ -1,237 +0,0 @@ -from django.urls import reverse - -from sentry.models.environment import Environment -from sentry.models.release_threshold.release_threshold import ReleaseThreshold -from sentry.testutils.cases import APITestCase - - -class ReleaseThresholdTest(APITestCase): - def setUp(self) -> None: - super().setUp() - self.user = self.create_user(is_staff=True, is_superuser=True) - - self.canary_environment = Environment.objects.create( - organization_id=self.organization.id, name="canary" - ) - self.production_environment = Environment.objects.create( - organization_id=self.organization.id, name="production" - ) - self.login_as(user=self.user) - - self.url = reverse( - "sentry-api-0-project-release-thresholds", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - }, - ) - - def test_post_missing_params(self) -> None: - response = self.client.post( - self.url, - data={ - "threshold_type": "total_error_count", - "trigger_type": "over", - # value is missing - "window_in_seconds": 1800, - "environment": "canary", - }, - ) - - assert response.status_code == 400 - assert response.data == {"value": ["This field is required."]} - - def test_post_invalid_threshold_type(self) -> None: - response = self.client.post( - self.url, - data={ - "threshold_type": "indiana_jones_and_the_temple_of_doom", - "trigger_type": "over", - "value": 100, - "window_in_seconds": 1800, - "environment": "canary", - }, - ) - - assert response.status_code == 400 - assert response.data["threshold_type"][0].code == "invalid_choice" - - def test_post_invalid_trigger_type(self) -> None: - response = self.client.post( - self.url, - data={ - "threshold_type": "total_error_count", - "trigger_type": "short_round", - "value": 100, - "window_in_seconds": 1800, - "environment": "production", - }, - ) - - assert response.status_code == 400 - assert response.data["trigger_type"][0].code == "invalid_choice" - - def test_post_invalid_project(self) -> None: - url_with_invalid_project = reverse( - "sentry-api-0-project-release-thresholds", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": "Why did it have to be snakes?", - }, - ) - response = self.client.post( - url_with_invalid_project, - data={ - "threshold_type": "total_error_count", - "trigger_type": "over", - "value": 100, - "window_in_seconds": 1800, - "environment": "production", - }, - ) - assert response.status_code == 404 - - def test_post_invalid_environment(self) -> None: - response = self.client.post( - self.url, - data={ - "threshold_type": "total_error_count", - "trigger_type": "over", - "value": 100, - "window_in_seconds": 1800, - "environment": "Sentry belongs in a museum.", - }, - ) - assert response.status_code == 400 - assert response.data["environment"][0].code == "invalid" - - def test_post_valid_no_environment(self) -> None: - response = self.client.post( - self.url, - data={ - "threshold_type": "total_error_count", - "trigger_type": "over", - "value": 100, - "window_in_seconds": 1800, - }, - ) - assert response.status_code == 201 - data = response.data - assert data["threshold_type"] == "total_error_count" - assert data["trigger_type"] == "over" - assert data["value"] == 100 - assert data["window_in_seconds"] == 1800 - assert data["project"]["id"] == str(self.project.id) - assert data["project"]["slug"] == self.project.slug - assert data["project"]["name"] == self.project.name - assert data["environment"] is None - assert data["date_added"] is not None - - def test_post_valid(self) -> None: - response = self.client.post( - self.url, - data={ - "threshold_type": "total_error_count", - "trigger_type": "over", - "value": 100, - "window_in_seconds": 1800, - "environment": "canary", - }, - ) - - assert response.status_code == 201 - data = response.data - assert data["threshold_type"] == "total_error_count" - assert data["trigger_type"] == "over" - assert data["value"] == 100 - assert data["window_in_seconds"] == 1800 - assert data["project"]["id"] == str(self.project.id) - assert data["project"]["slug"] == self.project.slug - assert data["project"]["name"] == self.project.name - assert data["environment"]["id"] == str(self.canary_environment.id) - assert data["environment"]["name"] == self.canary_environment.name - assert data["date_added"] is not None - - def test_get_invalid_project(self) -> None: - url_with_invalid_project = reverse( - "sentry-api-0-project-release-thresholds", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": "Why did it have to be snakes?", - }, - ) - response = self.client.get(url_with_invalid_project, data={"environment": "canary"}) - assert response.status_code == 404 - - def test_get_invalid_environment(self) -> None: - response = self.client.get(self.url, data={"environment": "The Hovitos are near"}) - assert response.status_code == 200 - assert len(response.data) == 0 - - def test_get_valid_no_environment(self) -> None: - response = self.client.get(self.url) - assert response.status_code == 200 - assert len(response.data) == 0 - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - response = self.client.get(self.url) - assert response.status_code == 200 - assert len(response.data) == 1 - - created_threshold = response.data[0] - - assert created_threshold["threshold_type"] == "total_error_count" - assert created_threshold["trigger_type"] == "over" - assert created_threshold["value"] == 100 - assert created_threshold["window_in_seconds"] == 1800 - assert created_threshold["project"]["id"] == str(self.project.id) - assert created_threshold["project"]["slug"] == self.project.slug - assert created_threshold["project"]["name"] == self.project.name - assert created_threshold["environment"]["id"] == str(self.canary_environment.id) - assert created_threshold["environment"]["name"] == self.canary_environment.name - - def test_get_valid_with_environment(self) -> None: - response = self.client.get(self.url, data={"environment": "canary"}) - assert response.status_code == 200 - assert len(response.data) == 0 - - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=1, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.production_environment, - ) - - response = self.client.get(self.url, data={"environment": "canary"}) - assert response.status_code == 200 - assert len(response.data) == 1 - - created_threshold = response.data[0] - - assert created_threshold["threshold_type"] == "total_error_count" - assert created_threshold["trigger_type"] == "over" - assert created_threshold["value"] == 100 - assert created_threshold["window_in_seconds"] == 1800 - assert created_threshold["project"]["id"] == str(self.project.id) - assert created_threshold["project"]["slug"] == self.project.slug - assert created_threshold["project"]["name"] == self.project.name - assert created_threshold["environment"]["id"] == str(self.canary_environment.id) - assert created_threshold["environment"]["name"] == self.canary_environment.name diff --git a/tests/sentry/api/endpoints/release_thresholds/test_release_threshold_details.py b/tests/sentry/api/endpoints/release_thresholds/test_release_threshold_details.py deleted file mode 100644 index 2147cfb6cf5f..000000000000 --- a/tests/sentry/api/endpoints/release_thresholds/test_release_threshold_details.py +++ /dev/null @@ -1,329 +0,0 @@ -from django.urls import reverse - -from sentry.models.environment import Environment -from sentry.models.release_threshold.constants import THRESHOLD_TYPE_INT_TO_STR -from sentry.models.release_threshold.release_threshold import ReleaseThreshold -from sentry.testutils.cases import APITestCase - - -class ReleaseThresholdDetailsGETTest(APITestCase): - def setUp(self) -> None: - super().setUp() - self.user = self.create_user(is_staff=True, is_superuser=True) - - self.canary_environment = Environment.objects.create( - organization_id=self.organization.id, name="canary" - ) - self.production_environment = Environment.objects.create( - organization_id=self.organization.id, name="production" - ) - self.login_as(user=self.user) - - self.basic_threshold = ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - def test_invalid_threshold_id(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": 123, - }, - ) - response = self.client.get(url) - - assert response.status_code == 404 - - def test_invalid_project(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": "kingdom_of_the_crystal_skull", - "release_threshold": self.basic_threshold.id, - }, - ) - response = self.client.get(url) - - assert response.status_code == 404 - - def test_valid(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": self.basic_threshold.id, - }, - ) - response = self.client.get(url) - - assert response.status_code == 200 - assert response.data["id"] == str(self.basic_threshold.id) - assert response.data["threshold_type"] == "total_error_count" - assert response.data["trigger_type"] == "over" - assert response.data["value"] == 100 - assert response.data["window_in_seconds"] == 1800 - - -class ReleaseThresholdDetailsDELETETest(APITestCase): - def setUp(self) -> None: - super().setUp() - self.user = self.create_user(is_staff=True, is_superuser=True) - - self.canary_environment = Environment.objects.create( - organization_id=self.organization.id, name="canary" - ) - self.production_environment = Environment.objects.create( - organization_id=self.organization.id, name="production" - ) - self.login_as(user=self.user) - - self.basic_threshold = ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - def test_invalid_threshold_id(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": 123, - }, - ) - response = self.client.delete(url) - - assert response.status_code == 404 - - def test_invalid_project(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": "kingdom_of_the_crystal_skull", - "release_threshold": self.basic_threshold.id, - }, - ) - response = self.client.delete(url) - - assert response.status_code == 404 - - def test_valid(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": self.basic_threshold.id, - }, - ) - response = self.client.delete(url) - - assert response.status_code == 204 - - -class ReleaseThresholdDetailsPUTTest(APITestCase): - def setUp(self) -> None: - super().setUp() - self.user = self.create_user(is_staff=True, is_superuser=True) - - self.canary_environment = Environment.objects.create( - organization_id=self.organization.id, name="canary" - ) - self.production_environment = Environment.objects.create( - organization_id=self.organization.id, name="production" - ) - self.login_as(user=self.user) - - self.basic_threshold = ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - def test_invalid_threshold_id(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": 123, - }, - ) - response = self.client.put(url) - - assert response.status_code == 404 - - def test_invalid_missing_data(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": self.basic_threshold.id, - }, - ) - assert self.basic_threshold.environment is not None - data = { - "project": self.basic_threshold.project.id, - "environment": self.basic_threshold.environment.name, - "id": self.basic_threshold.id, - } - response = self.client.put(url, data) - assert response.status_code == 400 - - def test_invalid_trigger_type(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": self.basic_threshold.id, - }, - ) - assert self.basic_threshold.environment is not None - data = { - "project": self.basic_threshold.project.id, - "environment": self.basic_threshold.environment.name, - "id": self.basic_threshold.id, - "trigger_type": "foobar", - "threshold_type": THRESHOLD_TYPE_INT_TO_STR[self.basic_threshold.threshold_type], - "value": 50, - "window_in_seconds": 120, - } - response = self.client.put(url, data) - assert response.status_code == 400 - - def test_invalid_threshold_type(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": self.basic_threshold.id, - }, - ) - assert self.basic_threshold.environment is not None - data = { - "project": self.basic_threshold.project.id, - "environment": self.basic_threshold.environment.name, - "id": self.basic_threshold.id, - "trigger_type": "over", - "threshold_type": "foobar", - "value": 50, - "window_in_seconds": 120, - } - response = self.client.put(url, data) - assert response.status_code == 400 - - def test_invalid_window(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": self.basic_threshold.id, - }, - ) - assert self.basic_threshold.environment is not None - data = { - "project": self.basic_threshold.project.id, - "environment": self.basic_threshold.environment.name, - "id": self.basic_threshold.id, - "trigger_type": "over", - "threshold_type": THRESHOLD_TYPE_INT_TO_STR[self.basic_threshold.threshold_type], - "value": 50, - "window_in_seconds": -120, - } - response = self.client.put(url, data) - assert response.status_code == 400 - - def test_invalid_project(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": "kingdom_of_the_crystal_skull", - "release_threshold": self.basic_threshold.id, - }, - ) - response = self.client.put(url) - - assert response.status_code == 404 - - def test_valid(self) -> None: - assert self.basic_threshold.environment is not None - updated_data = { - "project": self.basic_threshold.project.id, - "environment": self.basic_threshold.environment.name, - "date_added": self.basic_threshold.date_added, - "id": self.basic_threshold.id, - "trigger_type": "under", - "threshold_type": THRESHOLD_TYPE_INT_TO_STR[self.basic_threshold.threshold_type], - "value": 50, - "window_in_seconds": 120, - } - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": self.basic_threshold.id, - }, - ) - response = self.client.put(url, data=updated_data) - - assert response.status_code == 200 - assert response.data["id"] == str(self.basic_threshold.id) - assert response.data["threshold_type"] == "total_error_count" - assert response.data["trigger_type"] == updated_data["trigger_type"] - assert response.data["value"] == updated_data["value"] - assert response.data["window_in_seconds"] == updated_data["window_in_seconds"] - assert response.data["environment"]["name"] == "canary" - - def test_valid_with_extra_data(self) -> None: - updated_data = { - "project": self.basic_threshold.project.id, - "environment": "foobar", - "date_added": self.basic_threshold.date_added, - "id": self.basic_threshold.id, - "trigger_type": "under", - "threshold_type": THRESHOLD_TYPE_INT_TO_STR[self.basic_threshold.threshold_type], - "value": 50, - "window_in_seconds": 120, - "foo": "bar", - "biz": "baz", - } - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": self.basic_threshold.id, - }, - ) - response = self.client.put(url, data=updated_data) - - assert response.status_code == 200 - assert response.data["id"] == str(self.basic_threshold.id) - assert response.data["threshold_type"] == "total_error_count" - assert response.data["trigger_type"] == updated_data["trigger_type"] - assert response.data["value"] == updated_data["value"] - assert response.data["window_in_seconds"] == updated_data["window_in_seconds"] - assert response.data["environment"]["name"] == "canary" diff --git a/tests/sentry/api/endpoints/release_thresholds/test_release_threshold_status.py b/tests/sentry/api/endpoints/release_thresholds/test_release_threshold_status.py deleted file mode 100644 index cde3b874356c..000000000000 --- a/tests/sentry/api/endpoints/release_thresholds/test_release_threshold_status.py +++ /dev/null @@ -1,650 +0,0 @@ -from datetime import UTC, datetime, timedelta -from unittest.mock import MagicMock, patch - -from sentry.models.deploy import Deploy -from sentry.models.environment import Environment -from sentry.models.release import Release -from sentry.models.release_threshold.constants import ReleaseThresholdType -from sentry.models.release_threshold.release_threshold import ReleaseThreshold -from sentry.models.releaseenvironment import ReleaseEnvironment -from sentry.models.releaseprojectenvironment import ReleaseProjectEnvironment -from sentry.testutils.cases import APITestCase - - -class ReleaseThresholdStatusTest(APITestCase): - endpoint = "sentry-api-0-organization-release-threshold-statuses" - method = "get" - - def setUp(self) -> None: - super().setUp() - self.user = self.create_user(is_staff=True, is_superuser=True) - # 3 projects - self.project1 = self.create_project(name="foo", organization=self.organization) - self.project2 = self.create_project(name="bar", organization=self.organization) - self.project3 = self.create_project(name="biz", organization=self.organization) - - # 2 environments - self.canary_environment = Environment.objects.create( - organization_id=self.organization.id, name="canary" - ) - self.production_environment = Environment.objects.create( - organization_id=self.organization.id, name="production" - ) - - # release created for proj1, and proj2 - self.release1 = Release.objects.create(version="v1", organization=self.organization) - # add_project get_or_creates a ReleaseProject - self.release1.add_project(self.project1) - self.release1.add_project(self.project2) - - # release created for proj1 - self.release2 = Release.objects.create(version="v2", organization=self.organization) - self.release2.add_project(self.project1) - - # release created for proj3 - self.release3 = Release.objects.create(version="v3", organization=self.organization) - self.release3.add_project(self.project3) - - # Attaches the release to a particular environment - # project superfluous/deprecated in ReleaseEnvironment - # release1 canary - ReleaseEnvironment.objects.create( - organization_id=self.organization.id, - release_id=self.release1.id, - environment_id=self.canary_environment.id, - ) - # Release Project Environments are required to query releases by project - # Even though both environment & project are here, this seems to just attach a release to a project - # You can have multiple ReleaseProjectEnvironment's per release (this attaches multiple projects to the release&env) - # release1 project1 canary - ReleaseProjectEnvironment.objects.create( - release_id=self.release1.id, - project_id=self.project1.id, - environment_id=self.canary_environment.id, - ) - # release1 project2 canary - ReleaseProjectEnvironment.objects.create( - release_id=self.release1.id, - project_id=self.project2.id, - environment_id=self.canary_environment.id, - ) - - # release2 prod - ReleaseEnvironment.objects.create( - organization_id=self.organization.id, - release_id=self.release2.id, - environment_id=self.production_environment.id, - ) - # release2 project1 prod - ReleaseProjectEnvironment.objects.create( - release_id=self.release2.id, - project_id=self.project1.id, - environment_id=self.production_environment.id, - ) - - # thresholds for project1 in canary - ReleaseThreshold.objects.create( - threshold_type=ReleaseThresholdType.TOTAL_ERROR_COUNT, - trigger_type=1, - value=100, - window_in_seconds=100, - project=self.project1, - environment=self.canary_environment, - ) - ReleaseThreshold.objects.create( - threshold_type=ReleaseThresholdType.TOTAL_ERROR_COUNT, - trigger_type=1, - value=100, - window_in_seconds=100, - project=self.project1, - environment=self.canary_environment, - ) - # threshold for project1 in production - ReleaseThreshold.objects.create( - threshold_type=ReleaseThresholdType.TOTAL_ERROR_COUNT, - trigger_type=1, - value=100, - window_in_seconds=100, - project=self.project1, - environment=self.production_environment, - ) - # threshold for project2 in canary - ReleaseThreshold.objects.create( - threshold_type=ReleaseThresholdType.TOTAL_ERROR_COUNT, - trigger_type=1, - value=100, - window_in_seconds=100, - project=self.project2, - environment=self.canary_environment, - ) - # threshold for project3 with no environment - # NOTE: project 3 is also the only project for which a release was created with NO environment - ReleaseThreshold.objects.create( - threshold_type=ReleaseThresholdType.TOTAL_ERROR_COUNT, - trigger_type=1, - value=100, - window_in_seconds=100, - project=self.project3, - ) - - self.login_as(user=self.user) - - def test_get_success(self) -> None: - """ - Tests fetching all thresholds (env+project agnostic) within the past 24hrs. - - Set up creates - - 3 releases - - release1 - canary # env only matters for how we filter releases - - r1-proj1-canary # NOTE: is it possible to have a ReleaseProjectEnvironment without a corresponding ReleaseEnvironment?? - - r1-proj2-canary - - release2 - prod # env only matters for how we filter releases - - r2-proj1-prod - - release3 - None - - 4 thresholds - - project1 canary error_counts - - project1 canary new_issues - - project1 prod error_counts - - project2 canary error_counts - - project3 no environment error_counts - - so response should look like - { - {p1.slug}-{release1.version}: [threshold, threshold1, threshold2] - {p1.slug}-{release2.version}: [threshold, threshold, threshold] - {p1.slug}-{release3.version}: [threshold] - {p2.slug}-{release1.version}: [threshold] - } - """ - now = datetime.now(UTC) - yesterday = datetime.now(UTC) - timedelta(hours=24) - last_week = datetime.now(UTC) - timedelta(days=7) - release_old = Release.objects.create( - version="old_version", organization=self.organization, date_added=last_week - ) - - response = self.get_success_response(self.organization.slug, start=yesterday, end=now) - - assert len(response.data.keys()) == 4 - for key in response.data.keys(): - # NOTE: special characters *can* be included in release versions or environment names - assert release_old.version not in key # old release is filtered out of response - data = response.data - # release1 - r1_keys = [k for k, v in data.items() if k.split("-")[1] == self.release1.version] - assert len(r1_keys) == 2 # 2 keys produced in release 1 (p1, p2) - - temp_key = f"{self.project1.slug}-{self.release1.version}" - assert temp_key in r1_keys - assert len(data[temp_key]) == 3 - temp_key = f"{self.project2.slug}-{self.release1.version}" - assert temp_key in r1_keys - assert len(data[temp_key]) == 1 - - # release2 - r2_keys = [k for k, v in data.items() if k.split("-")[1] == self.release2.version] - assert len(r2_keys) == 1 # 1 key produced in release 2 (p1) - temp_key = f"{self.project1.slug}-{self.release2.version}" - assert temp_key in r2_keys - assert len(data[temp_key]) == 3 - - # release3 - r3_keys = [k for k, v in data.items() if k.split("-")[1] == self.release3.version] - assert len(r3_keys) == 1 # 1 key produced in release 3 (p1) - temp_key = f"{self.project3.slug}-{self.release3.version}" - assert temp_key in r3_keys - assert len(data[temp_key]) == 1 - - def test_get_success_environment_filter(self) -> None: - """ - Tests fetching thresholds within the past 24hrs filtered on environment - - Set up creates - - 2 releases - - release1 - canary # env only matters for how we filter releases - - r1-proj1-canary - - r1-proj2-canary - - release2 - prod # env only matters for how we filter releases - - r2-proj1-prod - - 4 thresholds - - project1 canary error_counts - - project1 canary new_issues - - project1 prod error_counts - - project2 canary error_counts - - We'll filter for _only_ canary releases, so the response should look like - { - {p1.slug}-{release1.version}: [threshold1, threshold2] - {p2.slug}-{release1.version}: [threshold] - } - """ - now = datetime.now(UTC) - yesterday = datetime.now(UTC) - timedelta(hours=24) - response = self.get_success_response( - self.organization.slug, start=yesterday, end=now, environment=["canary"] - ) - - assert len(response.data.keys()) == 2 - data = response.data - # release1 - r1_keys = [k for k, v in data.items() if k.split("-")[1] == self.release1.version] - assert len(r1_keys) == 2 # 2 keys produced in release 1 (p1-canary, p2-canary) - - temp_key = f"{self.project1.slug}-{self.release1.version}" - assert temp_key in r1_keys - assert len(data[temp_key]) == 2 - assert data[temp_key][0].get("environment", {}).get("name") == "canary" - - temp_key = f"{self.project2.slug}-{self.release1.version}" - assert temp_key in r1_keys - assert len(data[temp_key]) == 1 - assert data[temp_key][0].get("environment", {}).get("name") == "canary" - - def test_get_success_environment_with_deploy(self) -> None: - """ - Tests fetching thresholds within the past 24hrs for a release+env with a related deploys - API should utilize deploy finished_at, rather than release created_at timestamp - - Set up creates - - 2 releases - - release1 - canary # env only matters for how we filter releases - - r1-proj1-canary - - r1-proj2-canary - - release2 - prod # env only matters for how we filter releases - - r2-proj1-prod - - 4 thresholds - - project1 canary error_counts - - project1 canary new_issues - - project1 prod error_counts - - project2 canary error_counts - - 1 deploy - - r1 + canary - - 1 ReleaseProjectEnvironment - - deploy + r1 + p1 + canary - - We'll filter for _only_ canary releases, so the response should look like - { - {p1.slug}-{release1.version}: [threshold1, threshold2] - {p2.slug}-{release1.version}: [threshold] - } - """ - now = datetime.now(UTC) - yesterday = datetime.now(UTC) - timedelta(hours=24) - - # Creates a deploy for a particular Release in a particular Environment - r1_canary_deploy = Deploy.objects.create( - environment_id=self.canary_environment.id, - organization_id=self.organization.id, - release=self.release1, - date_finished=now, - ) - rpe = ReleaseProjectEnvironment.objects.get( - release_id=self.release1.id, - project_id=self.project1.id, - environment_id=self.canary_environment.id, - ) - rpe.update( - last_deploy_id=r1_canary_deploy.id, - ) - - response = self.get_success_response( - self.organization.slug, start=yesterday, end=now, environment=["canary"] - ) - - assert len(response.data.keys()) == 2 - data = response.data - # release1 - r1_keys = [k for k, v in data.items() if k.split("-")[1] == self.release1.version] - assert len(r1_keys) == 2 # 2 keys produced in release 1 (p1-canary, p2-canary) - - temp_key = f"{self.project1.slug}-{self.release1.version}" - assert temp_key in r1_keys - assert len(data[temp_key]) == 2 - assert data[temp_key][0].get("environment", {}).get("name") == "canary" - - temp_key = f"{self.project2.slug}-{self.release1.version}" - assert temp_key in r1_keys - assert len(data[temp_key]) == 1 - assert data[temp_key][0].get("environment", {}).get("name") == "canary" - - def test_get_success_release_filter(self) -> None: - """ - Tests fetching thresholds within the past 24hrs filtered on release versions - - Set up creates - - 2 releases - - release1 - canary # env only matters for how we filter releases - - r1-proj1-canary - - r1-proj2-canary - - release2 - prod # env only matters for how we filter releases - - r2-proj1-prod - - 4 thresholds - - project1 canary error_counts - - project1 canary new_issues - - project1 prod error_counts - - project2 canary error_counts - - We'll filter for _only_ release1, so the response should look like - { - {p1.slug}-{release1.version}: [threshold1, threshold2, threshold] - {p2.slug}-{release1.version}: [threshold] - } - """ - now = datetime.now(UTC) - yesterday = datetime.now(UTC) - timedelta(hours=24) - response = self.get_success_response( - self.organization.slug, start=yesterday, end=now, release=[self.release1.version] - ) - - assert len(response.data.keys()) == 2 - data = response.data - # release1 - r1_keys = [k for k, v in data.items() if k.split("-")[1] == self.release1.version] - assert len(r1_keys) == 2 # 2 keys produced in release 1 (p1, p2) - - temp_key = f"{self.project1.slug}-{self.release1.version}" - assert temp_key in r1_keys - assert len(data[temp_key]) == 3 - temp_key = f"{self.project2.slug}-{self.release1.version}" - assert temp_key in r1_keys - assert len(data[temp_key]) == 1 - - # release2 - r2_keys = [k for k, v in data.items() if k.split("-")[1] == self.release2.version] - assert len(r2_keys) == 0 - - def test_get_success_project_slug_filter(self) -> None: - """ - Tests fetching thresholds within the past 24hrs filtered on project_slug's - NOTE: Because releases may have multiple projects, filtering by project is _not_ adequate to - return accurate release health - So - filtering on project will give us all the releases associated with that project - but we still need all the other projects associated with the release to determine health status - - Set up creates - - 2 releases - - release1 - canary # env only matters for how we filter releases - - r1-proj1-canary - - r1-proj2-canary - - release2 - prod # env only matters for how we filter releases - - r2-proj1-prod - - 4 thresholds - - project1 canary error_counts - - project1 canary new_issues - - project1 prod error_counts - - project2 canary error_counts - - - We'll filter for _only_ project2, so the response should look like - since project2 was only ever added to release1 - { - {p2.slug}-{release1.version}: [threshold] - } - """ - now = datetime.now(UTC) - yesterday = datetime.now(UTC) - timedelta(hours=24) - response = self.get_success_response( - self.organization.slug, start=yesterday, end=now, projectSlug=[self.project2.slug] - ) - - assert len(response.data.keys()) == 1 - data = response.data - # release1 - r1_keys = [k for k, v in data.items() if k.split("-")[1] == self.release1.version] - assert len(r1_keys) == 1 # 1 key produced in release 1 (p2-canary) - - temp_key = f"{self.project1.slug}-{self.release1.version}" - assert temp_key not in r1_keys - temp_key = f"{self.project2.slug}-{self.release1.version}" - assert temp_key in r1_keys - assert len(data[temp_key]) == 1 - temp_key = ( - f"{self.project1.slug}-{self.production_environment.name}-{self.release1.version}" - ) - assert temp_key not in r1_keys - - # release2 - r2_keys = [k for k, v in data.items() if k.split("-")[1] == self.release2.version] - assert len(r2_keys) == 0 - - def test_get_success_project_param_slug_filter(self) -> None: - now = datetime.now(UTC) - yesterday = now - timedelta(hours=24) - - project_slug_response = self.get_success_response( - self.organization.slug, start=yesterday, end=now, projectSlug=[self.project2.slug] - ) - project_response = self.get_success_response( - self.organization.slug, start=yesterday, end=now, project=[self.project2.slug] - ) - - assert project_response.data == project_slug_response.data - - def test_get_success_project_param_mixed_id_and_slug_filter(self) -> None: - now = datetime.now(UTC) - yesterday = now - timedelta(hours=24) - - response = self.get_success_response( - self.organization.slug, - start=yesterday, - end=now, - project=[str(self.project1.id), self.project2.slug], - ) - - assert set(response.data.keys()) == { - f"{self.project1.slug}-{self.release1.version}", - f"{self.project1.slug}-{self.release2.version}", - f"{self.project2.slug}-{self.release1.version}", - } - - def test_get_success_project_slug_takes_precedence_over_project_id(self) -> None: - now = datetime.now(UTC) - yesterday = now - timedelta(hours=24) - - response = self.get_success_response( - self.organization.slug, - start=yesterday, - end=now, - projectSlug=[self.project2.slug], - project=[str(self.project1.id)], - ) - - assert set(response.data.keys()) == {f"{self.project2.slug}-{self.release1.version}"} - - def test_get_success_empty_project_slug_falls_back_to_project_filter(self) -> None: - now = datetime.now(UTC) - yesterday = now - timedelta(hours=24) - - response = self.get_success_response( - self.organization.slug, - start=yesterday, - end=now, - projectSlug=[""], - project=[self.project2.slug], - ) - - assert set(response.data.keys()) == {f"{self.project2.slug}-{self.release1.version}"} - - @patch( - "sentry.api.endpoints.release_thresholds.release_threshold_status_index.fetch_sessions_data" - ) - @patch( - "sentry.api.endpoints.release_thresholds.release_threshold_status_index.is_crash_free_rate_healthy_check" - ) - @patch( - "sentry.api.endpoints.release_thresholds.release_threshold_status_index.get_errors_counts_timeseries_by_project_and_release" - ) - @patch( - "sentry.api.endpoints.release_thresholds.release_threshold_status_index.is_error_count_healthy" - ) - @patch( - "sentry.api.endpoints.release_thresholds.release_threshold_status_index.get_new_issue_counts" - ) - @patch( - "sentry.api.endpoints.release_thresholds.release_threshold_status_index.is_new_issue_count_healthy" - ) - def test_fetches_relevant_stats( - self, - mock_is_new_issue_count_healthy: MagicMock, - mock_get_new_issue_counts: MagicMock, - mock_is_error_count_healthy: MagicMock, - mock_get_error_counts: MagicMock, - mock_is_crash_free_rate_healthy: MagicMock, - mock_fetch_sessions_data: MagicMock, - ) -> None: - self.project4 = self.create_project(name="baz", organization=self.organization) - self.release4 = Release.objects.create(version="v4", organization=self.organization) - self.release4.add_project(self.project4) - # Threshold for error count - ReleaseThreshold.objects.create( - threshold_type=ReleaseThresholdType.TOTAL_ERROR_COUNT, - trigger_type=0, # over - value=100, - window_in_seconds=100, - project=self.project4, - ) - # Threshold for new issue count - ReleaseThreshold.objects.create( - threshold_type=ReleaseThresholdType.NEW_ISSUE_COUNT, - trigger_type=0, # over - value=10, - window_in_seconds=100, - project=self.project4, - ) - # Threshold for crash free rate - ReleaseThreshold.objects.create( - threshold_type=ReleaseThresholdType.CRASH_FREE_SESSION_RATE, - trigger_type=1, # under - value=99, - window_in_seconds=3600, - project=self.project4, - ) - - now = datetime.now(UTC) - yesterday = datetime.now(UTC) - timedelta(hours=24) - - mock_is_error_count_healthy.return_value = True, 100 - mock_is_new_issue_count_healthy.return_value = True, 100 - mock_is_crash_free_rate_healthy.return_value = True, 100 - - self.get_success_response( - self.organization.slug, - start=yesterday, - end=now, - release=[self.release4.version], - ) - - assert mock_get_error_counts.call_count == 1 - assert mock_is_error_count_healthy.call_count == 1 - assert mock_get_new_issue_counts.call_count == 1 - assert mock_is_new_issue_count_healthy.call_count == 1 - assert mock_fetch_sessions_data.call_count == 1 - assert mock_is_crash_free_rate_healthy.call_count == 1 - - -class ReleaseThresholdStatusProjectAccessTest(APITestCase): - """Tests that release threshold status respects project-level access controls.""" - - endpoint = "sentry-api-0-organization-release-threshold-statuses" - method = "get" - - def setUp(self) -> None: - super().setUp() - # Create a separate owner so self.user doesn't get the owner role, - # which has global project access and would bypass team-based filtering. - owner = self.create_user("owner@example.com") - self.organization = self.create_organization(owner=owner) - self.organization.flags.allow_joinleave = False - self.organization.save() - - self.user = self.create_user(is_staff=False, is_superuser=False) - - self.team1 = self.create_team(organization=self.organization) - self.team2 = self.create_team(organization=self.organization) - - self.accessible_project = self.create_project( - name="accessible", organization=self.organization, teams=[self.team1] - ) - self.inaccessible_project = self.create_project( - name="inaccessible", organization=self.organization, teams=[self.team2] - ) - - # User only belongs to team1, giving access to accessible_project only - self.create_team_membership(team=self.team1, user=self.user) - - self.environment = Environment.objects.create( - organization_id=self.organization.id, name="production" - ) - - # Release attached to both projects - self.release = Release.objects.create(version="v1", organization=self.organization) - self.release.add_project(self.accessible_project) - self.release.add_project(self.inaccessible_project) - - ReleaseProjectEnvironment.objects.create( - release_id=self.release.id, - project_id=self.accessible_project.id, - environment_id=self.environment.id, - ) - ReleaseProjectEnvironment.objects.create( - release_id=self.release.id, - project_id=self.inaccessible_project.id, - environment_id=self.environment.id, - ) - - # Thresholds on both projects - ReleaseThreshold.objects.create( - threshold_type=ReleaseThresholdType.TOTAL_ERROR_COUNT, - trigger_type=1, - value=100, - window_in_seconds=100, - project=self.accessible_project, - environment=self.environment, - ) - ReleaseThreshold.objects.create( - threshold_type=ReleaseThresholdType.TOTAL_ERROR_COUNT, - trigger_type=1, - value=100, - window_in_seconds=100, - project=self.inaccessible_project, - environment=self.environment, - ) - - self.login_as(user=self.user) - - def test_inaccessible_project_slug_returns_no_data(self) -> None: - """Requesting only an inaccessible project slug must not return its threshold data.""" - now = datetime.now(UTC) - yesterday = now - timedelta(hours=24) - - response = self.get_response( - self.organization.slug, - start=yesterday, - end=now, - projectSlug=[self.inaccessible_project.slug], - ) - - # No valid projects → NoProjects is raised, so it should not be a 200 - assert response.status_code != 200 - - def test_mixed_slugs_only_returns_accessible_project(self) -> None: - """When both accessible and inaccessible slugs are requested, - only accessible project data is returned.""" - now = datetime.now(UTC) - yesterday = now - timedelta(hours=24) - - response = self.get_success_response( - self.organization.slug, - start=yesterday, - end=now, - projectSlug=[ - self.accessible_project.slug, - self.inaccessible_project.slug, - ], - ) - - assert len(response.data) == 1 - expected_key = f"{self.accessible_project.slug}-{self.release.version}" - assert expected_key in response.data - inaccessible_key = f"{self.inaccessible_project.slug}-{self.release.version}" - assert inaccessible_key not in response.data diff --git a/tests/sentry/api/endpoints/release_thresholds/test_release_thresholds_index.py b/tests/sentry/api/endpoints/release_thresholds/test_release_thresholds_index.py deleted file mode 100644 index fa7bcc7e0917..000000000000 --- a/tests/sentry/api/endpoints/release_thresholds/test_release_thresholds_index.py +++ /dev/null @@ -1,175 +0,0 @@ -from sentry.models.environment import Environment -from sentry.models.release_threshold.release_threshold import ReleaseThreshold -from sentry.testutils.cases import APITestCase - - -class ReleaseThresholdTest(APITestCase): - endpoint = "sentry-api-0-organization-release-thresholds" - method = "get" - - def setUp(self) -> None: - super().setUp() - self.user = self.create_user(is_staff=True, is_superuser=True) - self.login_as(user=self.user) - - self.canary_environment = Environment.objects.create( - organization_id=self.organization.id, name="canary" - ) - self.production_environment = Environment.objects.create( - organization_id=self.organization.id, name="production" - ) - - def test_get_invalid_project(self) -> None: - self.get_error_response(self.organization.slug, project="foo bar") - - def test_get_all_projects_slug_is_invalid(self) -> None: - response = self.get_error_response(self.organization.slug, project="$all") - - assert response.status_code == 400 - - def test_get_no_project(self) -> None: - self.get_error_response(self.organization.slug) - - def test_get_valid_project(self) -> None: - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - response = self.get_success_response(self.organization.slug, project=self.project.id) - assert len(response.data) == 1 - - created_threshold = response.data[0] - - assert created_threshold["threshold_type"] == "total_error_count" - assert created_threshold["trigger_type"] == "over" - assert created_threshold["value"] == 100 - assert created_threshold["window_in_seconds"] == 1800 - assert created_threshold["project"]["id"] == str(self.project.id) - assert created_threshold["project"]["slug"] == self.project.slug - assert created_threshold["project"]["name"] == self.project.name - assert created_threshold["environment"]["id"] == str(self.canary_environment.id) - assert created_threshold["environment"]["name"] == self.canary_environment.name - - def test_get_valid_project_slug(self) -> None: - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - response = self.get_success_response(self.organization.slug, project=self.project.slug) - - assert len(response.data) == 1 - assert response.data[0]["project"]["id"] == str(self.project.id) - - def test_get_invalid_environment(self) -> None: - self.get_error_response(self.organization.slug, environment="foo bar", project="-1") - - def test_get_valid_no_environment(self) -> None: - response = self.get_success_response(self.organization.slug, project="-1") - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - response = self.get_success_response(self.organization.slug, project=self.project.id) - assert len(response.data) == 1 - - created_threshold = response.data[0] - - assert created_threshold["threshold_type"] == "total_error_count" - assert created_threshold["trigger_type"] == "over" - assert created_threshold["value"] == 100 - assert created_threshold["window_in_seconds"] == 1800 - assert created_threshold["project"]["id"] == str(self.project.id) - assert created_threshold["project"]["slug"] == self.project.slug - assert created_threshold["project"]["name"] == self.project.name - assert created_threshold["environment"]["id"] == str(self.canary_environment.id) - assert created_threshold["environment"]["name"] == self.canary_environment.name - - def test_scoped_to_caller_accessible_projects(self) -> None: - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - other_org = self.create_organization() - other_project = self.create_project(organization=other_org) - other_environment = Environment.objects.create(organization_id=other_org.id, name="canary") - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=200, - window_in_seconds=1800, - project=other_project, - environment=other_environment, - ) - - # Closed membership so a teamless member has access to zero projects; - # otherwise `allow_joinleave` grants global project access and the - # `projects_list == []` path that triggered the bug is unreachable. - self.organization.flags.allow_joinleave = False - self.organization.save() - - member = self.create_user() - self.create_member(user=member, organization=self.organization, role="member", teams=[]) - self.login_as(user=member) - - response = self.get_success_response(self.organization.slug, project="-1") - assert response.data == [] - - def test_get_valid_with_environment(self) -> None: - response = self.get_success_response( - self.organization.slug, project="-1", environment="canary" - ) - - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=1, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.production_environment, - ) - - response = self.get_success_response( - self.organization.slug, project="-1", environment="canary" - ) - assert response.status_code == 200 - assert len(response.data) == 1 - - created_threshold = response.data[0] - - assert created_threshold["threshold_type"] == "total_error_count" - assert created_threshold["trigger_type"] == "over" - assert created_threshold["value"] == 100 - assert created_threshold["window_in_seconds"] == 1800 - assert created_threshold["project"]["id"] == str(self.project.id) - assert created_threshold["project"]["slug"] == self.project.slug - assert created_threshold["project"]["name"] == self.project.name - assert created_threshold["environment"]["id"] == str(self.canary_environment.id) - assert created_threshold["environment"]["name"] == self.canary_environment.name diff --git a/tests/sentry/api/endpoints/release_thresholds/utils/test_fetch_sessions_data.py b/tests/sentry/api/endpoints/release_thresholds/utils/test_fetch_sessions_data.py deleted file mode 100644 index c6ca6846494e..000000000000 --- a/tests/sentry/api/endpoints/release_thresholds/utils/test_fetch_sessions_data.py +++ /dev/null @@ -1,8 +0,0 @@ -# from sentry.api.endpoints.release_thresholds.utils import fetch_sessions_data -from sentry.testutils.cases import TestCase - - -class FetchSessionsdataTest(TestCase): - def test_constructs_query(self) -> None: - # TODO: - pass diff --git a/tests/sentry/api/endpoints/release_thresholds/utils/test_get_errors_counts_timeseries.py b/tests/sentry/api/endpoints/release_thresholds/utils/test_get_errors_counts_timeseries.py deleted file mode 100644 index 1fe1fee4a461..000000000000 --- a/tests/sentry/api/endpoints/release_thresholds/utils/test_get_errors_counts_timeseries.py +++ /dev/null @@ -1,220 +0,0 @@ -from datetime import timedelta -from typing import Any -from unittest import mock - -from django.utils import timezone -from snuba_sdk.column import Column -from snuba_sdk.conditions import Condition, Op - -from sentry.api.endpoints.release_thresholds.utils.get_errors_counts_timeseries import ( - _get_errors_counts_timeseries_eap, - _get_errors_counts_timeseries_snuba, -) -from sentry.testutils.cases import SnubaTestCase, TestCase -from sentry.testutils.helpers.datetime import before_now, freeze_time - - -class GetErrorCountTimeseriesSnubaTest(TestCase): - def setUp(self) -> None: - super().setUp() - self.org = self.create_organization() - self.project = self.create_project(name="foo", organization=self.org) - - @mock.patch( - "sentry.api.endpoints.release_thresholds.utils.get_errors_counts_timeseries.snuba.raw_snql_query" - ) - def test_errors_timeseries_snuba_fetch(self, mock_snql_query: mock.MagicMock) -> None: - mock_snql_query.return_value = {"data": []} - now = timezone.now() - _get_errors_counts_timeseries_snuba( - end=now, - organization_id=self.org.id, - project_id_list=[], - release_value_list=[], - start=now, - ) - - assert mock_snql_query.call_count == 1 - - @mock.patch( - "sentry.api.endpoints.release_thresholds.utils.get_errors_counts_timeseries.snuba.raw_snql_query" - ) - def test_errors_timeseries_snuba_fetch_called_with_env( - self, mock_snql_query: mock.MagicMock - ) -> None: - mock_snql_query.return_value = {"data": []} - now = timezone.now() - env_list = ["foo"] - _get_errors_counts_timeseries_snuba( - end=now, - organization_id=self.org.id, - project_id_list=[], - release_value_list=[], - start=now, - environments_list=env_list, - ) - - env_condition = Condition(Column("environment"), Op.IN, env_list) - call_conditions = mock_snql_query.call_args[1]["request"].query.where - assert env_condition in call_conditions - - -class TestEAPGetErrorsCountsTimeseries(TestCase, SnubaTestCase): - FROZEN_TIME = before_now(hours=24).replace(hour=6, minute=0, second=0) - - def _query_both( - self, - release_value_list: list[str], - project_id_list: list[int] | None = None, - environments_list: list[str] | None = None, - ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: - target_project_ids = project_id_list or [self.project.id] - start = self.FROZEN_TIME - timedelta(hours=1) - end = self.FROZEN_TIME + timedelta(hours=1) - - snuba_result = _get_errors_counts_timeseries_snuba( - end=end, - organization_id=self.organization.id, - project_id_list=target_project_ids, - release_value_list=release_value_list, - start=start, - environments_list=environments_list, - ) - eap_result = _get_errors_counts_timeseries_eap( - end=end, - organization_id=self.organization.id, - project_id_list=target_project_ids, - release_value_list=release_value_list, - start=start, - environments_list=environments_list, - ) - return snuba_result, eap_result - - @staticmethod - def _error_event_data(release: str, environment: str) -> dict[str, Any]: - return { - "type": "error", - "release": release, - "environment": environment, - "exception": [{"value": "BadError"}], - "tags": [["release", release], ["environment", environment]], - } - - @freeze_time(FROZEN_TIME) - def test_single_release_single_environment(self) -> None: - release = self.create_release(project=self.project, version="1.0.0") - ts = (self.FROZEN_TIME - timedelta(minutes=5)).timestamp() - self.store_events_to_snuba_and_eap( - "release-thresholds-group-a", - count=3, - timestamp=ts, - extra_event_data=self._error_event_data(release.version, "production"), - ) - - snuba_result, eap_result = self._query_both( - release_value_list=[release.version], environments_list=["production"] - ) - - assert eap_result == snuba_result - assert len(snuba_result) == 1 - assert snuba_result[0]["release"] == release.version - assert snuba_result[0]["environment"] == "production" - assert snuba_result[0]["count()"] == 3 - - @freeze_time(FROZEN_TIME) - def test_multiple_releases(self) -> None: - release_a = self.create_release(project=self.project, version="1.0.0") - release_b = self.create_release(project=self.project, version="2.0.0") - ts_a = (self.FROZEN_TIME - timedelta(minutes=10)).timestamp() - ts_b = (self.FROZEN_TIME - timedelta(minutes=5)).timestamp() - self.store_events_to_snuba_and_eap( - "release-thresholds-group-a", - count=2, - timestamp=ts_a, - extra_event_data=self._error_event_data(release_a.version, "production"), - ) - self.store_events_to_snuba_and_eap( - "release-thresholds-group-b", - count=4, - timestamp=ts_b, - extra_event_data=self._error_event_data(release_b.version, "production"), - ) - - snuba_result, eap_result = self._query_both( - release_value_list=[release_a.version, release_b.version], - environments_list=["production"], - ) - - assert eap_result == snuba_result - assert {row["release"] for row in snuba_result} == {release_a.version, release_b.version} - counts_by_release = {row["release"]: row["count()"] for row in snuba_result} - assert counts_by_release[release_a.version] == 2 - assert counts_by_release[release_b.version] == 4 - - @freeze_time(FROZEN_TIME) - def test_environment_filtering(self) -> None: - release = self.create_release(project=self.project, version="1.0.0") - ts = (self.FROZEN_TIME - timedelta(minutes=5)).timestamp() - self.store_events_to_snuba_and_eap( - "release-thresholds-group-a", - count=2, - timestamp=ts, - extra_event_data=self._error_event_data(release.version, "production"), - ) - self.store_events_to_snuba_and_eap( - "release-thresholds-group-b", - count=1, - timestamp=ts, - extra_event_data=self._error_event_data(release.version, "staging"), - ) - - snuba_result, eap_result = self._query_both( - release_value_list=[release.version], environments_list=["staging"] - ) - - assert eap_result == snuba_result - assert len(snuba_result) == 1 - assert snuba_result[0]["environment"] == "staging" - assert snuba_result[0]["count()"] == 1 - - @freeze_time(FROZEN_TIME) - def test_project_isolation(self) -> None: - other_project = self.create_project(organization=self.organization) - release = self.create_release(project=self.project, version="1.0.0") - ts = (self.FROZEN_TIME - timedelta(minutes=5)).timestamp() - - self.store_events_to_snuba_and_eap( - "release-thresholds-group-local", - count=2, - timestamp=ts, - project_id=self.project.id, - extra_event_data=self._error_event_data(release.version, "production"), - ) - self.store_events_to_snuba_and_eap( - "release-thresholds-group-other", - count=5, - timestamp=ts, - project_id=other_project.id, - extra_event_data=self._error_event_data(release.version, "production"), - ) - - snuba_result, eap_result = self._query_both( - release_value_list=[release.version], - project_id_list=[self.project.id], - environments_list=["production"], - ) - - assert eap_result == snuba_result - assert len(snuba_result) == 1 - assert snuba_result[0]["project_id"] == self.project.id - assert snuba_result[0]["count()"] == 2 - - @freeze_time(FROZEN_TIME) - def test_empty_results(self) -> None: - release = self.create_release(project=self.project, version="1.0.0") - snuba_result, eap_result = self._query_both( - release_value_list=[release.version], environments_list=["production"] - ) - - assert snuba_result == [] - assert eap_result == [] diff --git a/tests/sentry/api/endpoints/release_thresholds/utils/test_get_new_issue_counts.py b/tests/sentry/api/endpoints/release_thresholds/utils/test_get_new_issue_counts.py deleted file mode 100644 index dc0768033cdb..000000000000 --- a/tests/sentry/api/endpoints/release_thresholds/utils/test_get_new_issue_counts.py +++ /dev/null @@ -1,143 +0,0 @@ -from datetime import datetime, timedelta, timezone - -from sentry.api.endpoints.release_thresholds.types import EnrichedThreshold -from sentry.api.endpoints.release_thresholds.utils import get_new_issue_counts -from sentry.api.serializers import serialize -from sentry.models.environment import Environment -from sentry.models.group import Group -from sentry.models.groupenvironment import GroupEnvironment -from sentry.models.release import Release -from sentry.models.release_threshold.constants import ReleaseThresholdType, TriggerType -from sentry.models.releaseenvironment import ReleaseEnvironment -from sentry.models.releaseprojectenvironment import ReleaseProjectEnvironment -from sentry.testutils.cases import TestCase - - -class GetNewIssueCountTest(TestCase): - def setUp(self) -> None: - super().setUp() - self.org = self.create_organization() - self.project1 = self.create_project(name="foo", organization=self.org) - self.project2 = self.create_project(name="bar", organization=self.org) - - # 2 environments - self.null_environment = Environment.objects.create( - organization_id=self.organization.id, name="" - ) - self.canary_environment = Environment.objects.create( - organization_id=self.organization.id, name="canary" - ) - - # release created for proj1, and proj2 - self.release1 = Release.objects.create(version="v1", organization=self.organization) - # add_project get_or_creates a ReleaseProject - self.release1.add_project(self.project1) - self.release1.add_project(self.project2) - - # Attaches the release to a particular environment - # project superfluous/deprecated in ReleaseEnvironment - # release1 canary - ReleaseEnvironment.objects.create( - organization_id=self.organization.id, - release_id=self.release1.id, - environment_id=self.canary_environment.id, - ) - # Release Project Environments are required to query releases by project - # Even though both environment & project are here, this seems to just attach a release to a project - # You can have multiple ReleaseProjectEnvironment's per release (this attaches multiple projects to the release&env) - # release1 project1 canary - ReleaseProjectEnvironment.objects.create( - release_id=self.release1.id, - project_id=self.project1.id, - environment_id=self.canary_environment.id, - ) - - self.now = datetime.now(timezone.utc) - - self.group1_p1_r1 = Group.objects.create( - project=self.project1, - first_release=self.release1, - first_seen=self.now - timedelta(minutes=30), - ) - self.groupenvironment_g1_r1 = GroupEnvironment.objects.create( - group_id=self.group1_p1_r1.id, - environment_id=self.null_environment.id, - first_release=self.release1, - first_seen=self.now - timedelta(minutes=30), - ) - self.group2_p1_r1 = Group.objects.create( - project=self.project1, - first_release=self.release1, - first_seen=self.now - timedelta(minutes=30), - ) - self.groupenvironment_g2_r1 = GroupEnvironment.objects.create( - group_id=self.group2_p1_r1.id, - environment_id=self.canary_environment.id, - first_release=self.release1, - first_seen=self.now - timedelta(minutes=30), - ) - - def test_success_fetches_new_issue_counts(self) -> None: - # standard threshold - t1: EnrichedThreshold = { - "id": "1", - "project_id": self.project1.id, - "release": self.release1.version, - "start": self.now - timedelta(hours=1), - "end": self.now, - "date_added": self.now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_slug": self.project1.slug, - "threshold_type": ReleaseThresholdType.NEW_ISSUE_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 1, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - # threshold w/ environment - t2: EnrichedThreshold = { - "id": "2", - "project_id": self.project1.id, - "release": self.release1.version, - "start": self.now - timedelta(hours=1), - "end": self.now, - "date_added": self.now, - "environment": serialize(self.canary_environment), - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_slug": self.project1.slug, - "threshold_type": ReleaseThresholdType.NEW_ISSUE_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 1, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - # second threshold separate start/end - t3: EnrichedThreshold = { - "id": "3", - "project_id": self.project1.id, - "release": self.release1.version, - "start": self.now, - "end": self.now + timedelta(hours=1), - "date_added": self.now, - "environment": None, - "is_healthy": False, - "key": "", - "project": serialize(self.project1), - "project_slug": self.project1.slug, - "threshold_type": ReleaseThresholdType.NEW_ISSUE_COUNT_STR, - "trigger_type": TriggerType.OVER_STR, - "value": 1, - "window_in_seconds": 60, # NOTE: window_in_seconds only used to determine start/end. Not utilized in validation method - "metric_value": None, - } - thresholds: list[EnrichedThreshold] = [t1, t2, t3] - new_issue_counts = get_new_issue_counts(organization_id=self.org.id, thresholds=thresholds) - - assert new_issue_counts[str(t1["id"])] == 1 - assert new_issue_counts[str(t2["id"])] == 1 - assert new_issue_counts.get(str(t3["id"]), None) is None diff --git a/tests/sentry/seer/endpoints/test_organization_agent_token.py b/tests/sentry/seer/endpoints/test_organization_agent_token.py index 29b8aebf0b0d..316fc81a1270 100644 --- a/tests/sentry/seer/endpoints/test_organization_agent_token.py +++ b/tests/sentry/seer/endpoints/test_organization_agent_token.py @@ -1757,12 +1757,6 @@ def _query_params(self, endpoint: PublicGetEndpoint | PublicMutationEndpoint) -> } if endpoint.endpoint_name == "OrganizationProfilingFlamegraphEndpoint": return {"project": [self.project.id], "statsPeriod": "1h"} - if endpoint.endpoint_name == "ReleaseThresholdStatusIndexEndpoint": - now = timezone.now() - return { - "start": (now - timedelta(hours=1)).isoformat(), - "end": now.isoformat(), - } if endpoint.endpoint_name == "OrganizationSessionsEndpoint": return { "field": ["sum(session)"], From b530116533abc5cadd79093e80334b48bd6367f2 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:22:02 +0000 Subject: [PATCH 2/2] ref(releases): Remove experimental release threshold endpoints Remove the experimental release threshold create, list, update, and delete endpoints, which have no callers and no UI, and the unused /release-thresholds/ page route. Mark the public status endpoint deprecated. It is exported by @sentry/api, so removing it waits for that package's next major release. Refs ISWF-3793 Co-Authored-By: Athena Moghaddam <132939361+sentaur-athena@users.noreply.github.com> --- .../release_thresholds/release_threshold.py | 87 ----- .../release_threshold_details.py | 103 ------ .../release_threshold_index.py | 72 ---- .../release_threshold_status_index.py | 1 + src/sentry/api/urls.py | 22 -- .../api_pagination_allowlist_do_not_modify.py | 1 - .../models/release_threshold/constants.py | 34 -- src/sentry/web/urls.py | 5 - .../utils/api/knownSentryApiUrls.generated.ts | 3 - .../test_release_threshold.py | 237 ------------- .../test_release_threshold_details.py | 329 ------------------ .../test_release_thresholds_index.py | 175 ---------- 12 files changed, 1 insertion(+), 1068 deletions(-) delete mode 100644 src/sentry/api/endpoints/release_thresholds/release_threshold.py delete mode 100644 src/sentry/api/endpoints/release_thresholds/release_threshold_details.py delete mode 100644 src/sentry/api/endpoints/release_thresholds/release_threshold_index.py delete mode 100644 tests/sentry/api/endpoints/release_thresholds/test_release_threshold.py delete mode 100644 tests/sentry/api/endpoints/release_thresholds/test_release_threshold_details.py delete mode 100644 tests/sentry/api/endpoints/release_thresholds/test_release_thresholds_index.py diff --git a/src/sentry/api/endpoints/release_thresholds/release_threshold.py b/src/sentry/api/endpoints/release_thresholds/release_threshold.py deleted file mode 100644 index 6812711fbb36..000000000000 --- a/src/sentry/api/endpoints/release_thresholds/release_threshold.py +++ /dev/null @@ -1,87 +0,0 @@ -from typing import TypedDict - -from django.http import HttpResponse -from rest_framework import serializers -from rest_framework.request import Request -from rest_framework.response import Response - -from sentry.api.api_owners import ApiOwner -from sentry.api.api_publish_status import ApiPublishStatus -from sentry.api.base import cell_silo_endpoint -from sentry.api.bases.project import ProjectEndpoint, ProjectReleasePermission -from sentry.api.serializers import serialize -from sentry.api.serializers.rest_framework.environment import EnvironmentField -from sentry.models.project import Project -from sentry.models.release_threshold.constants import ( - THRESHOLD_TYPE_STR_TO_INT, - TRIGGER_TYPE_STRING_TO_INT, - ReleaseThresholdType, -) -from sentry.models.release_threshold.constants import TriggerType as ReleaseThresholdTriggerType -from sentry.models.release_threshold.release_threshold import ReleaseThreshold - - -class ReleaseThresholdPOSTData(TypedDict, total=False): - threshold_type: int - trigger_type: int - value: int - window_in_seconds: int - environment: object - - -class ReleaseThresholdPOSTSerializer(serializers.Serializer[ReleaseThresholdPOSTData]): - threshold_type = serializers.ChoiceField(choices=ReleaseThresholdType.as_str_choices()) - trigger_type = serializers.ChoiceField(choices=ReleaseThresholdTriggerType.as_str_choices()) - value = serializers.IntegerField(required=True, min_value=0) - window_in_seconds = serializers.IntegerField(required=True, min_value=0) - environment = EnvironmentField(required=False, allow_null=True) - - def validate_threshold_type(self, threshold_type: str) -> int: - if threshold_type not in THRESHOLD_TYPE_STR_TO_INT: - raise serializers.ValidationError("Invalid threshold type") - return THRESHOLD_TYPE_STR_TO_INT[threshold_type] - - def validate_trigger_type(self, trigger_type: str) -> int: - if trigger_type not in TRIGGER_TYPE_STRING_TO_INT: - raise serializers.ValidationError("Invalid trigger type") - return TRIGGER_TYPE_STRING_TO_INT[trigger_type] - - -@cell_silo_endpoint -class ReleaseThresholdEndpoint(ProjectEndpoint): - permission_classes = (ProjectReleasePermission,) - owner: ApiOwner = ApiOwner.REPLAY - publish_status = { - "GET": ApiPublishStatus.EXPERIMENTAL, - "POST": ApiPublishStatus.EXPERIMENTAL, - } - - def post(self, request: Request, project: Project) -> HttpResponse: - serializer = ReleaseThresholdPOSTSerializer( - data=request.data, - context={ - "organization": project.organization, - "access": request.access, - }, - ) - if not serializer.is_valid(): - return Response(serializer.errors, status=400) - result = serializer.validated_data - - release_threshold = ReleaseThreshold.objects.create( - threshold_type=result.get("threshold_type"), - trigger_type=result.get("trigger_type"), - value=result.get("value"), - window_in_seconds=result.get("window_in_seconds"), - project=project, - environment=result.get("environment"), - ) - return Response(serialize(release_threshold, request.user), status=201) - - def get(self, request: Request, project: Project) -> HttpResponse: - release_thresholds = ReleaseThreshold.objects.filter(project=project) - environment_name: str | None = request.GET.get("environment") - - if environment_name: - release_thresholds = release_thresholds.filter(environment__name=environment_name) - return Response(serialize(list(release_thresholds), request.user), status=200) diff --git a/src/sentry/api/endpoints/release_thresholds/release_threshold_details.py b/src/sentry/api/endpoints/release_thresholds/release_threshold_details.py deleted file mode 100644 index c2b1a595a8bf..000000000000 --- a/src/sentry/api/endpoints/release_thresholds/release_threshold_details.py +++ /dev/null @@ -1,103 +0,0 @@ -import logging -from typing import Any, TypedDict - -from django.http import HttpResponse -from rest_framework import serializers -from rest_framework.request import Request -from rest_framework.response import Response - -from sentry.api.api_owners import ApiOwner -from sentry.api.api_publish_status import ApiPublishStatus -from sentry.api.base import cell_silo_endpoint -from sentry.api.bases.project import ProjectEndpoint, ProjectReleasePermission -from sentry.api.exceptions import ResourceDoesNotExist -from sentry.api.serializers import serialize -from sentry.api.utils import to_valid_int_id -from sentry.models.project import Project -from sentry.models.release_threshold.constants import ( - THRESHOLD_TYPE_STR_TO_INT, - TRIGGER_TYPE_STRING_TO_INT, - ReleaseThresholdType, -) -from sentry.models.release_threshold.constants import TriggerType as ReleaseThresholdTriggerType -from sentry.models.release_threshold.release_threshold import ReleaseThreshold - - -class ReleaseThresholdPUTData(TypedDict): - threshold_type: int - trigger_type: int - value: int - window_in_seconds: int - - -logger = logging.getLogger("sentry.release_thresholds") - - -class ReleaseThresholdPUTSerializer(serializers.Serializer[ReleaseThresholdPUTData]): - threshold_type = serializers.ChoiceField(choices=ReleaseThresholdType.as_str_choices()) - trigger_type = serializers.ChoiceField(choices=ReleaseThresholdTriggerType.as_str_choices()) - value = serializers.IntegerField(required=True, min_value=0) - window_in_seconds = serializers.IntegerField(required=True, min_value=0) - - def validate_threshold_type(self, threshold_type: str) -> int: - if threshold_type not in THRESHOLD_TYPE_STR_TO_INT: - raise serializers.ValidationError("Invalid threshold type") - return THRESHOLD_TYPE_STR_TO_INT[threshold_type] - - def validate_trigger_type(self, trigger_type: str) -> int: - if trigger_type not in TRIGGER_TYPE_STRING_TO_INT: - raise serializers.ValidationError("Invalid trigger type") - return TRIGGER_TYPE_STRING_TO_INT[trigger_type] - - -@cell_silo_endpoint -class ReleaseThresholdDetailsEndpoint(ProjectEndpoint): - permission_classes = (ProjectReleasePermission,) - owner: ApiOwner = ApiOwner.REPLAY - publish_status = { - "DELETE": ApiPublishStatus.EXPERIMENTAL, - "GET": ApiPublishStatus.EXPERIMENTAL, - "PUT": ApiPublishStatus.EXPERIMENTAL, - } - - def convert_args( - self, - request: Request, - *args: Any, - **kwargs: Any, - ) -> tuple[tuple[Any, ...], dict[str, Any]]: - parsed_args, parsed_kwargs = super().convert_args(request, *args, **kwargs) - validated_id = to_valid_int_id( - "release_threshold", kwargs["release_threshold"], raise_404=True - ) - try: - parsed_kwargs["release_threshold"] = ReleaseThreshold.objects.get( - id=validated_id, - project=parsed_kwargs["project"], - ) - except ReleaseThreshold.DoesNotExist: - raise ResourceDoesNotExist - return parsed_args, parsed_kwargs - - def get( - self, request: Request, project: Project, release_threshold: ReleaseThreshold - ) -> HttpResponse: - return Response(serialize(release_threshold, request.user), status=200) - - def put( - self, request: Request, project: Project, release_threshold: ReleaseThreshold - ) -> HttpResponse: - serializer = ReleaseThresholdPUTSerializer(data=request.data) - - if not serializer.is_valid(): - return Response(serializer.errors, status=400) - - validated_data = serializer.validated_data - release_threshold.update(**validated_data) - return Response(serialize(release_threshold, request.user), status=200) - - def delete( - self, request: Request, project: Project, release_threshold: ReleaseThreshold - ) -> HttpResponse: - release_threshold.delete() - return Response(status=204) diff --git a/src/sentry/api/endpoints/release_thresholds/release_threshold_index.py b/src/sentry/api/endpoints/release_thresholds/release_threshold_index.py deleted file mode 100644 index b6d1827dd233..000000000000 --- a/src/sentry/api/endpoints/release_thresholds/release_threshold_index.py +++ /dev/null @@ -1,72 +0,0 @@ -from typing import TypedDict - -from django.db.models import Q -from django.http import HttpResponse -from rest_framework import serializers -from rest_framework.request import Request -from rest_framework.response import Response - -from sentry.api.api_owners import ApiOwner -from sentry.api.api_publish_status import ApiPublishStatus -from sentry.api.base import cell_silo_endpoint -from sentry.api.bases.organization import OrganizationEndpoint -from sentry.api.helpers.projects import ProjectIdOrSlug, ProjectIdOrSlugField -from sentry.api.paginator import OffsetPaginator -from sentry.api.serializers import serialize -from sentry.constants import ALL_ACCESS_PROJECTS_SLUG -from sentry.models.organization import Organization -from sentry.models.release_threshold.release_threshold import ReleaseThreshold - - -class ReleaseThresholdIndexGETData(TypedDict, total=False): - environment: list[str] - project: list[ProjectIdOrSlug] - - -class ReleaseThresholdIndexGETValidator(serializers.Serializer[ReleaseThresholdIndexGETData]): - environment = serializers.ListField( - required=False, allow_empty=True, child=serializers.CharField() - ) - project = serializers.ListField(required=True, allow_empty=False, child=ProjectIdOrSlugField()) - - def validate_project(self, value: list[ProjectIdOrSlug]) -> list[ProjectIdOrSlug]: - if ALL_ACCESS_PROJECTS_SLUG in value: - raise serializers.ValidationError("Invalid project") - return value - - -@cell_silo_endpoint -class ReleaseThresholdIndexEndpoint(OrganizationEndpoint): - owner: ApiOwner = ApiOwner.REPLAY - publish_status = { - "GET": ApiPublishStatus.EXPERIMENTAL, - } - - def get(self, request: Request, organization: Organization) -> HttpResponse: - validator = ReleaseThresholdIndexGETValidator( - data=self.get_query_params_without_empty_project_params(request), - ) - if not validator.is_valid(): - return Response(validator.errors, status=400) - - environments_list = self.get_environments(request, organization) - projects_list = self.get_projects(request, organization) - - # `projects_list` is already organization-scoped by `get_projects`, so - # `project__in=projects_list` both narrows to the caller's projects and - # prevents cross-tenant reads. An empty list yields zero rows. - release_query = Q(project__in=projects_list) - if environments_list: - release_query &= Q( - environment__in=environments_list, - ) - - queryset = ReleaseThreshold.objects.filter(release_query) - - return self.paginate( - request=request, - queryset=queryset, - order_by="date_added", - paginator_cls=OffsetPaginator, - on_results=lambda x: serialize(x, request.user), - ) diff --git a/src/sentry/api/endpoints/release_thresholds/release_threshold_status_index.py b/src/sentry/api/endpoints/release_thresholds/release_threshold_status_index.py index 32e2a6230da6..68ef56c34845 100644 --- a/src/sentry/api/endpoints/release_thresholds/release_threshold_status_index.py +++ b/src/sentry/api/endpoints/release_thresholds/release_threshold_status_index.py @@ -121,6 +121,7 @@ class ReleaseThresholdStatusIndexEndpoint(OrganizationReleasesBaseEndpoint): @extend_schema( operation_id="listOrganizationReleaseThresholdStatuses", summary="Retrieve Statuses of Release Thresholds (Alpha)", + deprecated=True, parameters=[GlobalParams.ORG_ID_OR_SLUG, ReleaseThresholdStatusIndexSerializer], request=None, responses={ diff --git a/src/sentry/api/urls.py b/src/sentry/api/urls.py index 90ebbfb16a19..a95797cb1e07 100644 --- a/src/sentry/api/urls.py +++ b/src/sentry/api/urls.py @@ -80,13 +80,6 @@ ) from sentry.api.endpoints.project_overview import ProjectOverviewEndpoint from sentry.api.endpoints.project_statistical_detectors import ProjectStatisticalDetectors -from sentry.api.endpoints.release_thresholds.release_threshold import ReleaseThresholdEndpoint -from sentry.api.endpoints.release_thresholds.release_threshold_details import ( - ReleaseThresholdDetailsEndpoint, -) -from sentry.api.endpoints.release_thresholds.release_threshold_index import ( - ReleaseThresholdIndexEndpoint, -) from sentry.api.endpoints.release_thresholds.release_threshold_status_index import ( ReleaseThresholdStatusIndexEndpoint, ) @@ -2345,11 +2338,6 @@ def create_group_urls( OrganizationReleasesEndpoint.as_view(), name="sentry-api-0-organization-releases", ), - re_path( - r"^(?P[^/]+)/release-thresholds/$", - ReleaseThresholdIndexEndpoint.as_view(), - name="sentry-api-0-organization-release-thresholds", - ), # TODO: also integrate release threshold status into the releases response? re_path( r"^(?P[^/]+)/release-threshold-statuses/$", @@ -3219,16 +3207,6 @@ def create_group_urls( ProjectReleasesEndpoint.as_view(), name="sentry-api-0-project-releases", ), - re_path( - r"^(?P[^/]+)/(?P[^/]+)/release-thresholds/$", - ReleaseThresholdEndpoint.as_view(), - name="sentry-api-0-project-release-thresholds", - ), - re_path( - r"^(?P[^/]+)/(?P[^/]+)/release-thresholds/(?P[^/]+)/$", - ReleaseThresholdDetailsEndpoint.as_view(), - name="sentry-api-0-project-release-thresholds-details", - ), re_path( r"^(?P[^/]+)/(?P[^/]+)/commits/$", ProjectCommitsEndpoint.as_view(), diff --git a/src/sentry/conf/api_pagination_allowlist_do_not_modify.py b/src/sentry/conf/api_pagination_allowlist_do_not_modify.py index 16b86b845ad7..066adff85065 100644 --- a/src/sentry/conf/api_pagination_allowlist_do_not_modify.py +++ b/src/sentry/conf/api_pagination_allowlist_do_not_modify.py @@ -77,7 +77,6 @@ "ProjectSymbolSourcesEndpoint", "ProjectTagsEndpoint", "ProjectUsersEndpoint", - "ReleaseThresholdEndpoint", "SentryAppInstallationServiceHookProjectsEndpoint", "SentryAppRequestsEndpoint", "SentryAppWebhookRequestsEndpoint", diff --git a/src/sentry/models/release_threshold/constants.py b/src/sentry/models/release_threshold/constants.py index f9cb8402b7f9..42caa23497f6 100644 --- a/src/sentry/models/release_threshold/constants.py +++ b/src/sentry/models/release_threshold/constants.py @@ -42,18 +42,6 @@ def as_choices(cls) -> tuple[tuple[str, int], ...]: (cls.CRASH_FREE_USER_RATE_STR, cls.CRASH_FREE_USER_RATE), ) - @classmethod - def as_str_choices(cls) -> tuple[tuple[str, str], ...]: - return ( - (cls.TOTAL_ERROR_COUNT_STR, cls.TOTAL_ERROR_COUNT_STR), - (cls.NEW_ISSUE_COUNT_STR, cls.NEW_ISSUE_COUNT_STR), - (cls.UNHANDLED_ISSUE_COUNT_STR, cls.UNHANDLED_ISSUE_COUNT_STR), - (cls.REGRESSED_ISSUE_COUNT_STR, cls.REGRESSED_ISSUE_COUNT_STR), - (cls.FAILURE_RATE_STR, cls.FAILURE_RATE_STR), - (cls.CRASH_FREE_SESSION_RATE_STR, cls.CRASH_FREE_SESSION_RATE_STR), - (cls.CRASH_FREE_USER_RATE_STR, cls.CRASH_FREE_USER_RATE_STR), - ) - class TriggerType: OVER = 0 @@ -69,13 +57,6 @@ def as_choices(cls) -> tuple[tuple[str, int], ...]: # choices for model column (cls.UNDER_STR, cls.UNDER), ) - @classmethod - def as_str_choices(cls) -> tuple[tuple[str, str], ...]: # choices for serializer - return ( - (cls.OVER_STR, cls.OVER_STR), - (cls.UNDER_STR, cls.UNDER_STR), - ) - THRESHOLD_TYPE_INT_TO_STR: dict[int, ThresholdTypeName] = { ReleaseThresholdType.TOTAL_ERROR_COUNT: ReleaseThresholdType.TOTAL_ERROR_COUNT_STR, @@ -87,22 +68,7 @@ def as_str_choices(cls) -> tuple[tuple[str, str], ...]: # choices for serialize ReleaseThresholdType.CRASH_FREE_USER_RATE: ReleaseThresholdType.CRASH_FREE_USER_RATE_STR, } -THRESHOLD_TYPE_STR_TO_INT = { - ReleaseThresholdType.TOTAL_ERROR_COUNT_STR: ReleaseThresholdType.TOTAL_ERROR_COUNT, - ReleaseThresholdType.NEW_ISSUE_COUNT_STR: ReleaseThresholdType.NEW_ISSUE_COUNT, - ReleaseThresholdType.UNHANDLED_ISSUE_COUNT_STR: ReleaseThresholdType.UNHANDLED_ISSUE_COUNT, - ReleaseThresholdType.REGRESSED_ISSUE_COUNT_STR: ReleaseThresholdType.REGRESSED_ISSUE_COUNT, - ReleaseThresholdType.FAILURE_RATE_STR: ReleaseThresholdType.FAILURE_RATE, - ReleaseThresholdType.CRASH_FREE_SESSION_RATE_STR: ReleaseThresholdType.CRASH_FREE_SESSION_RATE, - ReleaseThresholdType.CRASH_FREE_USER_RATE_STR: ReleaseThresholdType.CRASH_FREE_USER_RATE, -} - TRIGGER_TYPE_INT_TO_STR: dict[int, TriggerTypeName] = { TriggerType.OVER: TriggerType.OVER_STR, TriggerType.UNDER: TriggerType.UNDER_STR, } - -TRIGGER_TYPE_STRING_TO_INT = { - TriggerType.OVER_STR: TriggerType.OVER, - TriggerType.UNDER_STR: TriggerType.UNDER, -} diff --git a/src/sentry/web/urls.py b/src/sentry/web/urls.py index 58b0ae207292..f2bff02c1074 100644 --- a/src/sentry/web/urls.py +++ b/src/sentry/web/urls.py @@ -991,11 +991,6 @@ react_page_view, name="releases", ), - re_path( - r"^release-thresholds/", - react_page_view, - name="release-thresholds", - ), # User Feedback re_path( r"^user-feedback/", diff --git a/static/app/utils/api/knownSentryApiUrls.generated.ts b/static/app/utils/api/knownSentryApiUrls.generated.ts index 2899404aaeb9..366c9718770b 100644 --- a/static/app/utils/api/knownSentryApiUrls.generated.ts +++ b/static/app/utils/api/knownSentryApiUrls.generated.ts @@ -337,7 +337,6 @@ export type KnownSentryApiUrls = | '/organizations/$organizationIdOrSlug/recent-searches/' | '/organizations/$organizationIdOrSlug/relay_usage/' | '/organizations/$organizationIdOrSlug/release-threshold-statuses/' - | '/organizations/$organizationIdOrSlug/release-thresholds/' | '/organizations/$organizationIdOrSlug/releases/' | '/organizations/$organizationIdOrSlug/releases/$version/' | '/organizations/$organizationIdOrSlug/releases/$version/assemble/' @@ -530,8 +529,6 @@ export type KnownSentryApiUrls = | '/projects/$organizationIdOrSlug/$projectIdOrSlug/profiling/profiles/$profileId/' | '/projects/$organizationIdOrSlug/$projectIdOrSlug/profiling/raw_chunks/$profilerId/$chunkId/' | '/projects/$organizationIdOrSlug/$projectIdOrSlug/profiling/raw_profiles/$profileId/' - | '/projects/$organizationIdOrSlug/$projectIdOrSlug/release-thresholds/' - | '/projects/$organizationIdOrSlug/$projectIdOrSlug/release-thresholds/$releaseThreshold/' | '/projects/$organizationIdOrSlug/$projectIdOrSlug/releases/' | '/projects/$organizationIdOrSlug/$projectIdOrSlug/releases/$version/' | '/projects/$organizationIdOrSlug/$projectIdOrSlug/releases/$version/commits/' diff --git a/tests/sentry/api/endpoints/release_thresholds/test_release_threshold.py b/tests/sentry/api/endpoints/release_thresholds/test_release_threshold.py deleted file mode 100644 index 08798bd4f00d..000000000000 --- a/tests/sentry/api/endpoints/release_thresholds/test_release_threshold.py +++ /dev/null @@ -1,237 +0,0 @@ -from django.urls import reverse - -from sentry.models.environment import Environment -from sentry.models.release_threshold.release_threshold import ReleaseThreshold -from sentry.testutils.cases import APITestCase - - -class ReleaseThresholdTest(APITestCase): - def setUp(self) -> None: - super().setUp() - self.user = self.create_user(is_staff=True, is_superuser=True) - - self.canary_environment = Environment.objects.create( - organization_id=self.organization.id, name="canary" - ) - self.production_environment = Environment.objects.create( - organization_id=self.organization.id, name="production" - ) - self.login_as(user=self.user) - - self.url = reverse( - "sentry-api-0-project-release-thresholds", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - }, - ) - - def test_post_missing_params(self) -> None: - response = self.client.post( - self.url, - data={ - "threshold_type": "total_error_count", - "trigger_type": "over", - # value is missing - "window_in_seconds": 1800, - "environment": "canary", - }, - ) - - assert response.status_code == 400 - assert response.data == {"value": ["This field is required."]} - - def test_post_invalid_threshold_type(self) -> None: - response = self.client.post( - self.url, - data={ - "threshold_type": "indiana_jones_and_the_temple_of_doom", - "trigger_type": "over", - "value": 100, - "window_in_seconds": 1800, - "environment": "canary", - }, - ) - - assert response.status_code == 400 - assert response.data["threshold_type"][0].code == "invalid_choice" - - def test_post_invalid_trigger_type(self) -> None: - response = self.client.post( - self.url, - data={ - "threshold_type": "total_error_count", - "trigger_type": "short_round", - "value": 100, - "window_in_seconds": 1800, - "environment": "production", - }, - ) - - assert response.status_code == 400 - assert response.data["trigger_type"][0].code == "invalid_choice" - - def test_post_invalid_project(self) -> None: - url_with_invalid_project = reverse( - "sentry-api-0-project-release-thresholds", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": "Why did it have to be snakes?", - }, - ) - response = self.client.post( - url_with_invalid_project, - data={ - "threshold_type": "total_error_count", - "trigger_type": "over", - "value": 100, - "window_in_seconds": 1800, - "environment": "production", - }, - ) - assert response.status_code == 404 - - def test_post_invalid_environment(self) -> None: - response = self.client.post( - self.url, - data={ - "threshold_type": "total_error_count", - "trigger_type": "over", - "value": 100, - "window_in_seconds": 1800, - "environment": "Sentry belongs in a museum.", - }, - ) - assert response.status_code == 400 - assert response.data["environment"][0].code == "invalid" - - def test_post_valid_no_environment(self) -> None: - response = self.client.post( - self.url, - data={ - "threshold_type": "total_error_count", - "trigger_type": "over", - "value": 100, - "window_in_seconds": 1800, - }, - ) - assert response.status_code == 201 - data = response.data - assert data["threshold_type"] == "total_error_count" - assert data["trigger_type"] == "over" - assert data["value"] == 100 - assert data["window_in_seconds"] == 1800 - assert data["project"]["id"] == str(self.project.id) - assert data["project"]["slug"] == self.project.slug - assert data["project"]["name"] == self.project.name - assert data["environment"] is None - assert data["date_added"] is not None - - def test_post_valid(self) -> None: - response = self.client.post( - self.url, - data={ - "threshold_type": "total_error_count", - "trigger_type": "over", - "value": 100, - "window_in_seconds": 1800, - "environment": "canary", - }, - ) - - assert response.status_code == 201 - data = response.data - assert data["threshold_type"] == "total_error_count" - assert data["trigger_type"] == "over" - assert data["value"] == 100 - assert data["window_in_seconds"] == 1800 - assert data["project"]["id"] == str(self.project.id) - assert data["project"]["slug"] == self.project.slug - assert data["project"]["name"] == self.project.name - assert data["environment"]["id"] == str(self.canary_environment.id) - assert data["environment"]["name"] == self.canary_environment.name - assert data["date_added"] is not None - - def test_get_invalid_project(self) -> None: - url_with_invalid_project = reverse( - "sentry-api-0-project-release-thresholds", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": "Why did it have to be snakes?", - }, - ) - response = self.client.get(url_with_invalid_project, data={"environment": "canary"}) - assert response.status_code == 404 - - def test_get_invalid_environment(self) -> None: - response = self.client.get(self.url, data={"environment": "The Hovitos are near"}) - assert response.status_code == 200 - assert len(response.data) == 0 - - def test_get_valid_no_environment(self) -> None: - response = self.client.get(self.url) - assert response.status_code == 200 - assert len(response.data) == 0 - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - response = self.client.get(self.url) - assert response.status_code == 200 - assert len(response.data) == 1 - - created_threshold = response.data[0] - - assert created_threshold["threshold_type"] == "total_error_count" - assert created_threshold["trigger_type"] == "over" - assert created_threshold["value"] == 100 - assert created_threshold["window_in_seconds"] == 1800 - assert created_threshold["project"]["id"] == str(self.project.id) - assert created_threshold["project"]["slug"] == self.project.slug - assert created_threshold["project"]["name"] == self.project.name - assert created_threshold["environment"]["id"] == str(self.canary_environment.id) - assert created_threshold["environment"]["name"] == self.canary_environment.name - - def test_get_valid_with_environment(self) -> None: - response = self.client.get(self.url, data={"environment": "canary"}) - assert response.status_code == 200 - assert len(response.data) == 0 - - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=1, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.production_environment, - ) - - response = self.client.get(self.url, data={"environment": "canary"}) - assert response.status_code == 200 - assert len(response.data) == 1 - - created_threshold = response.data[0] - - assert created_threshold["threshold_type"] == "total_error_count" - assert created_threshold["trigger_type"] == "over" - assert created_threshold["value"] == 100 - assert created_threshold["window_in_seconds"] == 1800 - assert created_threshold["project"]["id"] == str(self.project.id) - assert created_threshold["project"]["slug"] == self.project.slug - assert created_threshold["project"]["name"] == self.project.name - assert created_threshold["environment"]["id"] == str(self.canary_environment.id) - assert created_threshold["environment"]["name"] == self.canary_environment.name diff --git a/tests/sentry/api/endpoints/release_thresholds/test_release_threshold_details.py b/tests/sentry/api/endpoints/release_thresholds/test_release_threshold_details.py deleted file mode 100644 index 2147cfb6cf5f..000000000000 --- a/tests/sentry/api/endpoints/release_thresholds/test_release_threshold_details.py +++ /dev/null @@ -1,329 +0,0 @@ -from django.urls import reverse - -from sentry.models.environment import Environment -from sentry.models.release_threshold.constants import THRESHOLD_TYPE_INT_TO_STR -from sentry.models.release_threshold.release_threshold import ReleaseThreshold -from sentry.testutils.cases import APITestCase - - -class ReleaseThresholdDetailsGETTest(APITestCase): - def setUp(self) -> None: - super().setUp() - self.user = self.create_user(is_staff=True, is_superuser=True) - - self.canary_environment = Environment.objects.create( - organization_id=self.organization.id, name="canary" - ) - self.production_environment = Environment.objects.create( - organization_id=self.organization.id, name="production" - ) - self.login_as(user=self.user) - - self.basic_threshold = ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - def test_invalid_threshold_id(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": 123, - }, - ) - response = self.client.get(url) - - assert response.status_code == 404 - - def test_invalid_project(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": "kingdom_of_the_crystal_skull", - "release_threshold": self.basic_threshold.id, - }, - ) - response = self.client.get(url) - - assert response.status_code == 404 - - def test_valid(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": self.basic_threshold.id, - }, - ) - response = self.client.get(url) - - assert response.status_code == 200 - assert response.data["id"] == str(self.basic_threshold.id) - assert response.data["threshold_type"] == "total_error_count" - assert response.data["trigger_type"] == "over" - assert response.data["value"] == 100 - assert response.data["window_in_seconds"] == 1800 - - -class ReleaseThresholdDetailsDELETETest(APITestCase): - def setUp(self) -> None: - super().setUp() - self.user = self.create_user(is_staff=True, is_superuser=True) - - self.canary_environment = Environment.objects.create( - organization_id=self.organization.id, name="canary" - ) - self.production_environment = Environment.objects.create( - organization_id=self.organization.id, name="production" - ) - self.login_as(user=self.user) - - self.basic_threshold = ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - def test_invalid_threshold_id(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": 123, - }, - ) - response = self.client.delete(url) - - assert response.status_code == 404 - - def test_invalid_project(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": "kingdom_of_the_crystal_skull", - "release_threshold": self.basic_threshold.id, - }, - ) - response = self.client.delete(url) - - assert response.status_code == 404 - - def test_valid(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": self.basic_threshold.id, - }, - ) - response = self.client.delete(url) - - assert response.status_code == 204 - - -class ReleaseThresholdDetailsPUTTest(APITestCase): - def setUp(self) -> None: - super().setUp() - self.user = self.create_user(is_staff=True, is_superuser=True) - - self.canary_environment = Environment.objects.create( - organization_id=self.organization.id, name="canary" - ) - self.production_environment = Environment.objects.create( - organization_id=self.organization.id, name="production" - ) - self.login_as(user=self.user) - - self.basic_threshold = ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - def test_invalid_threshold_id(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": 123, - }, - ) - response = self.client.put(url) - - assert response.status_code == 404 - - def test_invalid_missing_data(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": self.basic_threshold.id, - }, - ) - assert self.basic_threshold.environment is not None - data = { - "project": self.basic_threshold.project.id, - "environment": self.basic_threshold.environment.name, - "id": self.basic_threshold.id, - } - response = self.client.put(url, data) - assert response.status_code == 400 - - def test_invalid_trigger_type(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": self.basic_threshold.id, - }, - ) - assert self.basic_threshold.environment is not None - data = { - "project": self.basic_threshold.project.id, - "environment": self.basic_threshold.environment.name, - "id": self.basic_threshold.id, - "trigger_type": "foobar", - "threshold_type": THRESHOLD_TYPE_INT_TO_STR[self.basic_threshold.threshold_type], - "value": 50, - "window_in_seconds": 120, - } - response = self.client.put(url, data) - assert response.status_code == 400 - - def test_invalid_threshold_type(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": self.basic_threshold.id, - }, - ) - assert self.basic_threshold.environment is not None - data = { - "project": self.basic_threshold.project.id, - "environment": self.basic_threshold.environment.name, - "id": self.basic_threshold.id, - "trigger_type": "over", - "threshold_type": "foobar", - "value": 50, - "window_in_seconds": 120, - } - response = self.client.put(url, data) - assert response.status_code == 400 - - def test_invalid_window(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": self.basic_threshold.id, - }, - ) - assert self.basic_threshold.environment is not None - data = { - "project": self.basic_threshold.project.id, - "environment": self.basic_threshold.environment.name, - "id": self.basic_threshold.id, - "trigger_type": "over", - "threshold_type": THRESHOLD_TYPE_INT_TO_STR[self.basic_threshold.threshold_type], - "value": 50, - "window_in_seconds": -120, - } - response = self.client.put(url, data) - assert response.status_code == 400 - - def test_invalid_project(self) -> None: - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": "kingdom_of_the_crystal_skull", - "release_threshold": self.basic_threshold.id, - }, - ) - response = self.client.put(url) - - assert response.status_code == 404 - - def test_valid(self) -> None: - assert self.basic_threshold.environment is not None - updated_data = { - "project": self.basic_threshold.project.id, - "environment": self.basic_threshold.environment.name, - "date_added": self.basic_threshold.date_added, - "id": self.basic_threshold.id, - "trigger_type": "under", - "threshold_type": THRESHOLD_TYPE_INT_TO_STR[self.basic_threshold.threshold_type], - "value": 50, - "window_in_seconds": 120, - } - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": self.basic_threshold.id, - }, - ) - response = self.client.put(url, data=updated_data) - - assert response.status_code == 200 - assert response.data["id"] == str(self.basic_threshold.id) - assert response.data["threshold_type"] == "total_error_count" - assert response.data["trigger_type"] == updated_data["trigger_type"] - assert response.data["value"] == updated_data["value"] - assert response.data["window_in_seconds"] == updated_data["window_in_seconds"] - assert response.data["environment"]["name"] == "canary" - - def test_valid_with_extra_data(self) -> None: - updated_data = { - "project": self.basic_threshold.project.id, - "environment": "foobar", - "date_added": self.basic_threshold.date_added, - "id": self.basic_threshold.id, - "trigger_type": "under", - "threshold_type": THRESHOLD_TYPE_INT_TO_STR[self.basic_threshold.threshold_type], - "value": 50, - "window_in_seconds": 120, - "foo": "bar", - "biz": "baz", - } - url = reverse( - "sentry-api-0-project-release-thresholds-details", - kwargs={ - "organization_id_or_slug": self.organization.slug, - "project_id_or_slug": self.project.slug, - "release_threshold": self.basic_threshold.id, - }, - ) - response = self.client.put(url, data=updated_data) - - assert response.status_code == 200 - assert response.data["id"] == str(self.basic_threshold.id) - assert response.data["threshold_type"] == "total_error_count" - assert response.data["trigger_type"] == updated_data["trigger_type"] - assert response.data["value"] == updated_data["value"] - assert response.data["window_in_seconds"] == updated_data["window_in_seconds"] - assert response.data["environment"]["name"] == "canary" diff --git a/tests/sentry/api/endpoints/release_thresholds/test_release_thresholds_index.py b/tests/sentry/api/endpoints/release_thresholds/test_release_thresholds_index.py deleted file mode 100644 index fa7bcc7e0917..000000000000 --- a/tests/sentry/api/endpoints/release_thresholds/test_release_thresholds_index.py +++ /dev/null @@ -1,175 +0,0 @@ -from sentry.models.environment import Environment -from sentry.models.release_threshold.release_threshold import ReleaseThreshold -from sentry.testutils.cases import APITestCase - - -class ReleaseThresholdTest(APITestCase): - endpoint = "sentry-api-0-organization-release-thresholds" - method = "get" - - def setUp(self) -> None: - super().setUp() - self.user = self.create_user(is_staff=True, is_superuser=True) - self.login_as(user=self.user) - - self.canary_environment = Environment.objects.create( - organization_id=self.organization.id, name="canary" - ) - self.production_environment = Environment.objects.create( - organization_id=self.organization.id, name="production" - ) - - def test_get_invalid_project(self) -> None: - self.get_error_response(self.organization.slug, project="foo bar") - - def test_get_all_projects_slug_is_invalid(self) -> None: - response = self.get_error_response(self.organization.slug, project="$all") - - assert response.status_code == 400 - - def test_get_no_project(self) -> None: - self.get_error_response(self.organization.slug) - - def test_get_valid_project(self) -> None: - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - response = self.get_success_response(self.organization.slug, project=self.project.id) - assert len(response.data) == 1 - - created_threshold = response.data[0] - - assert created_threshold["threshold_type"] == "total_error_count" - assert created_threshold["trigger_type"] == "over" - assert created_threshold["value"] == 100 - assert created_threshold["window_in_seconds"] == 1800 - assert created_threshold["project"]["id"] == str(self.project.id) - assert created_threshold["project"]["slug"] == self.project.slug - assert created_threshold["project"]["name"] == self.project.name - assert created_threshold["environment"]["id"] == str(self.canary_environment.id) - assert created_threshold["environment"]["name"] == self.canary_environment.name - - def test_get_valid_project_slug(self) -> None: - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - response = self.get_success_response(self.organization.slug, project=self.project.slug) - - assert len(response.data) == 1 - assert response.data[0]["project"]["id"] == str(self.project.id) - - def test_get_invalid_environment(self) -> None: - self.get_error_response(self.organization.slug, environment="foo bar", project="-1") - - def test_get_valid_no_environment(self) -> None: - response = self.get_success_response(self.organization.slug, project="-1") - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - response = self.get_success_response(self.organization.slug, project=self.project.id) - assert len(response.data) == 1 - - created_threshold = response.data[0] - - assert created_threshold["threshold_type"] == "total_error_count" - assert created_threshold["trigger_type"] == "over" - assert created_threshold["value"] == 100 - assert created_threshold["window_in_seconds"] == 1800 - assert created_threshold["project"]["id"] == str(self.project.id) - assert created_threshold["project"]["slug"] == self.project.slug - assert created_threshold["project"]["name"] == self.project.name - assert created_threshold["environment"]["id"] == str(self.canary_environment.id) - assert created_threshold["environment"]["name"] == self.canary_environment.name - - def test_scoped_to_caller_accessible_projects(self) -> None: - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - other_org = self.create_organization() - other_project = self.create_project(organization=other_org) - other_environment = Environment.objects.create(organization_id=other_org.id, name="canary") - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=200, - window_in_seconds=1800, - project=other_project, - environment=other_environment, - ) - - # Closed membership so a teamless member has access to zero projects; - # otherwise `allow_joinleave` grants global project access and the - # `projects_list == []` path that triggered the bug is unreachable. - self.organization.flags.allow_joinleave = False - self.organization.save() - - member = self.create_user() - self.create_member(user=member, organization=self.organization, role="member", teams=[]) - self.login_as(user=member) - - response = self.get_success_response(self.organization.slug, project="-1") - assert response.data == [] - - def test_get_valid_with_environment(self) -> None: - response = self.get_success_response( - self.organization.slug, project="-1", environment="canary" - ) - - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=0, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.canary_environment, - ) - - ReleaseThreshold.objects.create( - threshold_type=0, - trigger_type=1, - value=100, - window_in_seconds=1800, - project=self.project, - environment=self.production_environment, - ) - - response = self.get_success_response( - self.organization.slug, project="-1", environment="canary" - ) - assert response.status_code == 200 - assert len(response.data) == 1 - - created_threshold = response.data[0] - - assert created_threshold["threshold_type"] == "total_error_count" - assert created_threshold["trigger_type"] == "over" - assert created_threshold["value"] == 100 - assert created_threshold["window_in_seconds"] == 1800 - assert created_threshold["project"]["id"] == str(self.project.id) - assert created_threshold["project"]["slug"] == self.project.slug - assert created_threshold["project"]["name"] == self.project.name - assert created_threshold["environment"]["id"] == str(self.canary_environment.id) - assert created_threshold["environment"]["name"] == self.canary_environment.name