Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(crons): Add stronger typing to error responses #70709

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/sentry/api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -651,6 +651,9 @@
from ..monitors.endpoints.organization_monitor_processing_errors_index import (
OrganizationMonitorProcessingErrorsIndexEndpoint,
)
from ..monitors.endpoints.project_processing_errors_details import (
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Heads up @wedamija looks like sometimes your editor is wanting to do parent relative imports

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It just copies other patterns it sees, so since it sees relative imports it does dumb stuff like this

ProjectProcessingErrorsDetailsEndpoint,
)

# issues endpoints are available both top level (by numerical ID) as well as coupled
# to the organization (and queryable via short ID)
Expand Down Expand Up @@ -2759,6 +2762,11 @@ def create_group_urls(name_prefix: str) -> list[URLPattern | URLResolver]:
ProjectMonitorEnvironmentDetailsEndpoint.as_view(),
name="sentry-api-0-project-monitor-environment-details",
),
re_path(
r"^(?P<organization_slug>[^\/]+)/(?P<project_id_or_slug>[^\/]+)/processing-errors/(?P<uuid>[^\/]+)/$",
ProjectProcessingErrorsDetailsEndpoint.as_view(),
name="sentry-api-0-project-processing-errors-details",
),
re_path(
r"^(?P<organization_slug>[^\/]+)/(?P<project_id_or_slug>[^\/]+)/monitors/(?P<monitor_id_or_slug>[^\/]+)/processing-errors/$",
ProjectMonitorProcessingErrorsIndexEndpoint.as_view(),
Expand Down
7 changes: 7 additions & 0 deletions src/sentry/apidocs/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,13 @@ class MonitorParams:
type=str,
description="The owner of the monitor, in the format `user:id` or `team:id`. May be specified multiple times.",
)
PROCESSING_ERROR_ID = OpenApiParameter(
name="processing_error_id",
location="path",
required=False,
type=OpenApiTypes.UUID,
description="The id of the processing error.",
)


class EventParams:
Expand Down
95 changes: 34 additions & 61 deletions src/sentry/monitors/consumers/monitor_consumer.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,23 @@
MonitorType,
)
from sentry.monitors.processing_errors import (
CheckinEnvironmentMismatch,
CheckinFinished,
CheckinGuidProjectMismatch,
CheckinInvalidDuration,
CheckinInvalidGuid,
CheckinValidationError,
ProcessingError,
ProcessingErrorType,
CheckinValidationFailed,
MonitorDisabled,
MonitorDisabledNoQuota,
MonitorEnviromentRateLimited,
MonitorEnvironmentLimitExceeded,
MonitorInvalidConfig,
MonitorInvalidEnvironment,
MonitorLimitExceeded,
MonitorNotFound,
MonitorOverQuota,
OrganizationKillswitchEnabled,
handle_processing_errors,
)
from sentry.monitors.types import CheckinItem
Expand Down Expand Up @@ -117,14 +131,7 @@ def _ensure_monitor_with_config(
}
logger.info("monitors.consumer.invalid_config", extra=extra)
if not monitor:
raise CheckinValidationError(
[
ProcessingError(
ProcessingErrorType.MONITOR_INVALID_CONFIG,
{"errors": validator.errors},
)
]
)
raise CheckinValidationError([MonitorInvalidConfig({"errors": validator.errors})])
return monitor

validated_config = validator.validated_data
Expand Down Expand Up @@ -266,12 +273,7 @@ def update_existing_check_in(
or existing_check_in.monitor_id != monitor.id
or existing_check_in.monitor_environment_id != monitor_environment.id
):
processing_errors.append(
ProcessingError(
ProcessingErrorType.CHECKIN_GUID_PROJECT_MISMATCH,
{"guid": existing_check_in.guid.hex},
)
)
processing_errors.append(CheckinGuidProjectMismatch({"guid": existing_check_in.guid.hex}))
metrics.incr(
"monitors.checkin.result",
tags={"source": "consumer", "status": "guid_mismatch"},
Expand Down Expand Up @@ -299,7 +301,7 @@ def update_existing_check_in(
)

if already_user_complete and not updated_duration_only:
processing_errors.append(ProcessingError(ProcessingErrorType.CHECKIN_FINISHED))
processing_errors.append(CheckinFinished())
metrics.incr(
"monitors.checkin.result",
tags={**metric_kwargs, "status": "checkin_finished"},
Expand All @@ -325,12 +327,7 @@ def update_existing_check_in(
)

if not valid_duration(updated_duration):
processing_errors.append(
ProcessingError(
ProcessingErrorType.CHECKIN_INVALID_DURATION,
{"duration": updated_duration},
)
)
processing_errors.append(CheckinInvalidDuration({"duration": updated_duration}))
metrics.incr(
"monitors.checkin.result",
tags={**metric_kwargs, "status": "failed_duration_check"},
Expand Down Expand Up @@ -412,9 +409,7 @@ def _process_checkin(item: CheckinItem, txn: Transaction | Span):
timestamp=start_time,
category=DataCategory.MONITOR,
)
raise CheckinValidationError(
[ProcessingError(ProcessingErrorType.ORGANIZATION_KILLSWITCH_ENABLED)]
)
raise CheckinValidationError([OrganizationKillswitchEnabled()])

if check_ratelimit(metric_kwargs, item):
track_outcome(
Expand All @@ -426,9 +421,7 @@ def _process_checkin(item: CheckinItem, txn: Transaction | Span):
timestamp=start_time,
category=DataCategory.MONITOR,
)
raise CheckinValidationError(
[ProcessingError(ProcessingErrorType.MONITOR_ENVIRONMENT_RATELIMITED)]
)
raise CheckinValidationError([MonitorEnviromentRateLimited()])

# Does quotas allow for this check-in to be accepted?
quotas_outcome: PermitCheckInStatus = quotas.backend.check_accept_monitor_checkin(
Expand All @@ -445,7 +438,7 @@ def _process_checkin(item: CheckinItem, txn: Transaction | Span):
timestamp=start_time,
category=DataCategory.MONITOR,
)
raise CheckinValidationError([ProcessingError(ProcessingErrorType.MONITOR_OVER_QUOTA)])
raise CheckinValidationError([MonitorOverQuota()])

guid, use_latest_checkin = transform_checkin_uuid(
txn,
Expand All @@ -464,7 +457,7 @@ def _process_checkin(item: CheckinItem, txn: Transaction | Span):
timestamp=start_time,
category=DataCategory.MONITOR,
)
raise CheckinValidationError([ProcessingError(ProcessingErrorType.CHECKIN_INVALID_GUID)])
raise CheckinValidationError([CheckinInvalidGuid()])

monitor_config = params.pop("monitor_config", None)

Expand Down Expand Up @@ -503,13 +496,7 @@ def _process_checkin(item: CheckinItem, txn: Transaction | Span):
timestamp=start_time,
category=DataCategory.MONITOR,
)
raise CheckinValidationError(
[
ProcessingError(
ProcessingErrorType.CHECKIN_VALIDATION_FAILED, {"errors": validator.errors}
)
]
)
raise CheckinValidationError([CheckinValidationFailed({"errors": validator.errors})])

validated_params = validator.validated_data

Expand Down Expand Up @@ -544,9 +531,7 @@ def _process_checkin(item: CheckinItem, txn: Transaction | Span):
timestamp=start_time,
category=DataCategory.MONITOR,
)
raise CheckinValidationError(
[ProcessingError(ProcessingErrorType.MONITOR_LIMIT_EXCEEDED, {"reason": str(e)})]
)
raise CheckinValidationError([MonitorLimitExceeded({"reason": str(e)})])

# When accepting for upsert attempt to assign a seat for the monitor,
# otherwise the monitor is marked as disabled
Expand Down Expand Up @@ -574,7 +559,7 @@ def _process_checkin(item: CheckinItem, txn: Transaction | Span):
timestamp=start_time,
category=DataCategory.MONITOR,
)
ensure_config_errors.append(ProcessingError(ProcessingErrorType.MONITOR_NOT_FOUND))
ensure_config_errors.append(MonitorNotFound())
raise CheckinValidationError(ensure_config_errors)

# When a monitor was accepted for upsert but is disabled we were unable to
Expand All @@ -592,9 +577,7 @@ def _process_checkin(item: CheckinItem, txn: Transaction | Span):
timestamp=start_time,
category=DataCategory.MONITOR,
)
raise CheckinValidationError(
[ProcessingError(ProcessingErrorType.MONITOR_DISABLED_NO_QUOTA)], monitor
)
raise CheckinValidationError([MonitorDisabledNoQuota()], monitor)

# Discard check-ins if the monitor is disabled
#
Expand All @@ -617,9 +600,7 @@ def _process_checkin(item: CheckinItem, txn: Transaction | Span):
timestamp=start_time,
category=DataCategory.MONITOR,
)
raise CheckinValidationError(
[ProcessingError(ProcessingErrorType.MONITOR_DISABLED)], monitor
)
raise CheckinValidationError([MonitorDisabled()], monitor)

# 02
# Retrieve or upsert monitor environment for this check-in
Expand Down Expand Up @@ -652,11 +633,7 @@ def _process_checkin(item: CheckinItem, txn: Transaction | Span):
category=DataCategory.MONITOR,
)
raise CheckinValidationError(
[
ProcessingError(
ProcessingErrorType.MONITOR_ENVIRONMENT_LIMIT_EXCEEDED, {"reason": str(e)}
)
],
[MonitorEnvironmentLimitExceeded({"reason": str(e)})],
monitor,
)
except MonitorEnvironmentValidationFailed as e:
Expand All @@ -683,10 +660,7 @@ def _process_checkin(item: CheckinItem, txn: Transaction | Span):
timestamp=start_time,
category=DataCategory.MONITOR,
)
raise CheckinValidationError(
[ProcessingError(ProcessingErrorType.MONITOR_INVALID_ENVIRONMENT, {"reason": str(e)})],
monitor,
)
raise CheckinValidationError([MonitorInvalidEnvironment({"reason": str(e)})], monitor)

# 03
# Create or update check-in
Expand Down Expand Up @@ -745,12 +719,11 @@ def _process_checkin(item: CheckinItem, txn: Transaction | Span):
)
raise CheckinValidationError(
[
ProcessingError(
ProcessingErrorType.CHECKIN_ENVIRONMENT_MISMATCH,
CheckinEnvironmentMismatch(
{
"existing_environment": check_in.monitor_environment.get_environment().name
},
)
}
),
],
monitor,
)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
from __future__ import annotations

from uuid import UUID

from drf_spectacular.utils import extend_schema
from rest_framework.exceptions import ValidationError
from rest_framework.permissions import BasePermission
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 region_silo_endpoint
from sentry.api.bases import ProjectEndpoint
from sentry.apidocs.constants import (
RESPONSE_FORBIDDEN,
RESPONSE_NO_CONTENT,
RESPONSE_NOT_FOUND,
RESPONSE_UNAUTHORIZED,
)
from sentry.apidocs.parameters import GlobalParams, MonitorParams
from sentry.models.project import Project
from sentry.monitors.endpoints.base import ProjectMonitorPermission
from sentry.monitors.processing_errors import CheckinProcessErrorsManager, InvalidProjectError


@region_silo_endpoint
@extend_schema(tags=["Crons"])
class ProjectProcessingErrorsDetailsEndpoint(ProjectEndpoint):
permission_classes: tuple[type[BasePermission], ...] = (ProjectMonitorPermission,)

publish_status = {
"DELETE": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.CRONS

@extend_schema(
operation_id="Delete a processing error for a Monitor",
parameters=[
GlobalParams.ORG_SLUG,
GlobalParams.PROJECT_ID_OR_SLUG,
MonitorParams.PROCESSING_ERROR_ID,
],
responses={
204: RESPONSE_NO_CONTENT,
401: RESPONSE_UNAUTHORIZED,
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
},
)
def delete(self, request: Request, project: Project, uuid: str) -> Response:
try:
parsed_uuid = UUID(uuid)
except ValueError:
raise ValidationError("Invalid UUID")
try:
CheckinProcessErrorsManager().delete(project, parsed_uuid)
except InvalidProjectError:
raise ValidationError("Invalid uuid for project")
return self.respond(status=204)
Loading
Loading