hash
stringlengths 40
40
| date
stringdate 2017-08-30 22:37:25
2025-03-22 03:08:47
| author
stringclasses 173
values | commit_message
stringlengths 15
151
| is_merge
bool 1
class | masked_commit_message
stringlengths 6
126
| type
stringclasses 17
values | git_diff
stringlengths 182
1.51M
⌀ |
|---|---|---|---|---|---|---|---|
37047cbf559aca33d3cb0d101c0b68b637be142f
|
2024-04-17 02:17:19
|
Bartek Ogryczak
|
chore(alerts): move weekly summary Monday -> Saturday (#69032)
| false
|
move weekly summary Monday -> Saturday (#69032)
|
chore
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index 4c20c1ed463685..6dae5d3f6ab252 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -1108,7 +1108,7 @@ def SOCIAL_AUTH_DEFAULT_USERNAME() -> str:
"schedule-weekly-organization-reports-new": {
"task": "sentry.tasks.summaries.weekly_reports.schedule_organizations",
# 05:00 PDT, 09:00 EDT, 12:00 UTC
- "schedule": crontab(minute="0", hour="12", day_of_week="monday"),
+ "schedule": crontab(minute="0", hour="12", day_of_week="saturday"),
"options": {"expires": 60 * 60 * 3},
},
"schedule-daily-organization-reports": {
|
a87c5a3a936a824b7dd713117b4225395c750807
|
2020-05-22 15:50:40
|
Matej Minar
|
feat(ui): Better mobile experience for grouping info (#18979)
| false
|
Better mobile experience for grouping info (#18979)
|
feat
|
diff --git a/src/sentry/static/sentry/app/components/events/groupingInfo/groupingVariant.tsx b/src/sentry/static/sentry/app/components/events/groupingInfo/groupingVariant.tsx
index cc9d0c424025d2..25ea757d6dae16 100644
--- a/src/sentry/static/sentry/app/components/events/groupingInfo/groupingVariant.tsx
+++ b/src/sentry/static/sentry/app/components/events/groupingInfo/groupingVariant.tsx
@@ -12,6 +12,7 @@ import {IconCheckmark, IconClose} from 'app/icons';
import space from 'app/styles/space';
import Tooltip from 'app/components/tooltip';
import QuestionTooltip from 'app/components/questionTooltip';
+import overflowEllipsis from 'app/styles/overflowEllipsis';
import {hasNonContributingComponent} from './utils';
import GroupingComponent from './groupingComponent';
@@ -49,7 +50,7 @@ class GroupVariant extends React.Component<Props, State> {
data.push([
t('Hash'),
<TextWithQuestionTooltip key="hash">
- {variant.hash}
+ <Hash>{variant.hash}</Hash>
<QuestionTooltip
size="xs"
position="top"
@@ -167,14 +168,14 @@ class GroupVariant extends React.Component<Props, State> {
const {showNonContributing} = this.state;
return (
- <ButtonBar merged active={showNonContributing ? 'all' : 'relevant'}>
+ <ContributingToggle merged active={showNonContributing ? 'all' : 'relevant'}>
<Button barId="relevant" size="xsmall" onClick={this.handleHideNonContributing}>
{t('Contributing values')}
</Button>
<Button barId="all" size="xsmall" onClick={this.handleShowNonContributing}>
{t('All values')}
</Button>
- </ButtonBar>
+ </ContributingToggle>
);
}
@@ -203,6 +204,9 @@ const Header = styled('div')`
align-items: center;
justify-content: space-between;
margin-bottom: ${space(2)};
+ @media (max-width: ${p => p.theme.breakpoints[0]}) {
+ display: block;
+ }
`;
const VariantTitle = styled('h5')`
@@ -222,6 +226,13 @@ const ContributionIcon = styled(({isContributing, ...p}) =>
margin-right: ${space(1)};
`;
+const ContributingToggle = styled(ButtonBar)`
+ justify-content: flex-end;
+ @media (max-width: ${p => p.theme.breakpoints[0]}) {
+ margin-top: ${space(0.5)};
+ }
+`;
+
const GroupingTree = styled('div')`
color: #2f2936;
`;
@@ -233,4 +244,11 @@ const TextWithQuestionTooltip = styled('div')`
grid-gap: ${space(0.5)};
`;
+const Hash = styled('span')`
+ @media (max-width: ${p => p.theme.breakpoints[0]}) {
+ ${overflowEllipsis};
+ width: 210px;
+ }
+`;
+
export default GroupVariant;
diff --git a/src/sentry/static/sentry/app/components/events/groupingInfo/index.tsx b/src/sentry/static/sentry/app/components/events/groupingInfo/index.tsx
index 2039982862e075..7a9e6c55f65ed9 100644
--- a/src/sentry/static/sentry/app/components/events/groupingInfo/index.tsx
+++ b/src/sentry/static/sentry/app/components/events/groupingInfo/index.tsx
@@ -72,7 +72,10 @@ class EventGroupingInfo extends AsyncComponent<Props, State> {
.sort((a, b) => a!.toLowerCase().localeCompare(b!.toLowerCase()))
.join(', ');
- return <small>{`(${t('grouped by')} ${groupedBy || t('nothing')})`}</small>;
+ return (
+ <SummaryGroupedBy>{`(${t('grouped by')} ${groupedBy ||
+ t('nothing')})`}</SummaryGroupedBy>
+ );
}
renderGroupConfigSelect() {
@@ -150,6 +153,13 @@ class EventGroupingInfo extends AsyncComponent<Props, State> {
}
}
+const SummaryGroupedBy = styled('small')`
+ @media (max-width: ${p => p.theme.breakpoints[0]}) {
+ display: block;
+ margin: 0 !important;
+ }
+`;
+
const ToggleButton = styled(Button)`
font-weight: 700;
color: ${p => p.theme.gray3};
|
0513d7f9962f4f672b6180d65c123ca9ec8bef7d
|
2021-10-16 04:30:27
|
Marcos Gaeta
|
ref(api): De-couple `update_groups()` from requests (#29303)
| false
|
De-couple `update_groups()` from requests (#29303)
|
ref
|
diff --git a/src/sentry/api/helpers/group_index.py b/src/sentry/api/helpers/group_index.py
index 0555484596b79b..f77b5a0ab683d9 100644
--- a/src/sentry/api/helpers/group_index.py
+++ b/src/sentry/api/helpers/group_index.py
@@ -1,6 +1,7 @@
import logging
from collections import defaultdict
from datetime import timedelta
+from typing import Any, Mapping, Optional
from uuid import uuid4
import sentry_sdk
@@ -566,7 +567,20 @@ def get_current_release_version_of_group(group, follows_semver=False):
return current_release_version
-def update_groups(request, group_ids, projects, organization_id, search_fn):
+def update_groups(
+ request,
+ group_ids,
+ projects,
+ organization_id,
+ search_fn,
+ user: Optional["User"] = None,
+ data: Optional[Mapping[str, Any]] = None,
+) -> Response:
+ # If `user` and `data` are passed as parameters then they should override
+ # the values in `request`.
+ user = user or request.user
+ data = data or request.data
+
if group_ids:
group_list = Group.objects.filter(
project__organization_id=organization_id, project__in=projects, id__in=group_ids
@@ -582,7 +596,7 @@ def update_groups(request, group_ids, projects, organization_id, search_fn):
# because of the assignee validation. Punting on this for now.
for project in projects:
serializer = GroupValidator(
- data=request.data,
+ data=data,
partial=True,
context={"project": project, "access": getattr(request, "access", None)},
)
@@ -594,7 +608,7 @@ def update_groups(request, group_ids, projects, organization_id, search_fn):
# so we won't have to requery for each group
project_lookup = {p.id: p for p in projects}
- acting_user = request.user if request.user.is_authenticated else None
+ acting_user = user if user.is_authenticated else None
if not group_ids:
try:
@@ -651,7 +665,7 @@ def update_groups(request, group_ids, projects, organization_id, search_fn):
}
status_details = {
"inNextRelease": True,
- "actor": serialize(extract_lazy_object(request.user), request.user),
+ "actor": serialize(extract_lazy_object(user), user),
}
res_type = GroupResolution.Type.in_next_release
res_type_str = "in_next_release"
@@ -672,7 +686,7 @@ def update_groups(request, group_ids, projects, organization_id, search_fn):
}
status_details = {
"inRelease": release.version,
- "actor": serialize(extract_lazy_object(request.user), request.user),
+ "actor": serialize(extract_lazy_object(user), user),
}
res_type = GroupResolution.Type.in_release
res_type_str = "in_release"
@@ -688,8 +702,8 @@ def update_groups(request, group_ids, projects, organization_id, search_fn):
activity_type = Activity.SET_RESOLVED_IN_COMMIT
activity_data = {"commit": commit.id}
status_details = {
- "inCommit": serialize(commit, request.user),
- "actor": serialize(extract_lazy_object(request.user), request.user),
+ "inCommit": serialize(commit, user),
+ "actor": serialize(extract_lazy_object(user), user),
}
res_type_str = "in_commit"
else:
@@ -731,7 +745,7 @@ def update_groups(request, group_ids, projects, organization_id, search_fn):
"release": release,
"type": res_type,
"status": res_status,
- "actor_id": request.user.id if request.user.is_authenticated else None,
+ "actor_id": user.id if user.is_authenticated else None,
}
# We only set `current_release_version` if GroupResolution type is
@@ -874,7 +888,7 @@ def update_groups(request, group_ids, projects, organization_id, search_fn):
issue_resolved.send_robust(
organization_id=organization_id,
- user=acting_user or request.user,
+ user=acting_user or user,
group=group,
project=project_lookup[group.project_id],
resolution_type=res_type_str,
@@ -930,9 +944,7 @@ def update_groups(request, group_ids, projects, organization_id, search_fn):
"user_count": ignore_user_count,
"user_window": ignore_user_window,
"state": state,
- "actor_id": request.user.id
- if request.user.is_authenticated
- else None,
+ "actor_id": user.id if user.is_authenticated else None,
},
)
result["statusDetails"] = {
@@ -941,7 +953,7 @@ def update_groups(request, group_ids, projects, organization_id, search_fn):
"ignoreUserCount": ignore_user_count,
"ignoreUserWindow": ignore_user_window,
"ignoreWindow": ignore_window,
- "actor": serialize(extract_lazy_object(request.user), request.user),
+ "actor": serialize(extract_lazy_object(user), user),
}
else:
GroupSnooze.objects.filter(group__in=group_ids).delete()
@@ -1042,8 +1054,8 @@ def update_groups(request, group_ids, projects, organization_id, search_fn):
if "assignedTo" in result:
assigned_actor = result["assignedTo"]
assigned_by = (
- request.data.get("assignedBy")
- if request.data.get("assignedBy") in ["assignee_selector", "suggested_assignee"]
+ data.get("assignedBy")
+ if data.get("assignedBy") in ["assignee_selector", "suggested_assignee"]
else None
)
if assigned_actor:
diff --git a/src/sentry/integrations/slack/endpoints/action.py b/src/sentry/integrations/slack/endpoints/action.py
index d5c1131258d419..dfe95a101df342 100644
--- a/src/sentry/integrations/slack/endpoints/action.py
+++ b/src/sentry/integrations/slack/endpoints/action.py
@@ -7,13 +7,14 @@
from sentry import analytics
from sentry.api import ApiClient, client
from sentry.api.base import Endpoint
+from sentry.api.helpers.group_index import update_groups
from sentry.integrations.slack.client import SlackClient
from sentry.integrations.slack.message_builder.issues import build_group_attachment
from sentry.integrations.slack.requests.action import SlackActionRequest
from sentry.integrations.slack.requests.base import SlackRequestError
from sentry.integrations.slack.views.link_identity import build_linking_url
from sentry.integrations.slack.views.unlink_identity import build_unlinking_url
-from sentry.models import ApiKey, Group, Identity, IdentityProvider, Integration, Project
+from sentry.models import Group, Identity, IdentityProvider, Integration, Project
from sentry.shared_integrations.exceptions import ApiError
from sentry.utils import json
from sentry.web.decorators import transaction_start
@@ -21,10 +22,15 @@
from ..message_builder import SlackBody
from ..utils import logger
-LINK_IDENTITY_MESSAGE = "Looks like you haven't linked your Sentry account with your Slack identity yet! <{associate_url}|Link your identity now> to perform actions in Sentry through Slack."
-
-UNLINK_IDENTITY_MESSAGE = "Looks like this Slack identity is linked to the Sentry user *{user_email}* who is not a member of organization *{org_name}* used with this Slack integration. <{associate_url}|Unlink your identity now>."
-
+LINK_IDENTITY_MESSAGE = (
+ "Looks like you haven't linked your Sentry account with your Slack identity yet! "
+ "<{associate_url}|Link your identity now> to perform actions in Sentry through Slack. "
+)
+UNLINK_IDENTITY_MESSAGE = (
+ "Looks like this Slack identity is linked to the Sentry user *{user_email}* "
+ "who is not a member of organization *{org_name}* used with this Slack integration. "
+ "<{associate_url}|Unlink your identity now>. "
+)
DEFAULT_ERROR_MESSAGE = "Sentry can't perform that action right now on your behalf!"
RESOLVE_SELECTOR = {
@@ -41,27 +47,68 @@
}
+def update_group(
+ group: Group,
+ identity: Identity,
+ data: Mapping[str, str],
+ request: Request,
+) -> Response:
+ if not group.organization.has_access(identity.user):
+ raise ApiClient.ApiError(
+ status_code=403, body="The user does not have access to the organization."
+ )
+
+ return update_groups(
+ request=request,
+ group_ids=[group.id],
+ projects=[group.project],
+ organization_id=group.organization.id,
+ search_fn=None,
+ user=identity.user,
+ data=data,
+ )
+
+
class SlackActionEndpoint(Endpoint): # type: ignore
authentication_classes = ()
permission_classes = ()
+ def respond_ephemeral(self, text: str) -> Response:
+ return self.respond({"response_type": "ephemeral", "replace_original": False, "text": text})
+
def api_error(
self,
+ slack_request: SlackActionRequest,
+ group: Group,
+ identity: Identity,
error: ApiClient.ApiError,
action_type: str,
- logging_data: Dict[str, str],
- error_text: str,
) -> Response:
- logging_data = logging_data.copy()
- logging_data["response"] = str(error.body)
- logging_data["action_type"] = action_type
- logger.info(f"slack.action.api-error-pre-message: {str(logging_data)}")
- logger.info("slack.action.api-error", extra=logging_data)
-
- return self.respond(
- {"response_type": "ephemeral", "replace_original": False, "text": error_text}
+ logger.info(
+ "slack.action.api-error",
+ extra={
+ **slack_request.get_logging_data(group),
+ "response": str(error.body),
+ "action_type": action_type,
+ },
)
+ if error.status_code == 403:
+ text = UNLINK_IDENTITY_MESSAGE.format(
+ associate_url=build_unlinking_url(
+ slack_request.integration.id,
+ slack_request.user_id,
+ slack_request.channel_id,
+ slack_request.response_url,
+ ),
+ user_email=identity.user,
+ org_name=group.organization.name,
+ )
+ else:
+ text = DEFAULT_ERROR_MESSAGE
+
+ return self.respond_ephemeral(text)
+
def on_assign(
self, request: Request, identity: Identity, group: Group, action: Mapping[str, Any]
) -> None:
@@ -70,7 +117,7 @@ def on_assign(
if assignee == "none":
assignee = None
- self.update_group(group, identity, {"assignedTo": assignee})
+ update_group(group, identity, {"assignedTo": assignee}, request)
analytics.record("integrations.slack.assign", actor_id=identity.user_id)
def on_status(
@@ -94,7 +141,7 @@ def on_status(
elif resolve_type == "inCurrentRelease":
status.update({"statusDetails": {"inRelease": "latest"}})
- self.update_group(group, identity, status)
+ update_group(group, identity, status, request)
analytics.record(
"integrations.slack.status",
@@ -103,19 +150,6 @@ def on_status(
actor_id=identity.user_id,
)
- def update_group(self, group: Group, identity: Identity, data: Mapping[str, str]) -> Response:
- event_write_key = ApiKey(
- organization=group.project.organization, scope_list=["event:write"]
- )
-
- return client.put(
- path=f"/projects/{group.project.organization.slug}/{group.project.slug}/issues/",
- params={"id": group.id},
- data=data,
- user=identity.user,
- auth=event_write_key,
- )
-
def open_resolve_dialog(
self, data: Mapping[str, Any], group: Group, integration: Integration
) -> None:
@@ -242,13 +276,7 @@ def post(self, request: Request) -> Response:
if not identity:
associate_url = build_linking_url(integration, user_id, channel_id, response_url)
- return self.respond(
- {
- "response_type": "ephemeral",
- "replace_original": False,
- "text": LINK_IDENTITY_MESSAGE.format(associate_url=associate_url),
- }
- )
+ return self.respond_ephemeral(LINK_IDENTITY_MESSAGE.format(associate_url=associate_url))
# Handle status dialog submission
if slack_request.type == "dialog_submission" and "resolve_type" in data["submission"]:
@@ -257,20 +285,8 @@ def post(self, request: Request) -> Response:
try:
self.on_status(request, identity, group, action, data, integration)
- except client.ApiError as e:
-
- if e.status_code == 403:
- text = UNLINK_IDENTITY_MESSAGE.format(
- associate_url=build_unlinking_url(
- integration.id, user_id, channel_id, response_url
- ),
- user_email=identity.user,
- org_name=group.organization.name,
- )
- else:
- text = DEFAULT_ERROR_MESSAGE
-
- return self.api_error(e, "status_dialog", logging_data, text)
+ except client.ApiError as error:
+ return self.api_error(slack_request, group, identity, error, "status_dialog")
group = Group.objects.get(id=group.id)
attachment = build_group_attachment(group, identity=identity, actions=[action])
@@ -309,19 +325,8 @@ def post(self, request: Request) -> Response:
elif action_type == "resolve_dialog":
self.open_resolve_dialog(data, group, integration)
defer_attachment_update = True
- except client.ApiError as e:
- if e.status_code == 403:
- text = UNLINK_IDENTITY_MESSAGE.format(
- associate_url=build_unlinking_url(
- integration.id, user_id, channel_id, response_url
- ),
- user_email=identity.user,
- org_name=group.organization.name,
- )
- else:
- text = DEFAULT_ERROR_MESSAGE
-
- return self.api_error(e, action_type, logging_data, text)
+ except client.ApiError as error:
+ return self.api_error(slack_request, group, identity, error, action_type)
if defer_attachment_update:
return self.respond()
diff --git a/src/sentry/integrations/slack/requests/action.py b/src/sentry/integrations/slack/requests/action.py
index b08753e91a0f09..0abed2c8826ca5 100644
--- a/src/sentry/integrations/slack/requests/action.py
+++ b/src/sentry/integrations/slack/requests/action.py
@@ -1,6 +1,9 @@
+from typing import Mapping, MutableMapping, Optional
+
from rest_framework.request import Request
from sentry.integrations.slack.requests.base import SlackRequest, SlackRequestError
+from sentry.models import Group
from sentry.utils import json
from sentry.utils.cache import memoize
from sentry.utils.json import JSONData
@@ -55,3 +58,22 @@ def _validate_data(self) -> None:
def _log_request(self) -> None:
self._info("slack.action")
+
+ def get_logging_data(
+ self,
+ group: Optional[Group] = None,
+ ) -> Mapping[str, Optional[str]]:
+ logging_data: MutableMapping[str, Optional[str]] = {
+ **self.logging_data,
+ "response_url": self.response_url,
+ }
+
+ if group:
+ logging_data.update(
+ {
+ "group_id": group.id,
+ "organization_id": group.organization.id,
+ }
+ )
+
+ return logging_data
diff --git a/src/sentry/integrations/slack/requests/base.py b/src/sentry/integrations/slack/requests/base.py
index acee55155459bf..38923216660d4d 100644
--- a/src/sentry/integrations/slack/requests/base.py
+++ b/src/sentry/integrations/slack/requests/base.py
@@ -1,4 +1,4 @@
-from typing import Any, Dict, Mapping, MutableMapping, Optional
+from typing import Any, Mapping, MutableMapping, Optional
from rest_framework import status as status_
from rest_framework.request import Request
@@ -61,33 +61,39 @@ def type(self) -> str:
raise NotImplementedError
@property
- def channel_id(self) -> Optional[Any]:
+ def channel_id(self) -> Optional[str]:
"""
Provide a normalized interface to ``channel_id``, which Action and Event
requests provide in different places.
"""
- return self.data.get("channel_id") or self.data.get("channel", {}).get("id")
+ # Explicitly typing to satisfy mypy.
+ channel_id: str = self.data.get("channel_id") or self.data.get("channel", {}).get("id")
+ return channel_id
@property
- def response_url(self) -> Optional[Any]:
+ def response_url(self) -> Optional[str]:
"""Provide an interface to ``response_url`` for convenience."""
return self.data.get("response_url")
@property
- def team_id(self) -> Any:
+ def team_id(self) -> str:
"""
Provide a normalized interface to ``team_id``, which Action and Event
requests provide in different places.
"""
- return self.data.get("team_id") or self.data.get("team", {}).get("id")
+ # Explicitly typing to satisfy mypy.
+ team_id: str = self.data.get("team_id") or self.data.get("team", {}).get("id")
+ return team_id
@property
- def user_id(self) -> Optional[Any]:
+ def user_id(self) -> Optional[str]:
"""
Provide a normalized interface to ``user_id``, which Action and Event
requests provide in different places.
"""
- return self.data.get("user_id") or self.data.get("user", {}).get("id")
+ # Explicitly typing to satisfy mypy.
+ user_id: Optional[str] = self.data.get("user_id") or self.data.get("user", {}).get("id")
+ return user_id
@property
def data(self) -> Mapping[str, Any]:
@@ -96,7 +102,7 @@ def data(self) -> Mapping[str, Any]:
return self._data
@property
- def logging_data(self) -> Dict[str, Any]:
+ def logging_data(self) -> Mapping[str, str]:
data = {
"slack_team_id": self.team_id,
"slack_channel_id": self.data.get("channel", {}).get("id"),
@@ -170,7 +176,7 @@ def _log_request(self) -> None:
self._info("slack.request")
def _error(self, key: str) -> None:
- logger.error(key, extra=self.logging_data)
+ logger.error(key, extra={**self.logging_data})
def _info(self, key: str) -> None:
- logger.info(key, extra=self.logging_data)
+ logger.info(key, extra={**self.logging_data})
diff --git a/tests/sentry/integrations/slack/endpoints/test_action.py b/tests/sentry/integrations/slack/endpoints/test_action.py
index b4e919404729ab..e02571d860ef42 100644
--- a/tests/sentry/integrations/slack/endpoints/test_action.py
+++ b/tests/sentry/integrations/slack/endpoints/test_action.py
@@ -3,7 +3,6 @@
import responses
from freezegun import freeze_time
-from sentry.api import client
from sentry.integrations.slack.endpoints.action import (
LINK_IDENTITY_MESSAGE,
UNLINK_IDENTITY_MESSAGE,
@@ -21,6 +20,7 @@
IdentityStatus,
Integration,
OrganizationIntegration,
+ OrganizationMember,
)
from sentry.testutils import APITestCase
from sentry.utils import json
@@ -322,8 +322,7 @@ def test_permission_denied(self):
@freeze_time("2021-01-14T12:27:28.303Z")
@responses.activate
- @patch("sentry.api.client.put")
- def test_handle_submission_fail(self, client_put):
+ def test_handle_submission_fail(self):
status_action = {"name": "resolve_dialog", "value": "resolve_dialog"}
# Expect request to open dialog on slack
@@ -360,27 +359,27 @@ def test_handle_submission_fail(self, client_put):
content_type="application/json",
)
- # make the client raise an API error
- client_put.side_effect = client.ApiError(
- 403, '{"detail":"You do not have permission to perform this action."}'
- )
+ # Remove the user from the organization.
+ member = OrganizationMember.objects.get(user=self.user, organization=self.organization)
+ member.remove_user()
+ member.save()
- resp = self.post_webhook(
+ response = self.post_webhook(
type="dialog_submission",
callback_id=dialog["callback_id"],
data={"submission": {"resolve_type": "resolved"}},
)
- # TODO(mgaeta): `assert_called` is deprecated. Find a replacement.
- # client_put.assert_called()
-
- associate_url = build_unlinking_url(
- self.integration.id, self.external_id, "C065W1189", self.response_url
- )
-
- assert resp.status_code == 200, resp.content
- assert resp.data["text"] == UNLINK_IDENTITY_MESSAGE.format(
- associate_url=associate_url, user_email=self.user.email, org_name=self.organization.name
+ assert response.status_code == 200, response.content
+ assert response.data["text"] == UNLINK_IDENTITY_MESSAGE.format(
+ associate_url=build_unlinking_url(
+ integration_id=self.integration.id,
+ slack_id=self.external_id,
+ channel_id="C065W1189",
+ response_url=self.response_url,
+ ),
+ user_email=self.user.email,
+ org_name=self.organization.name,
)
@patch(
|
642cf3309e321ae489530e03e63a5c190a404187
|
2024-12-05 03:31:50
|
William Mak
|
fix(rpc): Table request's timezone (#81694)
| false
|
Table request's timezone (#81694)
|
fix
|
diff --git a/src/sentry/search/eap/columns.py b/src/sentry/search/eap/columns.py
index 979f4a1da178db..58245dc36b872e 100644
--- a/src/sentry/search/eap/columns.py
+++ b/src/sentry/search/eap/columns.py
@@ -1,7 +1,9 @@
from collections.abc import Callable
from dataclasses import dataclass
+from datetime import datetime
from typing import Any, Literal
+from dateutil.tz import tz
from sentry_protos.snuba.v1.trace_item_attribute_pb2 import (
AttributeAggregation,
AttributeKey,
@@ -149,6 +151,10 @@ def simple_measurements_field(
)
+def datetime_processor(datetime_string: str) -> str:
+ return datetime.fromisoformat(datetime_string).replace(tzinfo=tz.tzutc()).isoformat()
+
+
SPAN_COLUMN_DEFINITIONS = {
column.public_alias: column
for column in [
@@ -301,6 +307,12 @@ def simple_measurements_field(
internal_name="sentry.sampling_factor",
search_type="percentage",
),
+ ResolvedColumn(
+ public_alias="timestamp",
+ internal_name="sentry.timestamp",
+ search_type="string",
+ processor=datetime_processor,
+ ),
simple_sentry_field("browser.name"),
simple_sentry_field("environment"),
simple_sentry_field("messaging.destination.name"),
@@ -311,7 +323,6 @@ def simple_measurements_field(
simple_sentry_field("sdk.version"),
simple_sentry_field("span.status_code"),
simple_sentry_field("span_id"),
- simple_sentry_field("timestamp"),
simple_sentry_field("trace.status"),
simple_sentry_field("transaction.method"),
simple_sentry_field("transaction.op"),
diff --git a/tests/snuba/api/endpoints/test_organization_events_span_indexed.py b/tests/snuba/api/endpoints/test_organization_events_span_indexed.py
index 79ba061aa302d8..503c6687e655a9 100644
--- a/tests/snuba/api/endpoints/test_organization_events_span_indexed.py
+++ b/tests/snuba/api/endpoints/test_organization_events_span_indexed.py
@@ -1,5 +1,5 @@
import uuid
-from datetime import datetime
+from datetime import datetime, timezone
from unittest import mock
import pytest
@@ -815,7 +815,9 @@ def test_explore_sample_query(self):
assert result["span.duration"] == 1000.0, "duration"
assert result["span.op"] == "", "op"
assert result["span.description"] == source["description"], "description"
- assert datetime.fromisoformat(result["timestamp"]).timestamp() == pytest.approx(
+ ts = datetime.fromisoformat(result["timestamp"])
+ assert ts.tzinfo == timezone.utc
+ assert ts.timestamp() == pytest.approx(
source["end_timestamp_precise"], abs=5
), "timestamp"
assert result["transaction.span_id"] == source["segment_id"], "transaction.span_id"
|
317c65fbcd0f0b31a4e97c415bcf35256900a286
|
2018-11-13 19:11:36
|
Armin Ronacher
|
ref: Use canonical keys everywhere in sentry itself (#10556)
| false
|
Use canonical keys everywhere in sentry itself (#10556)
|
ref
|
diff --git a/src/sentry/api/endpoints/event_apple_crash_report.py b/src/sentry/api/endpoints/event_apple_crash_report.py
index 0bdb0d02de8f38..13209ec1963982 100644
--- a/src/sentry/api/endpoints/event_apple_crash_report.py
+++ b/src/sentry/api/endpoints/event_apple_crash_report.py
@@ -47,7 +47,7 @@ def get(self, request, event_id):
threads = (event.data.get('threads') or {}).get('values')
exceptions = (event.data.get(
- 'sentry.interfaces.Exception') or {}).get('values')
+ 'exception') or {}).get('values')
symbolicated = (request.GET.get('minified') not in ('1', 'true'))
debug_images = None
diff --git a/src/sentry/api/serializers/models/event.py b/src/sentry/api/serializers/models/event.py
index 66d128f518915c..4b29566af0f641 100644
--- a/src/sentry/api/serializers/models/event.py
+++ b/src/sentry/api/serializers/models/event.py
@@ -33,7 +33,7 @@ def _get_entries(self, event, user, is_public=False):
entry = {
'data': data,
- 'type': interface.get_alias(),
+ 'type': interface.external_type,
}
api_meta = None
diff --git a/src/sentry/coreapi.py b/src/sentry/coreapi.py
index 2d38491279433c..5f032994aa76ae 100644
--- a/src/sentry/coreapi.py
+++ b/src/sentry/coreapi.py
@@ -180,12 +180,12 @@ def project_id_from_auth(self, auth):
return self.project_key_from_auth(auth).project_id
def ensure_does_not_have_ip(self, data):
- if 'sentry.interfaces.Http' in data:
- if 'env' in data['sentry.interfaces.Http']:
- data['sentry.interfaces.Http']['env'].pop('REMOTE_ADDR', None)
+ if 'request' in data:
+ if 'env' in data['request']:
+ data['request']['env'].pop('REMOTE_ADDR', None)
- if 'sentry.interfaces.User' in data:
- data['sentry.interfaces.User'].pop('ip_address', None)
+ if 'user' in data:
+ data['user'].pop('ip_address', None)
if 'sdk' in data:
data['sdk'].pop('client_ip', None)
@@ -235,7 +235,7 @@ def auth_from_request(self, request):
class SecurityApiHelper(ClientApiHelper):
- report_interfaces = ('sentry.interfaces.Csp', 'hpkp', 'expectct', 'expectstaple')
+ report_interfaces = ('csp', 'hpkp', 'expectct', 'expectstaple')
def origin_from_request(self, request):
# In the case of security reports, the origin is not available at the
diff --git a/src/sentry/event_manager.py b/src/sentry/event_manager.py
index f8a4e2138749aa..07ac56ba141ac4 100644
--- a/src/sentry/event_manager.py
+++ b/src/sentry/event_manager.py
@@ -71,7 +71,7 @@
DEFAULT_FINGERPRINT_VALUES = frozenset(['{{ default }}', '{{default}}'])
ALLOWED_FUTURE_DELTA = timedelta(minutes=1)
SECURITY_REPORT_INTERFACES = (
- "sentry.interfaces.Csp",
+ "csp",
"hpkp",
"expectct",
"expectstaple",
@@ -118,7 +118,7 @@ def get_hashes_for_event_with_reason(event):
result = interface.compute_hashes(event.platform)
if not result:
continue
- return (interface.get_path(), result)
+ return (interface.path, result)
return ('no_interfaces', [''])
@@ -202,19 +202,19 @@ def generate_culprit(data, platform=None):
culprit = ''
try:
stacktraces = [
- e['stacktrace'] for e in data['sentry.interfaces.Exception']['values']
+ e['stacktrace'] for e in data['exception']['values']
if e.get('stacktrace')
]
except KeyError:
- stacktrace = data.get('sentry.interfaces.Stacktrace')
+ stacktrace = data.get('stacktrace')
if stacktrace:
stacktraces = [stacktrace]
else:
stacktraces = None
if not stacktraces:
- if 'sentry.interfaces.Http' in data:
- culprit = data['sentry.interfaces.Http'].get('url', '')
+ if 'request' in data:
+ culprit = data['request'].get('url', '')
else:
from sentry.interfaces.stacktrace import Stacktrace
culprit = Stacktrace.to_python(stacktraces[-1]).get_culprit_string(
@@ -415,16 +415,16 @@ def clean(d):
'logger': 'csp',
'message': instance.get_message(),
'culprit': instance.get_culprit(),
- instance.get_path(): instance.to_json(),
+ instance.path: instance.to_json(),
'tags': instance.get_tags(),
'errors': [],
- 'sentry.interfaces.User': {'ip_address': self._client_ip},
+ 'user': {'ip_address': self._client_ip},
# Construct a faux Http interface based on the little information we have
# This is a bit weird, since we don't have nearly enough
# information to create an Http interface, but
# this automatically will pick up tags for the User-Agent
# which is actually important here for CSP
- 'sentry.interfaces.Http': {
+ 'request': {
'url': instance.get_origin(),
'headers': clean(
{
@@ -513,14 +513,14 @@ def stringify(f):
# Fill in ip addresses marked as {{auto}}
if self._client_ip:
- if get_path(data, ['sentry.interfaces.Http', 'env', 'REMOTE_ADDR']) == '{{auto}}':
- data['sentry.interfaces.Http']['env']['REMOTE_ADDR'] = self._client_ip
+ if get_path(data, ['request', 'env', 'REMOTE_ADDR']) == '{{auto}}':
+ data['request']['env']['REMOTE_ADDR'] = self._client_ip
if get_path(data, ['request', 'env', 'REMOTE_ADDR']) == '{{auto}}':
data['request']['env']['REMOTE_ADDR'] = self._client_ip
- if get_path(data, ['sentry.interfaces.User', 'ip_address']) == '{{auto}}':
- data['sentry.interfaces.User']['ip_address'] = self._client_ip
+ if get_path(data, ['user', 'ip_address']) == '{{auto}}':
+ data['user']['ip_address'] = self._client_ip
if get_path(data, ['user', 'ip_address']) == '{{auto}}':
data['user']['ip_address'] = self._client_ip
@@ -554,7 +554,7 @@ def stringify(f):
try:
inst = interface.to_python(value)
- data[inst.get_path()] = inst.to_json()
+ data[inst.path] = inst.to_json()
except Exception as e:
log = logger.debug if isinstance(
e, InterfaceValidationError) else logger.error
@@ -619,11 +619,11 @@ def stringify(f):
data['type'] = eventtypes.infer(data).key
data['version'] = self.version
- exception = data.get('sentry.interfaces.Exception')
- stacktrace = data.get('sentry.interfaces.Stacktrace')
+ exception = data.get('exception')
+ stacktrace = data.get('stacktrace')
if exception and len(exception['values']) == 1 and stacktrace:
exception['values'][0]['stacktrace'] = stacktrace
- del data['sentry.interfaces.Stacktrace']
+ del data['stacktrace']
# Exception mechanism needs SDK information to resolve proper names in
# exception meta (such as signal names). "SDK Information" really means
@@ -641,11 +641,11 @@ def stringify(f):
is_public = self._auth and self._auth.is_public
add_ip_platforms = ('javascript', 'cocoa', 'objc')
- http_ip = data.get('sentry.interfaces.Http', {}).get('env', {}).get('REMOTE_ADDR')
+ http_ip = data.get('request', {}).get('env', {}).get('REMOTE_ADDR')
if http_ip:
- data.setdefault('sentry.interfaces.User', {}).setdefault('ip_address', http_ip)
+ data.setdefault('user', {}).setdefault('ip_address', http_ip)
elif self._client_ip and (is_public or data.get('platform') in add_ip_platforms):
- data.setdefault('sentry.interfaces.User', {}).setdefault('ip_address', self._client_ip)
+ data.setdefault('user', {}).setdefault('ip_address', self._client_ip)
# Trim values
data['logger'] = trim(data['logger'].strip(), 64)
@@ -679,7 +679,7 @@ def should_filter(self):
if release and not is_valid_release(self._project, release):
return (True, FilterStatKeys.RELEASE_VERSION)
- message_interface = self._data.get('sentry.interfaces.Message', {})
+ message_interface = self._data.get('logentry', {})
error_message = message_interface.get('formatted', '') or message_interface.get(
'message', ''
)
@@ -687,7 +687,7 @@ def should_filter(self):
return (True, FilterStatKeys.ERROR_MESSAGE)
for exception_interface in self._data.get(
- 'sentry.interfaces.Exception', {}
+ 'exception', {}
).get('values', []):
message = u': '.join(
filter(None, map(exception_interface.get, ['type', 'value']))
@@ -849,7 +849,7 @@ def save(self, project_id, raw=False):
tags[k] = v
# Get rid of ephemeral interface data
if iface.ephemeral:
- data.pop(iface.get_path(), None)
+ data.pop(iface.path, None)
# tags are stored as a tuple
tags = tags.items()
@@ -883,11 +883,11 @@ def save(self, project_id, raw=False):
# index components into ``Event.message``
# See GH-3248
if event_type.key != 'default':
- if 'sentry.interfaces.Message' in data and \
- data['sentry.interfaces.Message']['message'] != message:
+ if 'logentry' in data and \
+ data['logentry']['message'] != message:
message = u'{} {}'.format(
message,
- data['sentry.interfaces.Message']['message'],
+ data['logentry']['message'],
)
if not message:
@@ -1158,7 +1158,7 @@ def save(self, project_id, raw=False):
return event
def _get_event_user(self, project, data):
- user_data = data.get('sentry.interfaces.User')
+ user_data = data.get('user')
if not user_data:
return
diff --git a/src/sentry/eventtypes/base.py b/src/sentry/eventtypes/base.py
index 746029c905d73f..8e76a00b0041c0 100644
--- a/src/sentry/eventtypes/base.py
+++ b/src/sentry/eventtypes/base.py
@@ -29,7 +29,7 @@ def has_metadata(self):
def get_metadata(self):
# See GH-3248
message_interface = self.data.get(
- 'sentry.interfaces.Message', {
+ 'logentry', {
'message': self.data.get('message', ''),
}
)
diff --git a/src/sentry/eventtypes/error.py b/src/sentry/eventtypes/error.py
index 99dc71493821ff..0d9d1e5d1bce4d 100644
--- a/src/sentry/eventtypes/error.py
+++ b/src/sentry/eventtypes/error.py
@@ -23,7 +23,7 @@ class ErrorEvent(BaseEvent):
def has_metadata(self):
try:
- exception = self.data['sentry.interfaces.Exception']['values'][-1]
+ exception = self.data['exception']['values'][-1]
exception['type']
exception['value']
return True
@@ -31,7 +31,7 @@ def has_metadata(self):
return False
def get_metadata(self):
- exception = self.data['sentry.interfaces.Exception']['values'][-1]
+ exception = self.data['exception']['values'][-1]
# in some situations clients are submitting non-string data for these
rv = {
diff --git a/src/sentry/eventtypes/security.py b/src/sentry/eventtypes/security.py
index c854467b56e5e8..784a8ec9e06348 100644
--- a/src/sentry/eventtypes/security.py
+++ b/src/sentry/eventtypes/security.py
@@ -8,13 +8,13 @@ class CspEvent(BaseEvent):
def has_metadata(self):
# TODO(alexh) also look for 'csp' ?
- return 'sentry.interfaces.Csp' in self.data
+ return 'csp' in self.data
def get_metadata(self):
from sentry.interfaces.security import Csp
# TODO(dcramer): pull get message into here to avoid instantiation
# or ensure that these get interfaces passed instead of raw data
- csp = Csp.to_python(self.data['sentry.interfaces.Csp'])
+ csp = Csp.to_python(self.data['csp'])
return {
'directive': csp.effective_directive,
diff --git a/src/sentry/filters/browser_extensions.py b/src/sentry/filters/browser_extensions.py
index 0c8e496c78bdf2..fb601499cf8910 100644
--- a/src/sentry/filters/browser_extensions.py
+++ b/src/sentry/filters/browser_extensions.py
@@ -79,14 +79,14 @@ class BrowserExtensionsFilter(Filter):
def get_exception_value(self, data):
try:
- return data['sentry.interfaces.Exception']['values'][0]['value']
+ return data['exception']['values'][0]['value']
except (LookupError, TypeError):
return ''
def get_exception_source(self, data):
try:
- return data['sentry.interfaces.Exception']['values'][0]['stacktrace']['frames'
- ][-1]['abs_path']
+ return data['exception']['values'][0]['stacktrace']['frames'
+ ][-1]['abs_path']
except (LookupError, TypeError):
return ''
diff --git a/src/sentry/filters/legacy_browsers.py b/src/sentry/filters/legacy_browsers.py
index 4f6d476c80e49f..288e5cf0639772 100644
--- a/src/sentry/filters/legacy_browsers.py
+++ b/src/sentry/filters/legacy_browsers.py
@@ -81,7 +81,7 @@ def enable(self, value=None):
def get_user_agent(self, data):
try:
- for key, value in data['sentry.interfaces.Http']['headers']:
+ for key, value in data['request']['headers']:
if key.lower() == 'user-agent':
return value
except LookupError:
diff --git a/src/sentry/filters/localhost.py b/src/sentry/filters/localhost.py
index 9233a8829521ec..8db763e318cc9b 100644
--- a/src/sentry/filters/localhost.py
+++ b/src/sentry/filters/localhost.py
@@ -15,13 +15,13 @@ class LocalhostFilter(Filter):
def get_ip_address(self, data):
try:
- return data['sentry.interfaces.User']['ip_address']
+ return data['user']['ip_address']
except KeyError:
return ''
def get_url(self, data):
try:
- return data['sentry.interfaces.Http']['url'] or ''
+ return data['request']['url'] or ''
except KeyError:
return ''
diff --git a/src/sentry/filters/web_crawlers.py b/src/sentry/filters/web_crawlers.py
index f8a47f532f614d..e30056f57845c7 100644
--- a/src/sentry/filters/web_crawlers.py
+++ b/src/sentry/filters/web_crawlers.py
@@ -52,7 +52,7 @@ class WebCrawlersFilter(Filter):
def get_user_agent(self, data):
try:
- for key, value in data['sentry.interfaces.Http']['headers']:
+ for key, value in data['request']['headers']:
if key.lower() == 'user-agent':
return value
except LookupError:
diff --git a/src/sentry/interfaces/base.py b/src/sentry/interfaces/base.py
index 467645f0f5da37..57a6403b58e147 100644
--- a/src/sentry/interfaces/base.py
+++ b/src/sentry/interfaces/base.py
@@ -10,6 +10,7 @@
from sentry.utils.html import escape
from sentry.utils.imports import import_string
from sentry.utils.safe import safe_execute
+from sentry.utils.decorators import classproperty
def get_interface(name):
@@ -66,6 +67,18 @@ class Interface(object):
def __init__(self, **data):
self._data = data or {}
+ @classproperty
+ def path(cls):
+ """The 'path' of the interface which is the root key in the data."""
+ return cls.__name__.lower()
+
+ @classproperty
+ def external_type(cls):
+ """The external name of the interface. This is mostly the same as
+ path with some small differences (message, debugmeta).
+ """
+ return cls.path
+
def __eq__(self, other):
if not isinstance(self, type(other)):
return False
@@ -105,13 +118,6 @@ def to_json(self):
# lists and strings get discarded as we've deemed them not important
return dict((k, v) for k, v in six.iteritems(self._data) if (v == 0 or v))
- def get_path(self):
- cls = type(self)
- return '%s.%s' % (cls.__module__, cls.__name__)
-
- def get_alias(self):
- return self.get_slug()
-
def get_hash(self):
return []
@@ -121,9 +127,6 @@ def compute_hashes(self, platform):
return []
return [result]
- def get_slug(self):
- return type(self).__name__.lower()
-
def get_title(self):
return _(type(self).__name__)
@@ -144,3 +147,21 @@ def to_email_html(self, event, **kwargs):
if not body:
return ''
return '<pre>%s</pre>' % (escape(body), )
+
+ # deprecated stuff. These were deprecated in late 2018, once
+ # determined they are unused we can kill them.
+
+ def get_path(self):
+ from warnings import warn
+ warn(DeprecationWarning('Replaced with .path'))
+ return self.path
+
+ def get_alias(self):
+ from warnings import warn
+ warn(DeprecationWarning('Replaced with .path'))
+ return self.path
+
+ def get_slug(self):
+ from warnings import warn
+ warn(DeprecationWarning('Replaced with .path'))
+ return self.path
diff --git a/src/sentry/interfaces/breadcrumbs.py b/src/sentry/interfaces/breadcrumbs.py
index 84c8763bcb797d..69b9f6f1de1322 100644
--- a/src/sentry/interfaces/breadcrumbs.py
+++ b/src/sentry/interfaces/breadcrumbs.py
@@ -113,12 +113,6 @@ def normalize_crumb(cls, crumb):
return rv
- def get_path(self):
- return 'sentry.interfaces.Breadcrumbs'
-
- def get_alias(self):
- return 'breadcrumbs'
-
def get_api_context(self, is_public=False):
def _convert(x):
return {
diff --git a/src/sentry/interfaces/contexts.py b/src/sentry/interfaces/contexts.py
index 027cfbb7695f1a..645a7ede2a3ee7 100644
--- a/src/sentry/interfaces/contexts.py
+++ b/src/sentry/interfaces/contexts.py
@@ -195,6 +195,3 @@ def iter_tags(self):
for inst in self.iter_contexts():
for tag in inst.iter_tags():
yield tag
-
- def get_path(self):
- return 'contexts'
diff --git a/src/sentry/interfaces/debug_meta.py b/src/sentry/interfaces/debug_meta.py
index 75d83173fef4ef..a91b21a39a95c0 100644
--- a/src/sentry/interfaces/debug_meta.py
+++ b/src/sentry/interfaces/debug_meta.py
@@ -95,6 +95,8 @@ class DebugMeta(Interface):
"""
ephemeral = False
+ path = 'debug_meta'
+ external_type = 'debugmeta'
@classmethod
def to_python(cls, data):
@@ -142,6 +144,3 @@ def normalize_sdk_info(sdk_info):
}
except KeyError as e:
raise InterfaceValidationError('Missing value for sdk_info: %s' % e.args[0])
-
- def get_path(self):
- return 'debug_meta'
diff --git a/src/sentry/interfaces/exception.py b/src/sentry/interfaces/exception.py
index 8e02a84ea1a8b1..0f488e3350f233 100644
--- a/src/sentry/interfaces/exception.py
+++ b/src/sentry/interfaces/exception.py
@@ -732,8 +732,6 @@ class Mechanism(Interface):
>>> }
"""
- path = 'mechanism'
-
@classmethod
def to_python(cls, data):
data = upgrade_legacy_mechanism(data)
@@ -795,9 +793,6 @@ def to_json(self):
'meta': prune_empty_keys(self.meta),
})
- def get_path(self):
- return self.path
-
def iter_tags(self):
yield (self.path, self.type)
@@ -812,7 +807,7 @@ class SingleException(Interface):
module namespace. Either ``type`` or ``value`` must be present.
You can also optionally bind a stacktrace interface to an exception. The
- spec is identical to ``sentry.interfaces.Stacktrace``.
+ spec is identical to ``stacktrace``.
>>> {
>>> "type": "ValueError",
@@ -820,12 +815,12 @@ class SingleException(Interface):
>>> "module": "__builtins__",
>>> "mechanism": {},
>>> "stacktrace": {
- >>> # see sentry.interfaces.Stacktrace
+ >>> # see stacktrace
>>> }
>>> }
"""
score = 2000
- path = 'sentry.interfaces.Exception'
+ path = 'exception'
@classmethod
def to_python(cls, data, slim_frames=True):
@@ -949,12 +944,6 @@ def get_api_meta(self, meta, is_public=False):
'stacktrace': stacktrace_meta,
}
- def get_alias(self):
- return 'exception'
-
- def get_path(self):
- return self.path
-
def get_hash(self, platform=None):
output = None
if self.stacktrace:
@@ -976,7 +965,7 @@ class Exception(Interface):
namespace.
You can also optionally bind a stacktrace interface to an exception. The
- spec is identical to ``sentry.interfaces.Stacktrace``.
+ spec is identical to ``stacktrace``.
>>> {
>>> "values": [{
@@ -987,7 +976,7 @@ class Exception(Interface):
>>> # see sentry.interfaces.Mechanism
>>> },
>>> "stacktrace": {
- >>> # see sentry.interfaces.Stacktrace
+ >>> # see stacktrace
>>> }
>>> }]
>>> }
@@ -1047,12 +1036,6 @@ def to_json(self):
'exc_omitted': self.exc_omitted,
}
- def get_alias(self):
- return 'exception'
-
- def get_path(self):
- return 'sentry.interfaces.Exception'
-
def compute_hashes(self, platform):
system_hash = self.get_hash(platform, system_frames=True)
if not system_hash:
diff --git a/src/sentry/interfaces/geo.py b/src/sentry/interfaces/geo.py
index 12c943fab28719..a9a7c9292219a9 100644
--- a/src/sentry/interfaces/geo.py
+++ b/src/sentry/interfaces/geo.py
@@ -19,9 +19,6 @@ class Geo(Interface):
>>> }
"""
- def get_path(self):
- return 'geo'
-
@classmethod
def to_python(cls, data):
kwargs = {
diff --git a/src/sentry/interfaces/http.py b/src/sentry/interfaces/http.py
index 6783ef60cdfee4..7f860e1f2130e9 100644
--- a/src/sentry/interfaces/http.py
+++ b/src/sentry/interfaces/http.py
@@ -118,7 +118,7 @@ class Http(Interface):
"""
display_score = 1000
score = 800
- path = 'sentry.interfaces.Http'
+ path = 'request'
FORM_TYPE = 'application/x-www-form-urlencoded'
@@ -213,9 +213,6 @@ def to_python(cls, data):
return cls(**kwargs)
- def get_path(self):
- return self.path
-
@property
def full_url(self):
url = self.url
@@ -237,9 +234,6 @@ def to_email_html(self, event, **kwargs):
}
)
- def get_alias(self):
- return 'request'
-
def get_title(self):
return _('Request')
diff --git a/src/sentry/interfaces/message.py b/src/sentry/interfaces/message.py
index d5c7685548bae8..ba453ffc4b5348 100644
--- a/src/sentry/interfaces/message.py
+++ b/src/sentry/interfaces/message.py
@@ -38,6 +38,8 @@ class Message(Interface):
"""
score = 0
display_score = 2050
+ path = 'logentry'
+ external_type = 'message'
@classmethod
def to_python(cls, data):
@@ -90,9 +92,6 @@ def to_python(cls, data):
return cls(**kwargs)
- def get_path(self):
- return 'sentry.interfaces.Message'
-
def get_hash(self):
return [self.message]
diff --git a/src/sentry/interfaces/schemas.py b/src/sentry/interfaces/schemas.py
index c8101551fb88a5..5b91aa924a729f 100644
--- a/src/sentry/interfaces/schemas.py
+++ b/src/sentry/interfaces/schemas.py
@@ -665,6 +665,7 @@ def apierror(message="Invalid data"):
"""
INPUT_SCHEMAS = {
'sentry.interfaces.Csp': CSP_SCHEMA,
+ 'csp': CSP_SCHEMA,
'hpkp': HPKP_SCHEMA,
'expectct': EXPECT_CT_SCHEMA,
'expectstaple': EXPECT_STAPLE_SCHEMA,
@@ -694,6 +695,7 @@ def apierror(message="Invalid data"):
# Security reports
'sentry.interfaces.Csp': CSP_INTERFACE_SCHEMA,
+ 'csp': CSP_INTERFACE_SCHEMA,
'hpkp': HPKP_INTERFACE_SCHEMA,
'expectct': EXPECT_CT_INTERFACE_SCHEMA,
'expectstaple': EXPECT_STAPLE_INTERFACE_SCHEMA,
diff --git a/src/sentry/interfaces/sdk.py b/src/sentry/interfaces/sdk.py
index 22495bab937a42..725ca8597e708b 100644
--- a/src/sentry/interfaces/sdk.py
+++ b/src/sentry/interfaces/sdk.py
@@ -68,9 +68,6 @@ def to_python(cls, data):
return cls(**kwargs)
- def get_path(self):
- return 'sdk'
-
def get_api_context(self, is_public=False):
newest_version = get_with_prefix(settings.SDK_VERSIONS, self.name)
newest_name = get_with_prefix(settings.DEPRECATED_SDKS, self.name, self.name)
diff --git a/src/sentry/interfaces/security.py b/src/sentry/interfaces/security.py
index 3a9d2952f52218..d2aa3d2f11db55 100644
--- a/src/sentry/interfaces/security.py
+++ b/src/sentry/interfaces/security.py
@@ -87,7 +87,6 @@ class SecurityReport(Interface):
A browser security violation report.
"""
- path = None
title = None
@classmethod
@@ -114,9 +113,6 @@ def get_culprit(self):
def get_message(self):
raise NotImplementedError
- def get_path(self):
- return self.path
-
def get_tags(self):
raise NotImplementedError
@@ -159,7 +155,6 @@ class Hpkp(SecurityReport):
score = 1300
display_score = 1300
- path = 'hpkp'
title = 'HPKP Report'
@classmethod
@@ -220,7 +215,6 @@ class ExpectStaple(SecurityReport):
score = 1300
display_score = 1300
- path = 'expectstaple'
title = 'Expect-Staple Report'
@classmethod
@@ -283,7 +277,6 @@ class ExpectCT(SecurityReport):
score = 1300
display_score = 1300
- path = 'expectct'
title = 'Expect-CT Report'
@classmethod
@@ -342,7 +335,6 @@ class Csp(SecurityReport):
score = 1300
display_score = 1300
- path = 'sentry.interfaces.Csp'
title = 'CSP Report'
@classmethod
diff --git a/src/sentry/interfaces/stacktrace.py b/src/sentry/interfaces/stacktrace.py
index df999a53cffb3e..91b36dbdf87680 100644
--- a/src/sentry/interfaces/stacktrace.py
+++ b/src/sentry/interfaces/stacktrace.py
@@ -285,8 +285,6 @@ def is_recursion(frame1, frame2):
class Frame(Interface):
- path = 'frame'
-
@classmethod
def to_python(cls, data, raw=False):
is_valid, errors = validate_and_default_interface(data, cls.path)
@@ -631,7 +629,7 @@ class Stacktrace(Interface):
OR
``module``
- Platform-specific module path (e.g. sentry.interfaces.Stacktrace)
+ Platform-specific module path (e.g. stacktrace)
The following additional attributes are supported:
@@ -699,7 +697,6 @@ class Stacktrace(Interface):
to the full interface path.
"""
score = 2000
- path = 'sentry.interfaces.Stacktrace'
def __iter__(self):
return iter(self.frames)
@@ -791,9 +788,6 @@ def to_json(self):
'registers': self.registers,
}
- def get_path(self):
- return self.path
-
def compute_hashes(self, platform):
system_hash = self.get_hash(platform, system_frames=True)
if not system_hash:
diff --git a/src/sentry/interfaces/template.py b/src/sentry/interfaces/template.py
index 1c698feed6251c..8546643c5534c5 100644
--- a/src/sentry/interfaces/template.py
+++ b/src/sentry/interfaces/template.py
@@ -53,12 +53,6 @@ def to_python(cls, data):
}
return cls(**kwargs)
- def get_alias(self):
- return 'template'
-
- def get_path(self):
- return 'sentry.interfaces.Template'
-
def get_hash(self):
return [self.filename, self.context_line]
diff --git a/src/sentry/interfaces/threads.py b/src/sentry/interfaces/threads.py
index 18d847847f4c1c..5805c98b284f3e 100644
--- a/src/sentry/interfaces/threads.py
+++ b/src/sentry/interfaces/threads.py
@@ -86,9 +86,6 @@ def get_meta_context(self, meta, is_public=False):
else:
return meta
- def get_path(self):
- return 'threads'
-
def get_hash(self):
if len(self.values) != 1:
return []
diff --git a/src/sentry/interfaces/user.py b/src/sentry/interfaces/user.py
index 3897b1441c4ec6..bb5f56f4f9c08f 100644
--- a/src/sentry/interfaces/user.py
+++ b/src/sentry/interfaces/user.py
@@ -130,9 +130,6 @@ def get_api_meta(self, meta, is_public=False):
'data': meta.get('data'),
}
- def get_path(self):
- return 'sentry.interfaces.User'
-
def get_hash(self):
return []
diff --git a/src/sentry/lang/javascript/errorlocale.py b/src/sentry/lang/javascript/errorlocale.py
index 4b5639b88d73c9..1e114f9c6df8a3 100644
--- a/src/sentry/lang/javascript/errorlocale.py
+++ b/src/sentry/lang/javascript/errorlocale.py
@@ -87,12 +87,12 @@ def translate_message(original_message):
def translate_exception(data):
- if 'sentry.interfaces.Message' in data:
- data['sentry.interfaces.Message']['message'] = translate_message(
- data['sentry.interfaces.Message']['message'])
+ if 'logentry' in data:
+ data['logentry']['message'] = translate_message(
+ data['logentry']['message'])
- if 'sentry.interfaces.Exception' in data:
- for entry in data['sentry.interfaces.Exception']['values']:
+ if 'exception' in data:
+ for entry in data['exception']['values']:
if 'value' in entry:
entry['value'] = translate_message(entry['value'])
diff --git a/src/sentry/lang/javascript/errormapping.py b/src/sentry/lang/javascript/errormapping.py
index b7fc18c2bfcebe..60d5f433d7d955 100644
--- a/src/sentry/lang/javascript/errormapping.py
+++ b/src/sentry/lang/javascript/errormapping.py
@@ -115,7 +115,7 @@ def rewrite_exception(data):
in place and returns `True` if a modification was performed or `False`
otherwise.
"""
- exc_data = data.get('sentry.interfaces.Exception')
+ exc_data = data.get('exception')
if not exc_data:
return False
diff --git a/src/sentry/lang/javascript/plugin.py b/src/sentry/lang/javascript/plugin.py
index 6598a7c9ed38d8..17b16bc547fbe0 100644
--- a/src/sentry/lang/javascript/plugin.py
+++ b/src/sentry/lang/javascript/plugin.py
@@ -34,7 +34,7 @@ def generate_modules(data):
def fix_culprit(data):
- exc = data.get('sentry.interfaces.Exception')
+ exc = data.get('exception')
if not exc:
return
@@ -43,7 +43,7 @@ def fix_culprit(data):
def parse_user_agent(data):
- http = data.get('sentry.interfaces.Http')
+ http = data.get('request')
if not http:
return None
diff --git a/src/sentry/lang/javascript/processor.py b/src/sentry/lang/javascript/processor.py
index e968b56e4e8f36..980c3ad036869e 100644
--- a/src/sentry/lang/javascript/processor.py
+++ b/src/sentry/lang/javascript/processor.py
@@ -491,14 +491,14 @@ def __init__(self, *args, **kwargs):
def get_stacktraces(self, data):
try:
stacktraces = [
- e['stacktrace'] for e in data['sentry.interfaces.Exception']['values']
+ e['stacktrace'] for e in data['exception']['values']
if e.get('stacktrace')
]
except KeyError:
stacktraces = []
- if 'sentry.interfaces.Stacktrace' in data:
- stacktraces.append(data['sentry.interfaces.Stacktrace'])
+ if 'stacktrace' in data:
+ stacktraces.append(data['stacktrace'])
return [(s, Stacktrace.to_python(s)) for s in stacktraces]
diff --git a/src/sentry/lang/native/plugin.py b/src/sentry/lang/native/plugin.py
index 229cb566ac1738..e61ef8a36117fd 100644
--- a/src/sentry/lang/native/plugin.py
+++ b/src/sentry/lang/native/plugin.py
@@ -73,7 +73,7 @@ def find_best_instruction(self, processable_frame):
# to disambiugate the first frame. If we can get this information
# from the mechanism we want to pass it onwards.
signal = None
- exc = self.data.get('sentry.interfaces.Exception')
+ exc = self.data.get('exception')
if exc is not None:
mechanism = exc['values'][0].get('mechanism')
if mechanism and 'meta' in mechanism and \
diff --git a/src/sentry/lang/native/utils.py b/src/sentry/lang/native/utils.py
index 105798efb40608..a0ba30c8273fab 100644
--- a/src/sentry/lang/native/utils.py
+++ b/src/sentry/lang/native/utils.py
@@ -41,13 +41,13 @@ def _probe_for_stacktrace(container):
if processed is not None:
rv.append((processed, container))
- exc_container = data.get('sentry.interfaces.Exception')
+ exc_container = data.get('exception')
if exc_container:
for exc in exc_container['values']:
_probe_for_stacktrace(exc)
# The legacy stacktrace interface does not support raw stacktraces
- stacktrace = data.get('sentry.interfaces.Stacktrace')
+ stacktrace = data.get('stacktrace')
if stacktrace:
rv.append((stacktrace, None))
diff --git a/src/sentry/management/commands/send_fake_data.py b/src/sentry/management/commands/send_fake_data.py
index a9acb86625a471..e0a6855aa232e1 100644
--- a/src/sentry/management/commands/send_fake_data.py
+++ b/src/sentry/management/commands/send_fake_data.py
@@ -50,7 +50,7 @@ def exception(client):
data={
'logger': six.next(loggers),
'site': 'web',
- 'sentry.interfaces.User': {
+ 'user': {
'id': email,
'email': email,
}
diff --git a/src/sentry/models/event.py b/src/sentry/models/event.py
index dd0c68e304ab08..c396b9cd31de37 100644
--- a/src/sentry/models/event.py
+++ b/src/sentry/models/event.py
@@ -97,7 +97,7 @@ def _get_project(self):
project = property(_get_project, _set_project)
def get_legacy_message(self):
- msg_interface = self.data.get('sentry.interfaces.Message', {
+ msg_interface = self.data.get('logentry', {
'message': self.message,
})
return msg_interface.get('formatted', msg_interface['message'])
@@ -151,13 +151,13 @@ def version(self):
@memoize
def ip_address(self):
- user_data = self.data.get('sentry.interfaces.User', self.data.get('user'))
+ user_data = self.data.get('user', self.data.get('user'))
if user_data:
value = user_data.get('ip_address')
if value:
return value
- http_data = self.data.get('sentry.interfaces.Http', self.data.get('http'))
+ http_data = self.data.get('request', self.data.get('http'))
if http_data and 'env' in http_data:
value = http_data['env'].get('REMOTE_ADDR')
if value:
diff --git a/src/sentry/ownership/grammar.py b/src/sentry/ownership/grammar.py
index 2a20a5b6c67fdb..32e938d2c498fb 100644
--- a/src/sentry/ownership/grammar.py
+++ b/src/sentry/ownership/grammar.py
@@ -96,7 +96,7 @@ def test(self, data):
def test_url(self, data):
try:
- url = data['sentry.interfaces.Http']['url']
+ url = data['request']['url']
except KeyError:
return False
return fnmatch(url, self.pattern)
@@ -198,13 +198,13 @@ def generic_visit(self, node, children):
def _iter_frames(data):
try:
- for frame in data['sentry.interfaces.Stacktrace']['frames']:
+ for frame in data['stacktrace']['frames']:
yield frame
except KeyError:
pass
try:
- values = data['sentry.interfaces.Exception']['values']
+ values = data['exception']['values']
except KeyError:
return
diff --git a/src/sentry/plugins/sentry_urls/models.py b/src/sentry/plugins/sentry_urls/models.py
index 9e99e2381c3a24..b9aa2bd01b1650 100644
--- a/src/sentry/plugins/sentry_urls/models.py
+++ b/src/sentry/plugins/sentry_urls/models.py
@@ -16,7 +16,7 @@
class UrlsPlugin(TagPlugin):
"""
Automatically adds the 'url' tag from events containing interface data
- from ``sentry.interfaces.Http``.
+ from ``request``.
"""
slug = 'urls'
title = 'Auto Tag: URLs'
@@ -27,7 +27,7 @@ class UrlsPlugin(TagPlugin):
project_default_enabled = True
def get_tag_values(self, event):
- http = event.interfaces.get('sentry.interfaces.Http')
+ http = event.interfaces.get('request')
if not http:
return []
if not http.url:
diff --git a/src/sentry/plugins/sentry_useragents/models.py b/src/sentry/plugins/sentry_useragents/models.py
index 153792b639e74f..d30347fbf8c86c 100644
--- a/src/sentry/plugins/sentry_useragents/models.py
+++ b/src/sentry/plugins/sentry_useragents/models.py
@@ -26,7 +26,7 @@ def get_tag_values(self, event):
if contexts:
return []
- http = event.interfaces.get('sentry.interfaces.Http')
+ http = event.interfaces.get('request')
if not http:
return []
if not http.headers:
@@ -53,7 +53,7 @@ def get_tag_values(self, event):
class BrowserPlugin(UserAgentPlugin):
"""
Automatically adds the 'browser' tag from events containing interface data
- from ``sentry.interfaces.Http``.
+ from ``request``.
"""
slug = 'browsers'
title = 'Auto Tag: Browsers'
@@ -82,7 +82,7 @@ def get_tag_from_ua(self, ua):
class OsPlugin(UserAgentPlugin):
"""
Automatically adds the 'os' tag from events containing interface data
- from ``sentry.interfaces.Http``.
+ from ``request``.
"""
slug = 'os'
title = 'Auto Tag: Operating Systems'
@@ -112,7 +112,7 @@ def get_tag_from_ua(self, ua):
class DevicePlugin(UserAgentPlugin):
"""
Automatically adds the 'device' tag from events containing interface data
- from ``sentry.interfaces.Http``.
+ from ``request``.
"""
slug = 'device'
title = 'Auto Tag: Device'
diff --git a/src/sentry/receivers/features.py b/src/sentry/receivers/features.py
index db8ec84f6ccef7..e3ceec8f68f84a 100644
--- a/src/sentry/receivers/features.py
+++ b/src/sentry/receivers/features.py
@@ -73,7 +73,7 @@ def record_event_processed(project, group, event, **kwargs):
feature_slugs.append('environment_tracking')
# User Tracking
- user_context = event.data.get('sentry.interfaces.User')
+ user_context = event.data.get('user')
# We'd like them to tag with id or email.
# Certain SDKs automatically tag with ip address.
# Check to make sure more the ip address is being sent.
@@ -91,7 +91,7 @@ def record_event_processed(project, group, event, **kwargs):
feature_slugs.append('source_maps')
# Breadcrumbs
- if event.data.get('sentry.interfaces.Breadcrumbs'):
+ if event.data.get('breadcrumbs'):
feature_slugs.append('breadcrumbs')
if not feature_slugs:
diff --git a/src/sentry/receivers/onboarding.py b/src/sentry/receivers/onboarding.py
index ab029be3df4174..7faab18e6b0338 100644
--- a/src/sentry/receivers/onboarding.py
+++ b/src/sentry/receivers/onboarding.py
@@ -222,7 +222,7 @@ def record_release_received(project, group, event, **kwargs):
@event_processed.connect(weak=False)
def record_user_context_received(project, group, event, **kwargs):
- user_context = event.data.get('sentry.interfaces.User')
+ user_context = event.data.get('user')
if not user_context:
return
# checking to see if only ip address is being sent (our js library does this automatically)
diff --git a/src/sentry/rules/conditions/event_attribute.py b/src/sentry/rules/conditions/event_attribute.py
index a06f6d51abe7c1..625179a88cfda0 100644
--- a/src/sentry/rules/conditions/event_attribute.py
+++ b/src/sentry/rules/conditions/event_attribute.py
@@ -158,27 +158,27 @@ def _get_attribute_values(self, event, attr):
return []
return [
- getattr(e, path[1]) for e in event.interfaces['sentry.interfaces.Exception'].values
+ getattr(e, path[1]) for e in event.interfaces['exception'].values
]
elif path[0] == 'user':
if path[1] in ('id', 'ip_address', 'email', 'username'):
- return [getattr(event.interfaces['sentry.interfaces.User'], path[1])]
- return [getattr(event.interfaces['sentry.interfaces.User'].data, path[1])]
+ return [getattr(event.interfaces['user'], path[1])]
+ return [getattr(event.interfaces['user'].data, path[1])]
elif path[0] == 'http':
if path[1] not in ('url', 'method'):
return []
- return [getattr(event.interfaces['sentry.interfaces.Http'], path[1])]
+ return [getattr(event.interfaces['request'], path[1])]
elif path[0] == 'stacktrace':
- stacks = event.interfaces.get('sentry.interfaces.Stacktrace')
+ stacks = event.interfaces.get('stacktrace')
if stacks:
stacks = [stacks]
else:
stacks = [
- e.stacktrace for e in event.interfaces['sentry.interfaces.Exception'].values
+ e.stacktrace for e in event.interfaces['exception'].values
if e.stacktrace
]
diff --git a/src/sentry/similarity/features.py b/src/sentry/similarity/features.py
index 22a65fa6eeef15..14b7af80149eaf 100644
--- a/src/sentry/similarity/features.py
+++ b/src/sentry/similarity/features.py
@@ -37,7 +37,7 @@ def __init__(self, function):
def extract(self, event):
try:
- interface = event.interfaces['sentry.interfaces.Exception']
+ interface = event.interfaces['exception']
except KeyError:
raise InterfaceDoesNotExist()
return self.function(interface.values[0])
@@ -49,7 +49,7 @@ def __init__(self, function):
def extract(self, event):
try:
- interface = event.interfaces['sentry.interfaces.Message']
+ interface = event.interfaces['logentry']
except KeyError:
raise InterfaceDoesNotExist()
return self.function(interface)
diff --git a/src/sentry/stacktraces.py b/src/sentry/stacktraces.py
index 4a7853a29fda63..952c271fc830ee 100644
--- a/src/sentry/stacktraces.py
+++ b/src/sentry/stacktraces.py
@@ -172,14 +172,14 @@ def _report_stack(stacktrace, container):
platforms.add(frame.get('platform') or data.get('platform'))
rv.append(StacktraceInfo(stacktrace=stacktrace, container=container, platforms=platforms))
- exc_container = data.get('sentry.interfaces.Exception')
+ exc_container = data.get('exception')
if exc_container:
for exc in exc_container['values']:
stacktrace = exc.get('stacktrace')
if stacktrace:
_report_stack(stacktrace, exc)
- stacktrace = data.get('sentry.interfaces.Stacktrace')
+ stacktrace = data.get('stacktrace')
if stacktrace:
_report_stack(stacktrace, None)
diff --git a/src/sentry/tasks/unmerge.py b/src/sentry/tasks/unmerge.py
index fefcf1c442720b..e76309846c6ebe 100644
--- a/src/sentry/tasks/unmerge.py
+++ b/src/sentry/tasks/unmerge.py
@@ -465,7 +465,7 @@ def collect_tsdb_data(caches, project, events):
counters[event.datetime][tsdb.models.group][(event.group_id, environment.id)] += 1
- user = event.data.get('sentry.interfaces.User')
+ user = event.data.get('user')
if user:
sets[event.datetime][tsdb.models.users_affected_by_group][(event.group_id, environment.id)].add(
get_event_user_from_interface(user).tag_value,
diff --git a/src/sentry/testutils/fixtures.py b/src/sentry/testutils/fixtures.py
index cf191f73b43344..988cfaaf5a73f3 100644
--- a/src/sentry/testutils/fixtures.py
+++ b/src/sentry/testutils/fixtures.py
@@ -62,7 +62,7 @@ def make_word(words=None):
'modules': {
'raven': '3.1.13'
},
- 'sentry.interfaces.Http': {
+ 'request': {
'cookies': {},
'data': {},
'env': {},
@@ -71,7 +71,7 @@ def make_word(words=None):
'query_string': '',
'url': 'http://example.com',
},
- 'sentry.interfaces.Stacktrace': {
+ 'stacktrace': {
'frames': [
{
'abs_path':
@@ -90,12 +90,12 @@ def make_word(words=None):
'raven.base',
'post_context': [
' },', ' })', '',
- " if 'sentry.interfaces.Stacktrace' in data:",
+ " if 'stacktrace' in data:",
' if self.include_paths:'
],
'pre_context': [
'', ' data.update({',
- " 'sentry.interfaces.Stacktrace': {",
+ " 'stacktrace': {",
" 'frames': get_stack_info(frames,",
' list_max_length=self.list_max_length,'
],
@@ -106,10 +106,10 @@ def make_word(words=None):
'event_type': 'raven.events.Message',
'frames': '<generator object iter_stack_frames at 0x103fef050>',
'handler': '<raven.events.Message object at 0x103feb710>',
- 'k': 'sentry.interfaces.Message',
+ 'k': 'logentry',
'public_key': None,
'result': {
- 'sentry.interfaces.Message':
+ 'logentry':
"{'message': 'This is a test message generated using ``raven test``', 'params': []}"
},
'self': '<raven.base.Client object at 0x104397f10>',
@@ -135,12 +135,12 @@ def make_word(words=None):
'raven.base',
'post_context': [
' },', ' })', '',
- " if 'sentry.interfaces.Stacktrace' in data:",
+ " if 'stacktrace' in data:",
' if self.include_paths:'
],
'pre_context': [
'', ' data.update({',
- " 'sentry.interfaces.Stacktrace': {",
+ " 'stacktrace': {",
" 'frames': get_stack_info(frames,",
' list_max_length=self.list_max_length,'
],
@@ -151,10 +151,10 @@ def make_word(words=None):
'event_type': 'raven.events.Message',
'frames': '<generator object iter_stack_frames at 0x103fef050>',
'handler': '<raven.events.Message object at 0x103feb710>',
- 'k': 'sentry.interfaces.Message',
+ 'k': 'logentry',
'public_key': None,
'result': {
- 'sentry.interfaces.Message':
+ 'logentry':
"{'message': 'This is a test message generated using ``raven test``', 'params': []}"
},
'self': '<raven.base.Client object at 0x104397f10>',
@@ -472,7 +472,7 @@ def create_event(self, event_id=None, **kwargs):
kwargs['data']['tags'] = tags
if kwargs.get('stacktrace'):
stacktrace = kwargs.pop('stacktrace')
- kwargs['data']['sentry.interfaces.Stacktrace'] = stacktrace
+ kwargs['data']['stacktrace'] = stacktrace
kwargs['data'].setdefault(
'errors', [{
@@ -483,8 +483,8 @@ def create_event(self, event_id=None, **kwargs):
# maintain simple event fixtures by supporting the legacy message
# parameter just like our API would
- if 'sentry.interfaces.Message' not in kwargs['data']:
- kwargs['data']['sentry.interfaces.Message'] = {
+ if 'logentry' not in kwargs['data']:
+ kwargs['data']['logentry'] = {
'message': kwargs.get('message') or '<unlabeled event>',
}
@@ -493,7 +493,7 @@ def create_event(self, event_id=None, **kwargs):
{
'type': 'default',
'metadata': {
- 'title': kwargs['data']['sentry.interfaces.Message']['message'],
+ 'title': kwargs['data']['logentry']['message'],
},
}
)
@@ -538,7 +538,7 @@ def create_full_event(self, event_id='a', **kwargs):
"extra": {
"session:duration": 40364
},
- "sentry.interfaces.Exception": {
+ "exception": {
"exc_omitted": null,
"values": [{
"stacktrace": {
@@ -569,20 +569,20 @@ def create_full_event(self, event_id='a', **kwargs):
"module": null
}]
},
- "sentry.interfaces.Http": {
+ "request": {
"url": "https://sentry.io/katon-direct/localhost/issues/112734598/",
"headers": [
["Referer", "https://sentry.io/welcome/"],
["User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36"]
]
},
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "0.0.0.0",
"id": "41656",
"email": "[email protected]"
},
"version": "7",
- "sentry.interfaces.Breadcrumbs": {
+ "breadcrumbs": {
"values": [
{
"category": "xhr",
diff --git a/src/sentry/utils/committers.py b/src/sentry/utils/committers.py
index 244914b2db5281..d63d125119ca79 100644
--- a/src/sentry/utils/committers.py
+++ b/src/sentry/utils/committers.py
@@ -39,10 +39,10 @@ def score_path_match_length(path_a, path_b):
def _get_frame_paths(event):
data = event.data
try:
- frames = data['sentry.interfaces.Stacktrace']['frames']
+ frames = data['stacktrace']['frames']
except KeyError:
try:
- frames = data['sentry.interfaces.Exception']['values'][0]['stacktrace']['frames']
+ frames = data['exception']['values'][0]['stacktrace']['frames']
except (KeyError, TypeError):
return [] # can't find stacktrace information
diff --git a/src/sentry/utils/data_scrubber.py b/src/sentry/utils/data_scrubber.py
index 74fbc95ac1613b..c5b860318c5637 100644
--- a/src/sentry/utils/data_scrubber.py
+++ b/src/sentry/utils/data_scrubber.py
@@ -74,26 +74,26 @@ def __init__(self, fields=None, include_defaults=True, exclude_fields=()):
def apply(self, data):
# TODO(dcramer): move this into each interface
- if 'sentry.interfaces.Stacktrace' in data:
- self.filter_stacktrace(data['sentry.interfaces.Stacktrace'])
+ if 'stacktrace' in data:
+ self.filter_stacktrace(data['stacktrace'])
- if 'sentry.interfaces.Exception' in data:
- for exc in data['sentry.interfaces.Exception']['values']:
+ if 'exception' in data:
+ for exc in data['exception']['values']:
if exc.get('stacktrace'):
self.filter_stacktrace(exc['stacktrace'])
- if 'sentry.interfaces.Breadcrumbs' in data:
- for crumb in data['sentry.interfaces.Breadcrumbs'].get('values') or ():
+ if 'breadcrumbs' in data:
+ for crumb in data['breadcrumbs'].get('values') or ():
self.filter_crumb(crumb)
- if 'sentry.interfaces.Http' in data:
- self.filter_http(data['sentry.interfaces.Http'])
+ if 'request' in data:
+ self.filter_http(data['request'])
- if 'sentry.interfaces.User' in data:
- self.filter_user(data['sentry.interfaces.User'])
+ if 'user' in data:
+ self.filter_user(data['user'])
- if 'sentry.interfaces.Csp' in data:
- self.filter_csp(data['sentry.interfaces.Csp'])
+ if 'csp' in data:
+ self.filter_csp(data['csp'])
if 'extra' in data:
data['extra'] = varmap(self.sanitize, data['extra'])
diff --git a/src/sentry/utils/javascript.py b/src/sentry/utils/javascript.py
index e38c8d030beb97..7bfeb91aee8a5e 100644
--- a/src/sentry/utils/javascript.py
+++ b/src/sentry/utils/javascript.py
@@ -13,9 +13,9 @@ def has_sourcemap(event):
return False
data = event.data
- if 'sentry.interfaces.Exception' not in data:
+ if 'exception' not in data:
return False
- exception = data['sentry.interfaces.Exception']
+ exception = data['exception']
for value in exception['values']:
stacktrace = value.get('stacktrace', {})
for frame in stacktrace.get('frames', []):
diff --git a/src/sentry/utils/samples.py b/src/sentry/utils/samples.py
index 0c5f788bdee61a..7ebdc8581bf795 100644
--- a/src/sentry/utils/samples.py
+++ b/src/sentry/utils/samples.py
@@ -135,7 +135,7 @@ def load_data(platform, default=None, timestamp=None, sample_name=None):
data['platform'] = platform
data['message'] = 'This is an example %s exception' % (sample_name or platform, )
- data['sentry.interfaces.User'] = generate_user(
+ data['user'] = generate_user(
ip_address='127.0.0.1',
username='sentry',
id=1,
@@ -155,7 +155,7 @@ def load_data(platform, default=None, timestamp=None, sample_name=None):
data['modules'] = {
'my.package': '1.0.0',
}
- data['sentry.interfaces.Http'] = {
+ data['request'] = {
"cookies": 'foo=bar;biz=baz',
"url": "http://example.com/foo",
"headers": {
@@ -182,7 +182,7 @@ def load_data(platform, default=None, timestamp=None, sample_name=None):
pass
# Make breadcrumb timestamps relative to right now so they make sense
- breadcrumbs = data.get('sentry.interfaces.Breadcrumbs')
+ breadcrumbs = data.get('breadcrumbs')
if breadcrumbs is not None:
duration = 1000
# At this point, breadcrumbs are not normalized. They can either be a
diff --git a/src/sentry/web/api.py b/src/sentry/web/api.py
index e35976ee8f699e..75489cc1c1df08 100644
--- a/src/sentry/web/api.py
+++ b/src/sentry/web/api.py
@@ -791,7 +791,7 @@ def post(self, request, project, helper, **kwargs):
def security_report_type(self, body):
report_type_for_key = {
- 'csp-report': 'sentry.interfaces.Csp',
+ 'csp-report': 'csp',
'expect-ct-report': 'expectct',
'expect-staple-report': 'expectstaple',
'known-pins': 'hpkp',
diff --git a/tests/integration/tests.py b/tests/integration/tests.py
index 1d0bf5da984f83..08b0286e29cb2b 100644
--- a/tests/integration/tests.py
+++ b/tests/integration/tests.py
@@ -176,7 +176,7 @@ def queue_event(method, url, body, headers):
group = Group.objects.get()
assert group.event_set.count() == 1
instance = group.event_set.get()
- assert instance.data['sentry.interfaces.Message']['message'] == 'foo'
+ assert instance.data['logentry']['message'] == 'foo'
class SentryRemoteTest(TestCase):
@@ -503,7 +503,7 @@ def assertReportCreated(self, input, output):
assert Event.objects.count() == 1
e = Event.objects.all()[0]
Event.objects.bind_nodes([e], 'data')
- assert output['message'] == e.data['sentry.interfaces.Message']['message']
+ assert output['message'] == e.data['logentry']['message']
for key, value in six.iteritems(output['tags']):
assert e.get_tag(key) == value
self.assertDictContainsSubset(output['data'], e.data, e.data)
diff --git a/tests/sentry/api/endpoints/test_event_committers.py b/tests/sentry/api/endpoints/test_event_committers.py
index dcd2e5f69e4436..2e01cbbfe27679 100644
--- a/tests/sentry/api/endpoints/test_event_committers.py
+++ b/tests/sentry/api/endpoints/test_event_committers.py
@@ -102,7 +102,7 @@ def test_null_stacktrace(self):
data={
'environment': 'production',
'type': 'default',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'ValueError',
diff --git a/tests/sentry/coreapi/test_coreapi.py b/tests/sentry/coreapi/test_coreapi.py
index 349ea27138b7de..67a66c908e3872 100644
--- a/tests/sentry/coreapi/test_coreapi.py
+++ b/tests/sentry/coreapi/test_coreapi.py
@@ -87,7 +87,7 @@ def test_get_interface_does_not_let_through_disallowed_name():
def test_get_interface_allows_http():
from sentry.interfaces.http import Http
- result = get_interface('sentry.interfaces.Http')
+ result = get_interface('request')
assert result is Http
result = get_interface('request')
assert result is Http
diff --git a/tests/sentry/digests/test_utilities.py b/tests/sentry/digests/test_utilities.py
index 4767c8622e5ed5..1ce05e89644d21 100644
--- a/tests/sentry/digests/test_utilities.py
+++ b/tests/sentry/digests/test_utilities.py
@@ -192,7 +192,7 @@ def setUp(self):
def create_event_data(self, filename, url='http://example.com'):
data = {
'tags': [('level', 'error')],
- 'sentry.interfaces.Stacktrace': {
+ 'stacktrace': {
'frames': [
{
'lineno': 1,
@@ -200,7 +200,7 @@ def create_event_data(self, filename, url='http://example.com'):
},
],
},
- 'sentry.interfaces.Http': {
+ 'request': {
'url': url
},
}
diff --git a/tests/sentry/event_manager/test_ensure_has_ip.py b/tests/sentry/event_manager/test_ensure_has_ip.py
index a36df48d8a75ec..c5fdf4b9dc7e6f 100644
--- a/tests/sentry/event_manager/test_ensure_has_ip.py
+++ b/tests/sentry/event_manager/test_ensure_has_ip.py
@@ -11,66 +11,66 @@ def validate_and_normalize(report, client_ip=None):
def test_with_remote_addr():
inp = {
- "sentry.interfaces.Http": {
+ "request": {
"url": "http://example.com/",
"env": {"REMOTE_ADDR": "192.168.0.1"},
}
}
out = validate_and_normalize(inp, client_ip="127.0.0.1")
- assert out["sentry.interfaces.Http"]["env"]["REMOTE_ADDR"] == "192.168.0.1"
+ assert out["request"]["env"]["REMOTE_ADDR"] == "192.168.0.1"
def test_with_user_ip():
- inp = {"sentry.interfaces.User": {"ip_address": "192.168.0.1"}}
+ inp = {"user": {"ip_address": "192.168.0.1"}}
out = validate_and_normalize(inp, client_ip="127.0.0.1")
- assert out["sentry.interfaces.User"]["ip_address"] == "192.168.0.1"
+ assert out["user"]["ip_address"] == "192.168.0.1"
def test_with_user_auto_ip():
- inp = {"sentry.interfaces.User": {"ip_address": "{{auto}}"}}
+ inp = {"user": {"ip_address": "{{auto}}"}}
out = validate_and_normalize(inp, client_ip="127.0.0.1")
- assert out["sentry.interfaces.User"]["ip_address"] == "127.0.0.1"
+ assert out["user"]["ip_address"] == "127.0.0.1"
inp = {"user": {"ip_address": "{{auto}}"}}
out = validate_and_normalize(inp, client_ip="127.0.0.1")
- assert out["sentry.interfaces.User"]["ip_address"] == "127.0.0.1"
+ assert out["user"]["ip_address"] == "127.0.0.1"
def test_without_ip_values():
inp = {
"platform": "javascript",
- "sentry.interfaces.User": {},
- "sentry.interfaces.Http": {"url": "http://example.com/", "env": {}},
+ "user": {},
+ "request": {"url": "http://example.com/", "env": {}},
}
out = validate_and_normalize(inp, client_ip="127.0.0.1")
- assert out["sentry.interfaces.User"]["ip_address"] == "127.0.0.1"
+ assert out["user"]["ip_address"] == "127.0.0.1"
def test_without_any_values():
inp = {"platform": "javascript"}
out = validate_and_normalize(inp, client_ip="127.0.0.1")
- assert out["sentry.interfaces.User"]["ip_address"] == "127.0.0.1"
+ assert out["user"]["ip_address"] == "127.0.0.1"
def test_with_http_auto_ip():
inp = {
- "sentry.interfaces.Http": {
+ "request": {
"url": "http://example.com/",
"env": {"REMOTE_ADDR": "{{auto}}"},
}
}
out = validate_and_normalize(inp, client_ip="127.0.0.1")
- assert out["sentry.interfaces.Http"]["env"]["REMOTE_ADDR"] == "127.0.0.1"
+ assert out["request"]["env"]["REMOTE_ADDR"] == "127.0.0.1"
def test_with_all_auto_ip():
inp = {
- "sentry.interfaces.User": {"ip_address": "{{auto}}"},
- "sentry.interfaces.Http": {
+ "user": {"ip_address": "{{auto}}"},
+ "request": {
"url": "http://example.com/",
"env": {"REMOTE_ADDR": "{{auto}}"},
},
}
out = validate_and_normalize(inp, client_ip="127.0.0.1")
- assert out["sentry.interfaces.Http"]["env"]["REMOTE_ADDR"] == "127.0.0.1"
- assert out["sentry.interfaces.User"]["ip_address"] == "127.0.0.1"
+ assert out["request"]["env"]["REMOTE_ADDR"] == "127.0.0.1"
+ assert out["user"]["ip_address"] == "127.0.0.1"
diff --git a/tests/sentry/event_manager/test_event_manager.py b/tests/sentry/event_manager/test_event_manager.py
index 05480b50967312..c68db37eb62ab8 100644
--- a/tests/sentry/event_manager/test_event_manager.py
+++ b/tests/sentry/event_manager/test_event_manager.py
@@ -691,7 +691,7 @@ def test_event_user(self):
manager = EventManager(make_event(
event_id='a',
environment='totally unique environment',
- **{'sentry.interfaces.User': {
+ **{'user': {
'id': '1',
}}
))
@@ -752,7 +752,7 @@ def test_event_user(self):
manager = EventManager(
make_event(
event_id='b',
- **{'sentry.interfaces.User': {
+ **{'user': {
'id': '1',
'name': 'jane',
}}
@@ -768,7 +768,7 @@ def test_event_user(self):
assert euser.ident == '1'
def test_event_user_unicode_identifier(self):
- manager = EventManager(make_event(**{'sentry.interfaces.User': {'username': u'foô'}}))
+ manager = EventManager(make_event(**{'user': {'username': u'foô'}}))
manager.normalize()
with self.tasks():
manager.save(self.project.id)
@@ -900,7 +900,7 @@ def test_message_event_type(self):
make_event(
**{
'message': '',
- 'sentry.interfaces.Message': {
+ 'logentry': {
'formatted': 'foo bar',
'message': 'foo %s',
'params': ['bar'],
@@ -922,7 +922,7 @@ def test_error_event_type(self):
manager = EventManager(
make_event(
**{
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [{
'type': 'Foo',
'value': 'bar',
@@ -946,7 +946,7 @@ def test_csp_event_type(self):
manager = EventManager(
make_event(
**{
- 'sentry.interfaces.Csp': {
+ 'csp': {
'effective_directive': 'script-src',
'blocked_uri': 'http://example.com',
},
@@ -988,7 +988,7 @@ def test_no_message(self):
make_event(
**{
'message': None,
- 'sentry.interfaces.Message': {
+ 'logentry': {
'message': 'hello world',
},
}
@@ -1008,7 +1008,7 @@ def test_bad_message(self):
event = manager.save(self.project.id)
assert event.message == '1234'
- assert event.data['sentry.interfaces.Message'] == {
+ assert event.data['logentry'] == {
'message': '1234',
}
@@ -1018,19 +1018,19 @@ def test_message_attribute_goes_to_interface(self):
}))
manager.normalize()
event = manager.save(self.project.id)
- assert event.data['sentry.interfaces.Message'] == {
+ assert event.data['logentry'] == {
'message': 'hello world',
}
def test_message_attribute_goes_to_formatted(self):
- # The combining of 'message' and 'sentry.interfaces.Message' is a bit
+ # The combining of 'message' and 'logentry' is a bit
# of a compatibility hack, and ideally we would just enforce a stricter
# schema instead of combining them like this.
manager = EventManager(
make_event(
**{
'message': 'world hello',
- 'sentry.interfaces.Message': {
+ 'logentry': {
'message': 'hello world',
},
}
@@ -1038,7 +1038,7 @@ def test_message_attribute_goes_to_formatted(self):
)
manager.normalize()
event = manager.save(self.project.id)
- assert event.data['sentry.interfaces.Message'] == {
+ assert event.data['logentry'] == {
'message': 'hello world',
'formatted': 'world hello',
}
@@ -1047,14 +1047,14 @@ def test_message_attribute_interface_both_strings(self):
manager = EventManager(
make_event(
**{
- 'sentry.interfaces.Message': 'a plain string',
+ 'logentry': 'a plain string',
'message': 'another string',
}
)
)
manager.normalize()
event = manager.save(self.project.id)
- assert event.data['sentry.interfaces.Message'] == {
+ assert event.data['logentry'] == {
'message': 'a plain string',
'formatted': 'another string',
}
@@ -1167,7 +1167,7 @@ def test_should_filter_message(self, mock_is_valid_error_message):
]
data = {
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [item.value for item in items]
},
}
diff --git a/tests/sentry/event_manager/test_generate_culprit.py b/tests/sentry/event_manager/test_generate_culprit.py
index cde72b21c39353..ac1d33db4b5ed0 100644
--- a/tests/sentry/event_manager/test_generate_culprit.py
+++ b/tests/sentry/event_manager/test_generate_culprit.py
@@ -8,7 +8,7 @@
def test_with_exception_interface():
data = {
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'stacktrace': {
@@ -26,7 +26,7 @@ def test_with_exception_interface():
}
]
},
- 'sentry.interfaces.Stacktrace': {
+ 'stacktrace': {
'frames': [
{
'lineno': 1,
@@ -38,7 +38,7 @@ def test_with_exception_interface():
}
],
},
- 'sentry.interfaces.Http': {
+ 'request': {
'url': 'http://example.com'
},
}
@@ -47,7 +47,7 @@ def test_with_exception_interface():
def test_with_missing_exception_interface():
data = {
- 'sentry.interfaces.Stacktrace': {
+ 'stacktrace': {
'frames': [
{
'lineno': 1,
@@ -59,7 +59,7 @@ def test_with_missing_exception_interface():
}
],
},
- 'sentry.interfaces.Http': {
+ 'request': {
'url': 'http://example.com'
},
}
@@ -68,8 +68,8 @@ def test_with_missing_exception_interface():
def test_with_empty_stacktrace():
data = {
- 'sentry.interfaces.Stacktrace': None,
- 'sentry.interfaces.Http': {
+ 'stacktrace': None,
+ 'request': {
'url': 'http://example.com'
},
}
@@ -78,14 +78,14 @@ def test_with_empty_stacktrace():
def test_with_only_http_interface():
data = {
- 'sentry.interfaces.Http': {
+ 'request': {
'url': 'http://example.com'
},
}
assert generate_culprit(data) == 'http://example.com'
data = {
- 'sentry.interfaces.Http': {},
+ 'request': {},
}
assert generate_culprit(data) == ''
@@ -96,7 +96,7 @@ def test_empty_data():
def test_truncation():
data = {
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values':
[{
'stacktrace': {
@@ -110,7 +110,7 @@ def test_truncation():
assert len(generate_culprit(data)) == MAX_CULPRIT_LENGTH
data = {
- 'sentry.interfaces.Stacktrace': {
+ 'stacktrace': {
'frames': [{
'filename': 'x' * (MAX_CULPRIT_LENGTH + 1),
}]
@@ -119,7 +119,7 @@ def test_truncation():
assert len(generate_culprit(data)) == MAX_CULPRIT_LENGTH
data = {
- 'sentry.interfaces.Http': {
+ 'request': {
'url': 'x' * (MAX_CULPRIT_LENGTH + 1),
}
}
diff --git a/tests/sentry/event_manager/test_get_hashes_from_fingerprint.py b/tests/sentry/event_manager/test_get_hashes_from_fingerprint.py
index 5db2dda8c9643b..460be4d722f99c 100644
--- a/tests/sentry/event_manager/test_get_hashes_from_fingerprint.py
+++ b/tests/sentry/event_manager/test_get_hashes_from_fingerprint.py
@@ -16,13 +16,13 @@ def test_stacktrace_wins_over_http(http_comp_hash, stack_comp_hash):
stack_comp_hash.return_value = [['foo', 'bar']]
event = Event(
data={
- 'sentry.interfaces.Stacktrace': {
+ 'stacktrace': {
'frames': [{
'lineno': 1,
'filename': 'foo.py',
}],
},
- 'sentry.interfaces.Http': {
+ 'request': {
'url': 'http://example.com'
},
},
diff --git a/tests/sentry/event_manager/test_normalization.py b/tests/sentry/event_manager/test_normalization.py
index e772816dcc1f68..01c2df2c5f7d7c 100644
--- a/tests/sentry/event_manager/test_normalization.py
+++ b/tests/sentry/event_manager/test_normalization.py
@@ -44,15 +44,13 @@ def test_interface_is_relabeled():
data = manager.get_data()
assert data['user'] == {'id': '1'}
- # data is a CanonicalKeyDict, so we need to check .keys() explicitly
- assert 'sentry.interfaces.User' not in data.keys()
def test_does_default_ip_address_to_user():
manager = EventManager(
make_event(
**{
- 'sentry.interfaces.Http': {
+ 'request': {
'url': 'http://example.com',
'env': {
'REMOTE_ADDR': '127.0.0.1',
@@ -64,7 +62,7 @@ def test_does_default_ip_address_to_user():
manager.normalize()
data = manager.get_data()
- assert data['sentry.interfaces.User']['ip_address'] == '127.0.0.1'
+ assert data['user']['ip_address'] == '127.0.0.1'
@mock.patch('sentry.interfaces.geo.Geo.from_ip_address')
@@ -81,7 +79,7 @@ def test_does_geo_from_ip(from_ip_address_mock):
manager = EventManager(
make_event(
**{
- 'sentry.interfaces.User': {
+ 'user': {
'ip_address': '192.168.0.1',
},
}
@@ -90,8 +88,8 @@ def test_does_geo_from_ip(from_ip_address_mock):
manager.normalize()
data = manager.get_data()
- assert data['sentry.interfaces.User']['ip_address'] == '192.168.0.1'
- assert data['sentry.interfaces.User']['geo'] == geo
+ assert data['user']['ip_address'] == '192.168.0.1'
+ assert data['user']['geo'] == geo
@mock.patch('sentry.interfaces.geo.geo_by_addr')
@@ -101,7 +99,7 @@ def test_skips_geo_with_no_result(geo_by_addr_mock):
manager = EventManager(
make_event(
**{
- 'sentry.interfaces.User': {
+ 'user': {
'ip_address': '127.0.0.1',
},
}
@@ -109,21 +107,21 @@ def test_skips_geo_with_no_result(geo_by_addr_mock):
)
manager.normalize()
data = manager.get_data()
- assert data['sentry.interfaces.User']['ip_address'] == '127.0.0.1'
- assert 'geo' not in data['sentry.interfaces.User']
+ assert data['user']['ip_address'] == '127.0.0.1'
+ assert 'geo' not in data['user']
def test_does_default_ip_address_if_present():
manager = EventManager(
make_event(
**{
- 'sentry.interfaces.Http': {
+ 'request': {
'url': 'http://example.com',
'env': {
'REMOTE_ADDR': '127.0.0.1',
}
},
- 'sentry.interfaces.User': {
+ 'user': {
'ip_address': '192.168.0.1',
},
}
@@ -131,7 +129,7 @@ def test_does_default_ip_address_if_present():
)
manager.normalize()
data = manager.get_data()
- assert data['sentry.interfaces.User']['ip_address'] == '192.168.0.1'
+ assert data['user']['ip_address'] == '192.168.0.1'
def test_long_culprit():
@@ -160,7 +158,7 @@ def test_long_message():
)
manager.normalize()
data = manager.get_data()
- assert len(data['sentry.interfaces.Message']['message']) == \
+ assert len(data['logentry']['message']) == \
settings.SENTRY_MAX_MESSAGE_LENGTH
@@ -195,8 +193,8 @@ def test_bad_interfaces_no_exception():
manager = EventManager(
make_event(
**{
- 'sentry.interfaces.User': None,
- 'sentry.interfaces.Http': None,
+ 'user': None,
+ 'request': None,
'sdk': 'A string for sdk is not valid'
}
),
@@ -208,7 +206,7 @@ def test_bad_interfaces_no_exception():
make_event(
**{
'errors': {},
- 'sentry.interfaces.Http': {},
+ 'request': {},
}
)
)
diff --git a/tests/sentry/event_manager/test_validate_csp.py b/tests/sentry/event_manager/test_validate_csp.py
index 8ec02cd75ce42f..0628c427d74490 100644
--- a/tests/sentry/event_manager/test_validate_csp.py
+++ b/tests/sentry/event_manager/test_validate_csp.py
@@ -18,7 +18,7 @@ def test_csp_validate_basic():
report = {
"release": "abc123",
"environment": "production",
- "interface": 'sentry.interfaces.Csp',
+ "interface": 'csp',
"report": {
"csp-report": {
"document-uri": "http://45.55.25.245:8123/csp",
@@ -36,15 +36,15 @@ def test_csp_validate_basic():
assert result['release'] == 'abc123'
assert result['environment'] == 'production'
assert result['errors'] == []
- assert 'sentry.interfaces.Message' in result
+ assert 'logentry' in result
assert 'culprit' in result
assert result['tags'] == [
('effective-directive', 'img-src'),
('blocked-uri', 'http://google.com'),
]
- assert result['sentry.interfaces.User'] == {'ip_address': '198.51.100.0'}
- assert result['sentry.interfaces.Http']['url'] == 'http://45.55.25.245:8123/csp'
- assert dict(result['sentry.interfaces.Http']['headers']) == {
+ assert result['user'] == {'ip_address': '198.51.100.0'}
+ assert result['request']['url'] == 'http://45.55.25.245:8123/csp'
+ assert dict(result['request']['headers']) == {
'User-Agent': 'Awesome Browser',
'Referer': 'http://example.com'
}
@@ -53,7 +53,7 @@ def test_csp_validate_basic():
def test_csp_validate_failure():
report = {
"release": "abc123",
- "interface": 'sentry.interfaces.Csp',
+ "interface": 'csp',
"report": {}
}
@@ -67,7 +67,7 @@ def test_csp_validate_failure():
def test_csp_tags_out_of_bounds():
report = {
"release": "abc123",
- "interface": 'sentry.interfaces.Csp',
+ "interface": 'csp',
"report": {
"csp-report": {
"document-uri": "http://45.55.25.245:8123/csp",
@@ -90,7 +90,7 @@ def test_csp_tags_out_of_bounds():
def test_csp_tag_value():
report = {
"release": "abc123",
- "interface": 'sentry.interfaces.Csp',
+ "interface": 'csp',
"report": {
"csp-report": {
"document-uri": "http://45.55.25.245:8123/csp",
@@ -129,15 +129,15 @@ def test_hpkp_validate_basic():
result = validate_and_normalize(report)
assert result['release'] == 'abc123'
assert result['errors'] == []
- assert 'sentry.interfaces.Message' in result
+ assert 'logentry' in result
assert 'culprit' in result
assert sorted(result['tags']) == [
('hostname', 'www.example.com'),
('include-subdomains', 'false'),
('port', '443'),
]
- assert result['sentry.interfaces.User'] == {'ip_address': '198.51.100.0'}
- assert result['sentry.interfaces.Http'] == {
+ assert result['user'] == {'ip_address': '198.51.100.0'}
+ assert result['request'] == {
'url': 'www.example.com',
'headers': [
('User-Agent', 'Awesome Browser'),
diff --git a/tests/sentry/event_manager/test_validate_data.py b/tests/sentry/event_manager/test_validate_data.py
index 7e5cd0655ae82f..7695acc0642fd6 100644
--- a/tests/sentry/event_manager/test_validate_data.py
+++ b/tests/sentry/event_manager/test_validate_data.py
@@ -92,12 +92,12 @@ def test_invalid_interface_name():
def test_invalid_interface_import_path():
data = validate_and_normalize(
- {"message": "foo", "sentry.interfaces.Exception2": "bar"}
+ {"message": "foo", "exception2": "bar"}
)
- assert "sentry.interfaces.Exception2" not in data
+ assert "exception2" not in data
assert len(data["errors"]) == 1
assert data["errors"][0]["type"] == "invalid_attribute"
- assert data["errors"][0]["name"] == "sentry.interfaces.Exception2"
+ assert data["errors"][0]["name"] == "exception2"
def test_does_expand_list():
@@ -109,7 +109,7 @@ def test_does_expand_list():
],
}
)
- assert "sentry.interfaces.Exception" in data
+ assert "exception" in data
def test_log_level_as_string():
@@ -355,18 +355,18 @@ def test_messages():
# Just 'message': wrap it in interface
data = validate_and_normalize({"message": "foo is bar"})
assert "message" not in data
- assert data["sentry.interfaces.Message"] == {"message": "foo is bar"}
+ assert data["logentry"] == {"message": "foo is bar"}
# both 'message' and interface with no 'formatted' value, put 'message'
# into 'formatted'.
data = validate_and_normalize(
{
"message": "foo is bar",
- "sentry.interfaces.Message": {"message": "something else"},
+ "logentry": {"message": "something else"},
}
)
assert "message" not in data
- assert data["sentry.interfaces.Message"] == {
+ assert data["logentry"] == {
"message": "something else",
"formatted": "foo is bar",
}
@@ -375,7 +375,7 @@ def test_messages():
data = validate_and_normalize(
{
"message": "foo is bar",
- "sentry.interfaces.Message": {
+ "logentry": {
"message": "something else",
"formatted": "something else formatted",
},
@@ -383,7 +383,7 @@ def test_messages():
)
assert "message" not in data
assert len(data["errors"]) == 0
- assert data["sentry.interfaces.Message"] == {
+ assert data["logentry"] == {
"message": "something else",
"formatted": "something else formatted",
}
@@ -397,7 +397,7 @@ def test_messages_old_behavior():
data = validate_and_normalize(
{
"message": "foo is bar",
- "sentry.interfaces.Message": {
+ "logentry": {
"message": "something else",
"formatted": "something else",
},
@@ -405,7 +405,7 @@ def test_messages_old_behavior():
)
assert "message" not in data
assert len(data["errors"]) == 0
- assert data["sentry.interfaces.Message"] == {
+ assert data["logentry"] == {
"message": "something else",
"formatted": "foo is bar",
}
@@ -413,8 +413,8 @@ def test_messages_old_behavior():
# interface discarded as invalid, replaced by new interface containing
# wrapped 'message'
data = validate_and_normalize(
- {"message": "foo is bar", "sentry.interfaces.Message": {"invalid": "invalid"}}
+ {"message": "foo is bar", "logentry": {"invalid": "invalid"}}
)
assert "message" not in data
assert len(data["errors"]) == 1
- assert data["sentry.interfaces.Message"] == {"message": "foo is bar"}
+ assert data["logentry"] == {"message": "foo is bar"}
diff --git a/tests/sentry/filters/test_browser_extensions.py b/tests/sentry/filters/test_browser_extensions.py
index a5cc8e461a869d..a30169a6f64737 100644
--- a/tests/sentry/filters/test_browser_extensions.py
+++ b/tests/sentry/filters/test_browser_extensions.py
@@ -13,7 +13,7 @@ def apply_filter(self, data):
def get_mock_data(self, exc_value=None, exc_source=None):
return {
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -71,7 +71,7 @@ def test_does_not_filter_generic_data(self):
def test_filters_malformed_data(self):
data = self.get_mock_data()
- data['sentry.interfaces.Exception'] = None
+ data['exception'] = None
assert not self.apply_filter(data)
def test_filters_facebook_source(self):
diff --git a/tests/sentry/filters/test_legacy_browsers.py b/tests/sentry/filters/test_legacy_browsers.py
index 71dd8ae22b8eb8..51935004c3a1eb 100644
--- a/tests/sentry/filters/test_legacy_browsers.py
+++ b/tests/sentry/filters/test_legacy_browsers.py
@@ -7,6 +7,7 @@
from sentry.filters.legacy_browsers import LegacyBrowsersFilter
from sentry.models import ProjectOption
from sentry.testutils import APITestCase, TestCase
+from sentry.utils.canonical import CanonicalKeyView
USER_AGENTS = {
'android_2':
@@ -204,12 +205,12 @@ class LegacyBrowsersFilterTest(TestCase):
filter_cls = LegacyBrowsersFilter
def apply_filter(self, data):
- return self.filter_cls(self.project).test(data)
+ return self.filter_cls(self.project).test(CanonicalKeyView(data))
def get_mock_data(self, user_agent):
return {
'platform': 'javascript',
- 'sentry.interfaces.Http': {
+ 'request': {
'url': 'http://example.com',
'method': 'GET',
'headers': [
diff --git a/tests/sentry/filters/test_localhost.py b/tests/sentry/filters/test_localhost.py
index 2440cab104987e..ced97cc00f4f31 100644
--- a/tests/sentry/filters/test_localhost.py
+++ b/tests/sentry/filters/test_localhost.py
@@ -12,10 +12,10 @@ def apply_filter(self, data):
def get_mock_data(self, client_ip=None, url=None):
return {
- 'sentry.interfaces.User': {
+ 'user': {
'ip_address': client_ip,
},
- 'sentry.interfaces.Http': {
+ 'request': {
'url': url,
}
}
diff --git a/tests/sentry/filters/test_web_crawlers.py b/tests/sentry/filters/test_web_crawlers.py
index 8688e13b9d45e4..14421fb5a1e2d4 100644
--- a/tests/sentry/filters/test_web_crawlers.py
+++ b/tests/sentry/filters/test_web_crawlers.py
@@ -12,7 +12,7 @@ def apply_filter(self, data):
def get_mock_data(self, user_agent):
return {
- 'sentry.interfaces.Http': {
+ 'request': {
'url': 'http://example.com',
'method': 'GET',
'headers': [
diff --git a/tests/sentry/interfaces/test_breadcrumbs.py b/tests/sentry/interfaces/test_breadcrumbs.py
index 90e4c09e1e3d6a..9a39e31c7c0d06 100644
--- a/tests/sentry/interfaces/test_breadcrumbs.py
+++ b/tests/sentry/interfaces/test_breadcrumbs.py
@@ -8,7 +8,7 @@
class BreadcrumbsTest(TestCase):
def test_path(self):
- assert Breadcrumbs().get_path() == 'sentry.interfaces.Breadcrumbs'
+ assert Breadcrumbs().get_path() == 'breadcrumbs'
def test_simple(self):
result = Breadcrumbs.to_python(
diff --git a/tests/sentry/interfaces/test_exception.py b/tests/sentry/interfaces/test_exception.py
index f0159725bb85b1..d7148aed5297cf 100644
--- a/tests/sentry/interfaces/test_exception.py
+++ b/tests/sentry/interfaces/test_exception.py
@@ -65,7 +65,7 @@ def test_does_not_wrap_if_exception_omitted_present(self):
}
def test_path(self):
- assert self.interface.get_path() == 'sentry.interfaces.Exception'
+ assert self.interface.get_path() == 'exception'
def test_args_as_keyword_args(self):
inst = Exception.to_python(
@@ -151,7 +151,7 @@ def test_context_with_mixed_frames(self):
)
self.create_event(data={
- 'sentry.interfaces.Exception': inst.to_json(),
+ 'exception': inst.to_json(),
})
context = inst.get_api_context()
assert context['hasSystemFrames']
@@ -181,7 +181,7 @@ def test_context_with_symbols(self):
)
self.create_event(data={
- 'sentry.interfaces.Exception': inst.to_json(),
+ 'exception': inst.to_json(),
})
context = inst.get_api_context()
assert context['values'][0]['stacktrace']['frames'][0]['symbol'] == 'Class.myfunc'
@@ -218,7 +218,7 @@ def test_context_with_only_system_frames(self):
)
self.create_event(data={
- 'sentry.interfaces.Exception': inst.to_json(),
+ 'exception': inst.to_json(),
})
context = inst.get_api_context()
assert not context['hasSystemFrames']
@@ -250,11 +250,11 @@ def test_context_with_only_app_frames(self):
}
]
exc = dict(values=values)
- normalize_in_app({'sentry.interfaces.Exception': exc})
+ normalize_in_app({'exception': exc})
inst = Exception.to_python(exc)
self.create_event(data={
- 'sentry.interfaces.Exception': inst.to_json(),
+ 'exception': inst.to_json(),
})
context = inst.get_api_context()
assert not context['hasSystemFrames']
@@ -293,7 +293,7 @@ def test_context_with_raw_stacks(self):
)
self.create_event(data={
- 'sentry.interfaces.Exception': inst.to_json(),
+ 'exception': inst.to_json(),
})
context = inst.get_api_context()
assert context['values'][0]['stacktrace']['frames'][0]['function'] == 'main'
@@ -323,7 +323,7 @@ def test_context_with_mechanism(self):
)
self.create_event(data={
- 'sentry.interfaces.Exception': inst.to_json(),
+ 'exception': inst.to_json(),
})
context = inst.get_api_context()
assert context['values'][0]['mechanism']['type'] == 'generic'
diff --git a/tests/sentry/interfaces/test_http.py b/tests/sentry/interfaces/test_http.py
index 7722bca324bb25..60013aae30f516 100644
--- a/tests/sentry/interfaces/test_http.py
+++ b/tests/sentry/interfaces/test_http.py
@@ -17,7 +17,7 @@ def interface(self):
))
def test_path(self):
- assert self.interface.get_path() == 'sentry.interfaces.Http'
+ assert self.interface.get_path() == 'request'
def test_serialize_unserialize_behavior(self):
result = type(self.interface).to_python(self.interface.to_json())
diff --git a/tests/sentry/interfaces/test_paths.py b/tests/sentry/interfaces/test_paths.py
new file mode 100644
index 00000000000000..ea5912af5de22f
--- /dev/null
+++ b/tests/sentry/interfaces/test_paths.py
@@ -0,0 +1,11 @@
+from __future__ import absolute_import
+
+from django.conf import settings
+from sentry.utils.imports import import_string
+
+
+def test_paths():
+ for interface in settings.SENTRY_INTERFACES.values():
+ cls = import_string(interface)
+ assert cls.path == object.__new__(cls).get_path()
+ assert cls.path == object.__new__(cls).get_alias()
diff --git a/tests/sentry/interfaces/test_security.py b/tests/sentry/interfaces/test_security.py
index b45bf099c61e66..7e80cfe1660f16 100644
--- a/tests/sentry/interfaces/test_security.py
+++ b/tests/sentry/interfaces/test_security.py
@@ -21,7 +21,7 @@ def interface(self):
)
def test_path(self):
- assert self.interface.get_path() == 'sentry.interfaces.Csp'
+ assert self.interface.get_path() == 'csp'
def test_serialize_unserialize_behavior(self):
result = type(self.interface).to_python(self.interface.to_json())
diff --git a/tests/sentry/interfaces/test_stacktrace.py b/tests/sentry/interfaces/test_stacktrace.py
index 1d7df01162c7b2..62ad9db4c719fa 100644
--- a/tests/sentry/interfaces/test_stacktrace.py
+++ b/tests/sentry/interfaces/test_stacktrace.py
@@ -63,9 +63,9 @@ def test_legacy_interface(self):
# Simple test to ensure legacy data works correctly with the ``Frame``
# objects
event = self.event
- interface = Stacktrace.to_python(event.data['sentry.interfaces.Stacktrace'])
+ interface = Stacktrace.to_python(event.data['stacktrace'])
assert len(interface.frames) == 2
- assert interface == event.interfaces['sentry.interfaces.Stacktrace']
+ assert interface == event.interfaces['stacktrace']
def test_filename(self):
Stacktrace.to_python(dict(frames=[{
diff --git a/tests/sentry/interfaces/test_threads.py b/tests/sentry/interfaces/test_threads.py
index c5d316fea41092..487afd33d025a2 100644
--- a/tests/sentry/interfaces/test_threads.py
+++ b/tests/sentry/interfaces/test_threads.py
@@ -46,7 +46,7 @@ def interface(self):
def test_basics(self):
self.create_event(data={
- 'sentry.interfaces.Exception': self.interface.to_json(),
+ 'exception': self.interface.to_json(),
})
context = self.interface.get_api_context()
assert context['values'][0]['stacktrace']['frames'][0]['function'] == 'main'
diff --git a/tests/sentry/interfaces/test_user.py b/tests/sentry/interfaces/test_user.py
index 7944bea7146a9a..b9a42016d35397 100644
--- a/tests/sentry/interfaces/test_user.py
+++ b/tests/sentry/interfaces/test_user.py
@@ -29,7 +29,7 @@ def test_null_values(self):
assert User.to_python({}).to_json() == sink
def test_path(self):
- assert self.interface.get_path() == 'sentry.interfaces.User'
+ assert self.interface.get_path() == 'user'
def test_serialize_behavior(self):
assert self.interface.to_json() == {
diff --git a/tests/sentry/lang/java/test_plugin.py b/tests/sentry/lang/java/test_plugin.py
index 182b7971bf1a6f..d956aa8d32f1d4 100644
--- a/tests/sentry/lang/java/test_plugin.py
+++ b/tests/sentry/lang/java/test_plugin.py
@@ -59,7 +59,7 @@ def test_basic_resolving(self):
assert len(response.data) == 1
event_data = {
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "31.172.207.97"
},
"extra": {},
@@ -71,7 +71,7 @@ def test_basic_resolving(self):
"uuid": PROGUARD_UUID,
}]
},
- "sentry.interfaces.Exception": {
+ "exception": {
"values": [
{
'stacktrace': {
@@ -118,7 +118,7 @@ def test_basic_resolving(self):
event = Event.objects.first()
- bt = event.interfaces['sentry.interfaces.Exception'].values[0].stacktrace
+ bt = event.interfaces['exception'].values[0].stacktrace
frames = bt.frames
assert frames[0].function == 'getClassContext'
@@ -159,7 +159,7 @@ def test_error_on_resolving(self):
assert len(response.data) == 1
event_data = {
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "31.172.207.97"
},
"extra": {},
@@ -171,7 +171,7 @@ def test_error_on_resolving(self):
"uuid": PROGUARD_BUG_UUID,
}]
},
- "sentry.interfaces.Exception": {
+ "exception": {
"values": [
{
'stacktrace': {
diff --git a/tests/sentry/lang/javascript/test_example.py b/tests/sentry/lang/javascript/test_example.py
index 3aaa4d35f7637b..c93b27078ceb0a 100644
--- a/tests/sentry/lang/javascript/test_example.py
+++ b/tests/sentry/lang/javascript/test_example.py
@@ -45,7 +45,7 @@ def test_sourcemap_expansion(self):
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -62,7 +62,7 @@ def test_sourcemap_expansion(self):
event = Event.objects.get()
- exception = event.interfaces['sentry.interfaces.Exception']
+ exception = event.interfaces['exception']
frame_list = exception.values[0].stacktrace.frames
assert len(frame_list) == 4
diff --git a/tests/sentry/lang/javascript/test_plugin.py b/tests/sentry/lang/javascript/test_plugin.py
index 2e6f5045934dfc..56013107680b3b 100644
--- a/tests/sentry/lang/javascript/test_plugin.py
+++ b/tests/sentry/lang/javascript/test_plugin.py
@@ -37,7 +37,7 @@ def test_adds_contexts_without_device(self):
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Http': {
+ 'request': {
'url':
'http://example.com',
'headers': [
@@ -82,7 +82,7 @@ def test_adds_contexts_with_device(self):
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Http': {
+ 'request': {
'url':
'http://example.com',
'headers': [
@@ -120,7 +120,7 @@ def test_adds_contexts_with_ps4_device(self):
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Http': {
+ 'request': {
'url':
'http://example.com',
'headers': [
@@ -151,7 +151,7 @@ def test_source_expansion(self, mock_fetch_file):
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -191,7 +191,7 @@ def test_source_expansion(self, mock_fetch_file):
)
event = Event.objects.get()
- exception = event.interfaces['sentry.interfaces.Exception']
+ exception = event.interfaces['exception']
frame_list = exception.values[0].stacktrace.frames
frame = frame_list[0]
@@ -213,7 +213,7 @@ def test_inlined_sources(self, mock_discover_sourcemap, mock_fetch_file):
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -250,7 +250,7 @@ def test_inlined_sources(self, mock_discover_sourcemap, mock_fetch_file):
)
event = Event.objects.get()
- exception = event.interfaces['sentry.interfaces.Exception']
+ exception = event.interfaces['exception']
frame_list = exception.values[0].stacktrace.frames
frame = frame_list[0]
@@ -264,10 +264,10 @@ def test_error_message_translations(self):
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Message': {
+ 'logentry': {
'message': u'ReferenceError: Impossible de d\xe9finir une propri\xe9t\xe9 \xab foo \xbb : objet non extensible'
},
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -286,10 +286,10 @@ def test_error_message_translations(self):
event = Event.objects.get()
- message = event.interfaces['sentry.interfaces.Message']
+ message = event.interfaces['logentry']
assert message.message == 'ReferenceError: Cannot define property \'foo\': object is not extensible'
- exception = event.interfaces['sentry.interfaces.Exception']
+ exception = event.interfaces['exception']
assert exception.values[0].value == 'Too many files'
assert exception.values[1].value == 'foo: an unexpected failure occurred while trying to obtain metadata information'
@@ -324,7 +324,7 @@ def test_sourcemap_source_expansion(self):
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -364,7 +364,7 @@ def test_sourcemap_source_expansion(self):
}
]
- exception = event.interfaces['sentry.interfaces.Exception']
+ exception = event.interfaces['exception']
frame_list = exception.values[0].stacktrace.frames
frame = frame_list[0]
@@ -406,7 +406,7 @@ def test_sourcemap_embedded_source_expansion(self):
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -446,7 +446,7 @@ def test_sourcemap_embedded_source_expansion(self):
}
]
- exception = event.interfaces['sentry.interfaces.Exception']
+ exception = event.interfaces['exception']
frame_list = exception.values[0].stacktrace.frames
frame = frame_list[0]
@@ -497,7 +497,7 @@ def test_sourcemap_nofiles_source_expansion(self):
'message': 'hello',
'platform': 'javascript',
'release': 'abc',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -521,7 +521,7 @@ def test_sourcemap_nofiles_source_expansion(self):
event = Event.objects.get()
assert not event.data['errors']
- exception = event.interfaces['sentry.interfaces.Exception']
+ exception = event.interfaces['exception']
frame_list = exception.values[0].stacktrace.frames
assert len(frame_list) == 1
@@ -569,7 +569,7 @@ def test_indexed_sourcemap_source_expansion(self):
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -600,7 +600,7 @@ def test_indexed_sourcemap_source_expansion(self):
event = Event.objects.get()
assert not event.data['errors']
- exception = event.interfaces['sentry.interfaces.Exception']
+ exception = event.interfaces['exception']
frame_list = exception.values[0].stacktrace.frames
frame = frame_list[0]
@@ -742,7 +742,7 @@ def test_expansion_via_release_artifacts(self):
'message': 'hello',
'platform': 'javascript',
'release': 'abc',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -772,7 +772,7 @@ def test_expansion_via_release_artifacts(self):
event = Event.objects.get()
assert not event.data['errors']
- exception = event.interfaces['sentry.interfaces.Exception']
+ exception = event.interfaces['exception']
frame_list = exception.values[0].stacktrace.frames
frame = frame_list[0]
@@ -900,7 +900,7 @@ def test_expansion_via_distribution_release_artifacts(self):
'platform': 'javascript',
'release': 'abc',
'dist': 'foo',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -930,7 +930,7 @@ def test_expansion_via_distribution_release_artifacts(self):
event = Event.objects.get()
assert not event.data['errors']
- exception = event.interfaces['sentry.interfaces.Exception']
+ exception = event.interfaces['exception']
frame_list = exception.values[0].stacktrace.frames
frame = frame_list[0]
@@ -975,7 +975,7 @@ def test_sourcemap_expansion_with_missing_source(self):
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -1014,7 +1014,7 @@ def test_sourcemap_expansion_with_missing_source(self):
}
]
- exception = event.interfaces['sentry.interfaces.Exception']
+ exception = event.interfaces['exception']
frame_list = exception.values[0].stacktrace.frames
frame = frame_list[0]
@@ -1051,7 +1051,7 @@ def test_failed_sourcemap_expansion(self):
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -1085,7 +1085,7 @@ def test_failed_sourcemap_expansion_data_url(self):
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -1125,7 +1125,7 @@ def test_failed_sourcemap_expansion_missing_location_entirely(self):
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -1177,7 +1177,7 @@ def test_html_response_for_js(self):
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -1260,7 +1260,7 @@ def test_node_processing(self):
'message': 'hello',
'platform': 'node',
'release': 'nodeabc123',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -1314,7 +1314,7 @@ def test_node_processing(self):
event = Event.objects.get()
- exception = event.interfaces['sentry.interfaces.Exception']
+ exception = event.interfaces['exception']
frame_list = exception.values[0].stacktrace.frames
assert len(frame_list) == 6
@@ -1369,7 +1369,7 @@ def test_no_fetch_from_http(self):
data = {
'message': 'hello',
'platform': 'node',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -1422,7 +1422,7 @@ def test_no_fetch_from_http(self):
assert resp.status_code, 200
event = Event.objects.get()
- exception = event.interfaces['sentry.interfaces.Exception']
+ exception = event.interfaces['exception']
frame_list = exception.values[0].stacktrace.frames
# This one should not process, so this one should be none.
diff --git a/tests/sentry/lang/javascript/test_processor.py b/tests/sentry/lang/javascript/test_processor.py
index c980cf45ec42c0..3f93d375739536 100644
--- a/tests/sentry/lang/javascript/test_processor.py
+++ b/tests/sentry/lang/javascript/test_processor.py
@@ -539,7 +539,7 @@ def test_get_culprit_is_patched():
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -575,7 +575,7 @@ def test_ensure_module_names():
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
@@ -601,7 +601,7 @@ def test_ensure_module_names():
}
}
generate_modules(data)
- exc = data['sentry.interfaces.Exception']['values'][0]
+ exc = data['exception']['values'][0]
assert exc['stacktrace']['frames'][1]['module'] == 'foo/bar'
@@ -624,7 +624,7 @@ def test_react_error_mapping_resolving(self):
for x in range(3):
data = {
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type':
@@ -659,7 +659,7 @@ def test_react_error_mapping_resolving(self):
assert rewrite_exception(data)
- assert data['sentry.interfaces.Exception']['values'][0]['value'] == (
+ assert data['exception']['values'][0]['value'] == (
'Component.render(): A valid React element (or null) must be '
'returned. You may have returned undefined, an array or '
'some other invalid object.'
@@ -680,7 +680,7 @@ def test_react_error_mapping_empty_args(self):
data = {
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type':
@@ -709,7 +709,7 @@ def test_react_error_mapping_empty_args(self):
assert rewrite_exception(data)
- assert data['sentry.interfaces.Exception']['values'][0]['value'] == (
+ assert data['exception']['values'][0]['value'] == (
'Component.getChildContext(): key "" is not defined in '
'childContextTypes.'
)
@@ -729,7 +729,7 @@ def test_react_error_mapping_truncated(self):
data = {
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type':
@@ -755,7 +755,7 @@ def test_react_error_mapping_truncated(self):
assert rewrite_exception(data)
- assert data['sentry.interfaces.Exception']['values'][0]['value'] == (
+ assert data['exception']['values'][0]['value'] == (
'<redacted>.getChildContext(): key "<redacted>" is not defined in '
'childContextTypes.'
)
diff --git a/tests/sentry/lang/native/test_plugin.py b/tests/sentry/lang/native/test_plugin.py
index c53aac67a9af40..9251d9bf41580a 100644
--- a/tests/sentry/lang/native/test_plugin.py
+++ b/tests/sentry/lang/native/test_plugin.py
@@ -43,7 +43,7 @@ def test_frame_resolution(self, symbolize_frame):
}]
event_data = {
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "31.172.207.97"
},
"extra": {},
@@ -70,7 +70,7 @@ def test_frame_resolution(self, symbolize_frame):
"version_patchlevel": 0
}
},
- "sentry.interfaces.Exception": {
+ "exception": {
"values": [
{
'stacktrace': {
@@ -188,7 +188,7 @@ def test_frame_resolution(self, symbolize_frame):
event = Event.objects.first()
- bt = event.interfaces['sentry.interfaces.Exception'].values[0].stacktrace
+ bt = event.interfaces['exception'].values[0].stacktrace
frames = bt.frames
assert frames[0].function == '<redacted>'
@@ -250,7 +250,7 @@ def test_frame_resolution_no_sdk_info(self):
)
event_data = {
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "31.172.207.97"
},
"extra": {},
@@ -270,7 +270,7 @@ def test_frame_resolution_no_sdk_info(self):
}
]
},
- "sentry.interfaces.Exception": {
+ "exception": {
"values": [
{
"stacktrace": {
@@ -351,7 +351,7 @@ def test_frame_resolution_no_sdk_info(self):
event = Event.objects.get()
- bt = event.interfaces['sentry.interfaces.Exception'].values[0].stacktrace
+ bt = event.interfaces['exception'].values[0].stacktrace
frames = bt.frames
assert frames[0].function == '<redacted>'
@@ -411,7 +411,7 @@ def test_frame_resolution(self, symbolize_frame):
}]
event_data = {
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "31.172.207.97"
},
"extra": {},
@@ -438,7 +438,7 @@ def test_frame_resolution(self, symbolize_frame):
"version_patchlevel": 0
}
},
- "sentry.interfaces.Exception": {
+ "exception": {
"values": [
{
'stacktrace': {
@@ -544,7 +544,7 @@ def test_frame_resolution(self, symbolize_frame):
event = Event.objects.get()
- bt = event.interfaces['sentry.interfaces.Exception'].values[0].stacktrace
+ bt = event.interfaces['exception'].values[0].stacktrace
frames = bt.frames
assert frames[0].function == '<redacted>'
@@ -606,7 +606,7 @@ def test_frame_resolution_no_sdk_info(self):
)
event_data = {
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "31.172.207.97"
},
"extra": {},
@@ -626,7 +626,7 @@ def test_frame_resolution_no_sdk_info(self):
}
]
},
- "sentry.interfaces.Exception": {
+ "exception": {
"values": [
{
"stacktrace": {
@@ -707,7 +707,7 @@ def test_frame_resolution_no_sdk_info(self):
event = Event.objects.get()
- bt = event.interfaces['sentry.interfaces.Exception'].values[0].stacktrace
+ bt = event.interfaces['exception'].values[0].stacktrace
frames = bt.frames
assert frames[0].function == '<redacted>'
@@ -755,7 +755,7 @@ def test_in_app_function_name(self):
# '/private/var/containers/Bundle/Application/',
# (kscm_|kscrash_|KSCrash |SentryClient |RNSentry )
event_data = {
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "31.172.207.97"
},
"extra": {},
@@ -775,7 +775,7 @@ def test_in_app_function_name(self):
}
]
},
- "sentry.interfaces.Exception": {
+ "exception": {
"values": [
{
"stacktrace": {
@@ -890,7 +890,7 @@ def test_in_app_function_name(self):
event = Event.objects.get()
- bt = event.interfaces['sentry.interfaces.Exception'].values[0].stacktrace
+ bt = event.interfaces['exception'].values[0].stacktrace
frames = bt.frames
assert not frames[0].in_app
assert not frames[1].in_app
@@ -938,7 +938,7 @@ def test_in_app_macos(self):
"CrashLib.framework/Versions/A/CrashLib"
)
event_data = {
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "31.172.207.97"
},
"extra": {},
@@ -958,7 +958,7 @@ def test_in_app_macos(self):
}
]
},
- "sentry.interfaces.Exception": {
+ "exception": {
"values": [
{
"stacktrace": {
@@ -1045,7 +1045,7 @@ def test_in_app_macos(self):
event = Event.objects.get()
- bt = event.interfaces['sentry.interfaces.Exception'].values[0].stacktrace
+ bt = event.interfaces['exception'].values[0].stacktrace
frames = bt.frames
assert frames[0].in_app
@@ -1099,7 +1099,7 @@ def test_real_resolving(self):
"version_patchlevel": 4,
}
},
- "sentry.interfaces.Exception": {
+ "exception": {
"values": [
{
'stacktrace': {
@@ -1122,7 +1122,7 @@ def test_real_resolving(self):
event = Event.objects.get()
- bt = event.interfaces['sentry.interfaces.Exception'].values[0].stacktrace
+ bt = event.interfaces['exception'].values[0].stacktrace
frames = bt.frames
assert frames[0].function == 'main'
@@ -1189,7 +1189,7 @@ def broken_make_symcache(cls, obj):
"version_patchlevel": 4,
}
},
- "sentry.interfaces.Exception": {
+ "exception": {
"values": [
{
'stacktrace': {
@@ -1290,7 +1290,7 @@ def test_debug_id_resolving(self):
event = Event.objects.get()
- bt = event.interfaces['sentry.interfaces.Exception'].values[0].stacktrace
+ bt = event.interfaces['exception'].values[0].stacktrace
frames = bt.frames
assert frames[0].function == 'main'
@@ -1304,7 +1304,7 @@ class ExceptionMechanismIntegrationTest(TestCase):
def test_full_mechanism(self):
event_data = {
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "31.172.207.97"
},
"extra": {},
@@ -1319,7 +1319,7 @@ def test_full_mechanism(self):
"version_patchlevel": 0
}
},
- "sentry.interfaces.Exception": {
+ "exception": {
"values": [
{
"stacktrace": {
@@ -1356,7 +1356,7 @@ def test_full_mechanism(self):
event = Event.objects.get()
- mechanism = event.interfaces['sentry.interfaces.Exception'].values[0].mechanism
+ mechanism = event.interfaces['exception'].values[0].mechanism
assert mechanism.type == 'mach'
assert mechanism.meta['signal']['number'] == 6
@@ -1369,7 +1369,7 @@ def test_full_mechanism(self):
def test_mechanism_name_expansion(self):
event_data = {
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "31.172.207.97"
},
"extra": {},
@@ -1384,7 +1384,7 @@ def test_mechanism_name_expansion(self):
"version_patchlevel": 0
}
},
- "sentry.interfaces.Exception": {
+ "exception": {
"values": [
{
"stacktrace": {
@@ -1419,7 +1419,7 @@ def test_mechanism_name_expansion(self):
event = Event.objects.get()
- mechanism = event.interfaces['sentry.interfaces.Exception'].values[0].mechanism
+ mechanism = event.interfaces['exception'].values[0].mechanism
assert mechanism.type == 'mach'
assert mechanism.meta['signal']['number'] == 10
@@ -1433,7 +1433,7 @@ def test_mechanism_name_expansion(self):
def test_legacy_mechanism(self):
event_data = {
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "31.172.207.97"
},
"extra": {},
@@ -1448,7 +1448,7 @@ def test_legacy_mechanism(self):
"version_patchlevel": 0
}
},
- "sentry.interfaces.Exception": {
+ "exception": {
"values": [
{
"stacktrace": {
@@ -1482,7 +1482,7 @@ def test_legacy_mechanism(self):
event = Event.objects.get()
- mechanism = event.interfaces['sentry.interfaces.Exception'].values[0].mechanism
+ mechanism = event.interfaces['exception'].values[0].mechanism
# NOTE: legacy mechanisms are always classified "generic"
assert mechanism.type == 'generic'
@@ -1540,7 +1540,7 @@ def test_full_minidump(self):
event = Event.objects.get()
- bt = event.interfaces['sentry.interfaces.Exception'].values[0].stacktrace
+ bt = event.interfaces['exception'].values[0].stacktrace
frames = bt.frames
main = frames[-1]
assert main.function == 'main'
diff --git a/tests/sentry/lang/native/test_processor.py b/tests/sentry/lang/native/test_processor.py
index cd935354cb276c..1033dc2913d4e7 100644
--- a/tests/sentry/lang/native/test_processor.py
+++ b/tests/sentry/lang/native/test_processor.py
@@ -65,7 +65,7 @@ class BasicResolvingFileTest(TestCase):
)
def test_frame_resolution(self):
event_data = {
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "31.172.207.97"
},
"extra": {},
@@ -97,7 +97,7 @@ def test_frame_resolution(self):
"sdk_info":
SDK_INFO,
},
- "sentry.interfaces.Exception": {
+ "exception": {
"values": [
{
"stacktrace": {
@@ -178,7 +178,7 @@ def make_processors(data, infos):
event_data = process_stacktraces(
event_data, make_processors=make_processors)
- bt = event_data['sentry.interfaces.Exception']['values'][0]['stacktrace']
+ bt = event_data['exception']['values'][0]['stacktrace']
frames = bt['frames']
assert frames[0]['function'] == '<redacted>'
diff --git a/tests/sentry/models/test_event.py b/tests/sentry/models/test_event.py
index 785d3bfb9c2d10..2c6cf53c8be150 100644
--- a/tests/sentry/models/test_event.py
+++ b/tests/sentry/models/test_event.py
@@ -58,7 +58,7 @@ def test_pickling_compat(self):
def test_event_as_dict(self):
event = self.create_event(
data={
- 'sentry.interfaces.Message': {
+ 'logentry': {
'message': 'Hello World!',
},
}
@@ -134,7 +134,7 @@ def test_message(self):
def test_message_interface(self):
event = self.create_event(
message='biz baz',
- data={'sentry.interfaces.Message': {
+ data={'logentry': {
'message': 'foo bar'
}},
)
@@ -144,7 +144,7 @@ def test_message_interface_with_formatting(self):
event = self.create_event(
message='biz baz',
data={
- 'sentry.interfaces.Message': {
+ 'logentry': {
'message': 'foo %s',
'formatted': 'foo bar',
'params': ['bar'],
diff --git a/tests/sentry/models/test_projectownership.py b/tests/sentry/models/test_projectownership.py
index f704fc4963a514..6de7a8d4becd1f 100644
--- a/tests/sentry/models/test_projectownership.py
+++ b/tests/sentry/models/test_projectownership.py
@@ -40,7 +40,7 @@ def test_get_owners_basic(self):
# Match only rule_a
self.assert_ownership_equals(ProjectOwnership.get_owners(
self.project.id, {
- 'sentry.interfaces.Stacktrace': {
+ 'stacktrace': {
'frames': [{
'filename': 'foo.py',
}]
@@ -51,7 +51,7 @@ def test_get_owners_basic(self):
# Match only rule_b
self.assert_ownership_equals(ProjectOwnership.get_owners(
self.project.id, {
- 'sentry.interfaces.Stacktrace': {
+ 'stacktrace': {
'frames': [{
'filename': 'src/thing.txt',
}]
@@ -62,7 +62,7 @@ def test_get_owners_basic(self):
# Matches both rule_a and rule_b
self.assert_ownership_equals(ProjectOwnership.get_owners(
self.project.id, {
- 'sentry.interfaces.Stacktrace': {
+ 'stacktrace': {
'frames': [{
'filename': 'src/foo.py',
}]
@@ -72,7 +72,7 @@ def test_get_owners_basic(self):
assert ProjectOwnership.get_owners(
self.project.id, {
- 'sentry.interfaces.Stacktrace': {
+ 'stacktrace': {
'frames': [{
'filename': 'xxxx',
}]
@@ -87,7 +87,7 @@ def test_get_owners_basic(self):
assert ProjectOwnership.get_owners(
self.project.id, {
- 'sentry.interfaces.Stacktrace': {
+ 'stacktrace': {
'frames': [{
'filename': 'xxxx',
}]
diff --git a/tests/sentry/ownership/test_grammar.py b/tests/sentry/ownership/test_grammar.py
index e85a50f822e932..78deb6b9aad84a 100644
--- a/tests/sentry/ownership/test_grammar.py
+++ b/tests/sentry/ownership/test_grammar.py
@@ -64,7 +64,7 @@ def test_load_schema():
def test_matcher_test_url():
data = {
- 'sentry.interfaces.Http': {
+ 'request': {
'url': 'http://example.com/foo.js',
}
}
@@ -79,7 +79,7 @@ def test_matcher_test_url():
def test_matcher_test_exception():
data = {
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [{
'stacktrace': {
'frames': [
@@ -102,7 +102,7 @@ def test_matcher_test_exception():
def test_matcher_test_stacktrace():
data = {
- 'sentry.interfaces.Stacktrace': {
+ 'stacktrace': {
'frames': [
{'filename': 'foo/file.py'},
{'abs_path': '/usr/local/src/other/app.py'},
diff --git a/tests/sentry/plugins/mail/tests.py b/tests/sentry/plugins/mail/tests.py
index f1413bf36b910f..87f67d7ecc891e 100644
--- a/tests/sentry/plugins/mail/tests.py
+++ b/tests/sentry/plugins/mail/tests.py
@@ -76,7 +76,7 @@ def test_notify_users_renders_interfaces_with_utf8(self, _send_mail):
event.group = group
event.project = self.project
event.message = 'hello world'
- event.interfaces = {'sentry.interfaces.Stacktrace': stacktrace}
+ event.interfaces = {'stacktrace': stacktrace}
notification = Notification(event=event)
@@ -103,7 +103,7 @@ def test_notify_users_renders_interfaces_with_utf8_fix_issue_422(self, _send_mai
event.group = group
event.project = self.project
event.message = 'Soubor ji\xc5\xbe existuje'
- event.interfaces = {'sentry.interfaces.Stacktrace': stacktrace}
+ event.interfaces = {'stacktrace': stacktrace}
notification = Notification(event=event)
@@ -532,7 +532,7 @@ def setUp(self):
def make_event_data(self, filename, url='http://example.com'):
data = {
'tags': [('level', 'error')],
- 'sentry.interfaces.Stacktrace': {
+ 'stacktrace': {
'frames': [
{
'lineno': 1,
@@ -540,7 +540,7 @@ def make_event_data(self, filename, url='http://example.com'):
},
],
},
- 'sentry.interfaces.Http': {
+ 'request': {
'url': url
},
}
diff --git a/tests/sentry/receivers/test_featureadoption.py b/tests/sentry/receivers/test_featureadoption.py
index 14f20414ec5e07..117b403614dbc2 100644
--- a/tests/sentry/receivers/test_featureadoption.py
+++ b/tests/sentry/receivers/test_featureadoption.py
@@ -343,7 +343,7 @@ def test_no_user_tracking_for_ip_address_only(self):
"extra": {
"session:duration": 40364
},
- "sentry.interfaces.Exception": {
+ "exception": {
"exc_omitted": null,
"values": [{
"stacktrace": {
@@ -374,18 +374,18 @@ def test_no_user_tracking_for_ip_address_only(self):
"module": null
}]
},
- "sentry.interfaces.Http": {
+ "request": {
"url": "https://sentry.io/katon-direct/localhost/issues/112734598/",
"headers": [
["Referer", "https://sentry.io/welcome/"],
["User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36"]
]
},
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "0.0.0.0"
},
"version": "7",
- "sentry.interfaces.Breadcrumbs": {
+ "breadcrumbs": {
"values": [
{
"category": "xhr",
@@ -443,7 +443,7 @@ def test_no_env_tracking(self):
"extra": {
"session:duration": 40364
},
- "sentry.interfaces.Exception": {
+ "exception": {
"exc_omitted": null,
"values": [{
"stacktrace": {
@@ -474,18 +474,18 @@ def test_no_env_tracking(self):
"module": null
}]
},
- "sentry.interfaces.Http": {
+ "request": {
"url": "https://sentry.io/katon-direct/localhost/issues/112734598/",
"headers": [
["Referer", "https://sentry.io/welcome/"],
["User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36"]
]
},
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "0.0.0.0"
},
"version": "7",
- "sentry.interfaces.Breadcrumbs": {
+ "breadcrumbs": {
"values": [
{
"category": "xhr",
diff --git a/tests/sentry/rules/conditions/test_event_attribute.py b/tests/sentry/rules/conditions/test_event_attribute.py
index 6e8cdaad8c4b3d..a18977f064d411 100644
--- a/tests/sentry/rules/conditions/test_event_attribute.py
+++ b/tests/sentry/rules/conditions/test_event_attribute.py
@@ -13,17 +13,17 @@ def get_event(self):
platform='php',
data={
'type': 'error',
- 'sentry.interfaces.Http': {
+ 'request': {
'method': 'GET',
'url': 'http://example.com',
},
- 'sentry.interfaces.User': {
+ 'user': {
'id': '1',
'ip_address': '127.0.0.1',
'email': '[email protected]',
'username': 'foo',
},
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'SyntaxError',
diff --git a/tests/sentry/rules/test_processor.py b/tests/sentry/rules/test_processor.py
index 5a281590e19988..bedf1dfb676249 100644
--- a/tests/sentry/rules/test_processor.py
+++ b/tests/sentry/rules/test_processor.py
@@ -65,7 +65,7 @@ def test_simple(self):
event = self.create_event(
message='biz baz',
data={
- 'sentry.interfaces.Message': {
+ 'logentry': {
'message': 'foo %s',
'formatted': 'foo bar',
'params': ['bar'],
diff --git a/tests/sentry/tasks/test_unmerge.py b/tests/sentry/tasks/test_unmerge.py
index ba4919f959f791..a40b60116d6c2d 100644
--- a/tests/sentry/tasks/test_unmerge.py
+++ b/tests/sentry/tasks/test_unmerge.py
@@ -39,7 +39,7 @@ def test_get_fingerprint():
assert get_fingerprint(
Event(
data={
- 'sentry.interfaces.Message': {
+ 'logentry': {
'message': 'Hello world',
},
},
@@ -50,7 +50,7 @@ def test_get_fingerprint():
Event(
data={
'fingerprint': ['Not hello world'],
- 'sentry.interfaces.Message': {
+ 'logentry': {
'message': 'Hello world',
},
},
@@ -246,12 +246,12 @@ def create_message_event(template, parameters, environment, release):
'metadata': {
'title': template % parameters,
},
- 'sentry.interfaces.Message': {
+ 'logentry': {
'message': template,
'params': parameters,
'formatted': template % parameters,
},
- 'sentry.interfaces.User': next(user_values),
+ 'user': next(user_values),
'tags': tags,
},
)
@@ -645,7 +645,7 @@ def collect_by_user_tag(aggregate, event):
aggregate = aggregate if aggregate is not None else set()
aggregate.add(
get_event_user_from_interface(
- event.data['sentry.interfaces.User'],
+ event.data['user'],
).tag_value,
)
return aggregate
diff --git a/tests/sentry/test_stacktraces.py b/tests/sentry/test_stacktraces.py
index 58b3fb99841fcf..711f4cba1d6f69 100644
--- a/tests/sentry/test_stacktraces.py
+++ b/tests/sentry/test_stacktraces.py
@@ -7,7 +7,7 @@ def test_stacktraces_basics():
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Stacktrace': {
+ 'stacktrace': {
'frames': [
{
'abs_path': 'http://example.com/foo.js',
@@ -35,7 +35,7 @@ def test_get_stacktraces_returns_exception_interface():
data = {
'message': 'hello',
'platform': 'javascript',
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'Error',
diff --git a/tests/sentry/utils/test_data_scrubber.py b/tests/sentry/utils/test_data_scrubber.py
index c6bc567c54f1da..bad4cccc230f7d 100644
--- a/tests/sentry/utils/test_data_scrubber.py
+++ b/tests/sentry/utils/test_data_scrubber.py
@@ -62,7 +62,7 @@ def _check_vars_sanitized(self, vars, proc):
def test_stacktrace(self):
data = {
- 'sentry.interfaces.Stacktrace': {
+ 'stacktrace': {
'frames': [{
'vars': VARS
}],
@@ -72,8 +72,8 @@ def test_stacktrace(self):
proc = SensitiveDataFilter()
proc.apply(data)
- assert 'sentry.interfaces.Stacktrace' in data
- stack = data['sentry.interfaces.Stacktrace']
+ assert 'stacktrace' in data
+ stack = data['stacktrace']
assert 'frames' in stack
assert len(stack['frames']) == 1
frame = stack['frames'][0]
@@ -82,7 +82,7 @@ def test_stacktrace(self):
def test_http(self):
data = {
- 'sentry.interfaces.Http': {
+ 'request': {
'data': VARS,
'env': VARS,
'headers': list(VARS.items()),
@@ -93,8 +93,8 @@ def test_http(self):
proc = SensitiveDataFilter()
proc.apply(data)
- assert 'sentry.interfaces.Http' in data
- http = data['sentry.interfaces.Http']
+ assert 'request' in data
+ http = data['request']
for n in ('data', 'env', 'cookies'):
assert n in http
self._check_vars_sanitized(http[n], proc)
@@ -104,7 +104,7 @@ def test_http(self):
def test_user(self):
data = {
- 'sentry.interfaces.User': {
+ 'user': {
'username': 'secret',
'data': VARS,
},
@@ -113,9 +113,9 @@ def test_user(self):
proc = SensitiveDataFilter()
proc.apply(data)
- assert 'sentry.interfaces.User' in data
- assert data['sentry.interfaces.User']['username'] == 'secret'
- self._check_vars_sanitized(data['sentry.interfaces.User']['data'], proc)
+ assert 'user' in data
+ assert data['user']['username'] == 'secret'
+ self._check_vars_sanitized(data['user']['data'], proc)
def test_extra(self):
data = {'extra': VARS}
@@ -145,7 +145,7 @@ def test_contexts(self):
def test_querystring_as_string(self):
data = {
- 'sentry.interfaces.Http': {
+ 'request': {
'query_string':
'foo=bar&password=hello&the_secret=hello'
'&a_password_here=hello&api_key=secret_key',
@@ -155,8 +155,8 @@ def test_querystring_as_string(self):
proc = SensitiveDataFilter()
proc.apply(data)
- assert 'sentry.interfaces.Http' in data
- http = data['sentry.interfaces.Http']
+ assert 'request' in data
+ http = data['request']
assert http['query_string'] == (
'foo=bar&password=%(m)s&the_secret=%(m)s'
'&a_password_here=%(m)s&api_key=%(m)s' % {
@@ -166,7 +166,7 @@ def test_querystring_as_string(self):
def test_querystring_as_string_with_partials(self):
data = {
- 'sentry.interfaces.Http': {
+ 'request': {
'query_string': 'foo=bar&password&baz=bar',
}
}
@@ -174,8 +174,8 @@ def test_querystring_as_string_with_partials(self):
proc = SensitiveDataFilter()
proc.apply(data)
- assert 'sentry.interfaces.Http' in data
- http = data['sentry.interfaces.Http']
+ assert 'request' in data
+ http = data['request']
assert http['query_string'] == 'foo=bar&password&baz=bar'
def test_sanitize_additional_sensitive_fields(self):
@@ -260,15 +260,15 @@ def test_sanitize_url(self):
def test_sanitize_http_body(self):
data = {
- 'sentry.interfaces.Http': {
+ 'request': {
'data': '{"email":"[email protected]","password":"zzzzz"}',
},
}
proc = SensitiveDataFilter()
proc.apply(data)
- assert 'sentry.interfaces.Http' in data
- http = data['sentry.interfaces.Http']
+ assert 'request' in data
+ http = data['request']
assert http['data'] == FILTER_MASK
def test_does_not_fail_on_non_string(self):
@@ -431,7 +431,7 @@ def test_doesnt_scrub_not_scrubbed(self):
def test_csp_blocked_uri(self):
data = {
- 'sentry.interfaces.Csp': {
+ 'csp': {
'blocked_uri': 'https://example.com/?foo=4571234567890111&bar=baz',
}
}
@@ -439,6 +439,6 @@ def test_csp_blocked_uri(self):
proc = SensitiveDataFilter()
proc.apply(data)
- assert 'sentry.interfaces.Csp' in data
- csp = data['sentry.interfaces.Csp']
+ assert 'csp' in data
+ csp = data['csp']
assert csp['blocked_uri'] == 'https://example.com/?foo=[Filtered]&bar=baz'
diff --git a/tests/sentry/utils/test_sdk.py b/tests/sentry/utils/test_sdk.py
index c1868615546244..877a491cab0897 100644
--- a/tests/sentry/utils/test_sdk.py
+++ b/tests/sentry/utils/test_sdk.py
@@ -21,7 +21,7 @@ def test_simple(self):
event = Event.objects.get()
assert event.project_id == settings.SENTRY_PROJECT
assert event.event_id == event_id
- assert event.data['sentry.interfaces.Message']['message'] == \
+ assert event.data['logentry']['message'] == \
'internal client test'
def test_encoding(self):
@@ -38,5 +38,5 @@ class NotJSONSerializable():
event = Event.objects.get()
assert event.project_id == settings.SENTRY_PROJECT
- assert event.data['sentry.interfaces.Message']['message'] == 'check the req'
+ assert event.data['logentry']['message'] == 'check the req'
assert 'NotJSONSerializable' in event.data['extra']['request']
diff --git a/tests/sentry/web/api/tests.py b/tests/sentry/web/api/tests.py
index 6f5ae442d3e1a1..8898e0ba59dab2 100644
--- a/tests/sentry/web/api/tests.py
+++ b/tests/sentry/web/api/tests.py
@@ -234,10 +234,10 @@ def test_request_with_filtered_release(self):
body = {
"release": "abcdefg",
"message": "foo bar",
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "127.0.0.1"
},
- "sentry.interfaces.Http": {
+ "request": {
"method": "GET",
"url": "http://example.com/",
"env": {
@@ -253,10 +253,10 @@ def test_request_with_filtered_error(self):
body = {
"release": "abcdefg",
"message": "foo bar",
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "127.0.0.1"
},
- "sentry.interfaces.Http": {
+ "request": {
"method": "GET",
"url": "http://example.com/",
"env": {
@@ -272,10 +272,10 @@ def test_request_with_invalid_ip(self):
body = {
"release": "abcdefg",
"message": "foo bar",
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "127.0.0.1"
},
- "sentry.interfaces.Http": {
+ "request": {
"method": "GET",
"url": "http://example.com/",
"env": {
@@ -291,10 +291,10 @@ def test_request_with_invalid_release(self):
body = {
"release": "1.3.2",
"message": "foo bar",
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "127.0.0.1"
},
- "sentry.interfaces.Http": {
+ "request": {
"method": "GET",
"url": "http://example.com/",
"env": {
@@ -310,10 +310,10 @@ def test_request_with_short_release_globbing(self):
body = {
"release": "1.3.2",
"message": "foo bar",
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "127.0.0.1"
},
- "sentry.interfaces.Http": {
+ "request": {
"method": "GET",
"url": "http://example.com/",
"env": {
@@ -329,10 +329,10 @@ def test_request_with_longer_release_globbing(self):
body = {
"release": "2.1.3",
"message": "foo bar",
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "127.0.0.1"
},
- "sentry.interfaces.Http": {
+ "request": {
"method": "GET",
"url": "http://example.com/",
"env": {
@@ -349,17 +349,17 @@ def test_request_with_invalid_error_messages(self):
)
body = {
"release": "abcdefg",
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "127.0.0.1"
},
- "sentry.interfaces.Http": {
+ "request": {
"method": "GET",
"url": "http://example.com/",
"env": {
"REMOTE_ADDR": "127.0.0.1"
}
},
- "sentry.interfaces.Message": {
+ "logentry": {
"formatted": "ZeroDivisionError: integer division or modulo by zero",
"message": "%s: integer division or modulo by zero",
},
@@ -374,17 +374,17 @@ def test_request_with_beggining_glob(self):
)
body = {
"release": "abcdefg",
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "127.0.0.1"
},
- "sentry.interfaces.Http": {
+ "request": {
"method": "GET",
"url": "http://example.com/",
"env": {
"REMOTE_ADDR": "127.0.0.1"
}
},
- "sentry.interfaces.Message": {
+ "logentry": {
"message": "ZeroDivisionError: integer division or modulo by zero",
"formatted": "",
},
@@ -402,10 +402,10 @@ def test_scrubs_ip_address(self, mock_insert_data_to_database):
"version": "3.23.3",
"client_ip": "127.0.0.1"
},
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "127.0.0.1"
},
- "sentry.interfaces.Http": {
+ "request": {
"method": "GET",
"url": "http://example.com/",
"env": {
@@ -417,8 +417,8 @@ def test_scrubs_ip_address(self, mock_insert_data_to_database):
assert resp.status_code == 200, (resp.status_code, resp.content)
call_data = mock_insert_data_to_database.call_args[0][0]
- assert not call_data['sentry.interfaces.User'].get('ip_address')
- assert not call_data['sentry.interfaces.Http']['env'].get('REMOTE_ADDR')
+ assert not call_data['user'].get('ip_address')
+ assert not call_data['request']['env'].get('REMOTE_ADDR')
assert not call_data['sdk'].get('client_ip')
@mock.patch('sentry.coreapi.ClientApiHelper.insert_data_to_database')
@@ -427,10 +427,10 @@ def test_scrubs_org_ip_address_override(self, mock_insert_data_to_database):
self.project.update_option('sentry:scrub_ip_address', False)
body = {
"message": "foo bar",
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "127.0.0.1"
},
- "sentry.interfaces.Http": {
+ "request": {
"method": "GET",
"url": "http://example.com/",
"env": {
@@ -442,8 +442,8 @@ def test_scrubs_org_ip_address_override(self, mock_insert_data_to_database):
assert resp.status_code == 200, (resp.status_code, resp.content)
call_data = mock_insert_data_to_database.call_args[0][0]
- assert not call_data['sentry.interfaces.User'].get('ip_address')
- assert not call_data['sentry.interfaces.Http']['env'].get('REMOTE_ADDR')
+ assert not call_data['user'].get('ip_address')
+ assert not call_data['request']['env'].get('REMOTE_ADDR')
@mock.patch('sentry.coreapi.ClientApiHelper.insert_data_to_database')
def test_scrub_data_off(self, mock_insert_data_to_database):
@@ -451,10 +451,10 @@ def test_scrub_data_off(self, mock_insert_data_to_database):
self.project.update_option('sentry:scrub_defaults', False)
body = {
"message": "foo bar",
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "127.0.0.1"
},
- "sentry.interfaces.Http": {
+ "request": {
"method": "GET",
"url": "http://example.com/",
"data": "password=lol&foo=1&bar=2&baz=3"
@@ -464,7 +464,7 @@ def test_scrub_data_off(self, mock_insert_data_to_database):
assert resp.status_code == 200, (resp.status_code, resp.content)
call_data = mock_insert_data_to_database.call_args[0][0]
- assert call_data['sentry.interfaces.Http']['data'] == {
+ assert call_data['request']['data'] == {
'password': ['lol'],
'foo': ['1'],
'bar': ['2'],
@@ -477,10 +477,10 @@ def test_scrub_data_on(self, mock_insert_data_to_database):
self.project.update_option('sentry:scrub_defaults', False)
body = {
"message": "foo bar",
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "127.0.0.1"
},
- "sentry.interfaces.Http": {
+ "request": {
"method": "GET",
"url": "http://example.com/",
"data": "password=lol&foo=1&bar=2&baz=3"
@@ -490,7 +490,7 @@ def test_scrub_data_on(self, mock_insert_data_to_database):
assert resp.status_code == 200, (resp.status_code, resp.content)
call_data = mock_insert_data_to_database.call_args[0][0]
- assert call_data['sentry.interfaces.Http']['data'] == {
+ assert call_data['request']['data'] == {
'password': ['lol'],
'foo': ['1'],
'bar': ['2'],
@@ -503,10 +503,10 @@ def test_scrub_data_defaults(self, mock_insert_data_to_database):
self.project.update_option('sentry:scrub_defaults', True)
body = {
"message": "foo bar",
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "127.0.0.1"
},
- "sentry.interfaces.Http": {
+ "request": {
"method": "GET",
"url": "http://example.com/",
"data": "password=lol&foo=1&bar=2&baz=3"
@@ -516,7 +516,7 @@ def test_scrub_data_defaults(self, mock_insert_data_to_database):
assert resp.status_code == 200, (resp.status_code, resp.content)
call_data = mock_insert_data_to_database.call_args[0][0]
- assert call_data['sentry.interfaces.Http']['data'] == {
+ assert call_data['request']['data'] == {
'password': ['[Filtered]'],
'foo': ['1'],
'bar': ['2'],
@@ -530,10 +530,10 @@ def test_scrub_data_sensitive_fields(self, mock_insert_data_to_database):
self.project.update_option('sentry:sensitive_fields', ['foo', 'bar'])
body = {
"message": "foo bar",
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "127.0.0.1"
},
- "sentry.interfaces.Http": {
+ "request": {
"method": "GET",
"url": "http://example.com/",
"data": "password=lol&foo=1&bar=2&baz=3"
@@ -543,7 +543,7 @@ def test_scrub_data_sensitive_fields(self, mock_insert_data_to_database):
assert resp.status_code == 200, (resp.status_code, resp.content)
call_data = mock_insert_data_to_database.call_args[0][0]
- assert call_data['sentry.interfaces.Http']['data'] == {
+ assert call_data['request']['data'] == {
'password': ['[Filtered]'],
'foo': ['[Filtered]'],
'bar': ['[Filtered]'],
@@ -558,10 +558,10 @@ def test_scrub_data_org_override(self, mock_insert_data_to_database):
self.project.update_option('sentry:scrub_defaults', False)
body = {
"message": "foo bar",
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "127.0.0.1"
},
- "sentry.interfaces.Http": {
+ "request": {
"method": "GET",
"url": "http://example.com/",
"data": "password=lol&foo=1&bar=2&baz=3"
@@ -571,7 +571,7 @@ def test_scrub_data_org_override(self, mock_insert_data_to_database):
assert resp.status_code == 200, (resp.status_code, resp.content)
call_data = mock_insert_data_to_database.call_args[0][0]
- assert call_data['sentry.interfaces.Http']['data'] == {
+ assert call_data['request']['data'] == {
'password': ['[Filtered]'],
'foo': ['1'],
'bar': ['2'],
@@ -586,10 +586,10 @@ def test_scrub_data_org_override_sensitive_fields(self, mock_insert_data_to_data
self.project.update_option('sentry:sensitive_fields', ['foo', 'bar'])
body = {
"message": "foo bar",
- "sentry.interfaces.User": {
+ "user": {
"ip_address": "127.0.0.1"
},
- "sentry.interfaces.Http": {
+ "request": {
"method": "GET",
"url": "http://example.com/",
"data": "password=lol&foo=1&bar=2&baz=3"
@@ -599,7 +599,7 @@ def test_scrub_data_org_override_sensitive_fields(self, mock_insert_data_to_data
assert resp.status_code == 200, (resp.status_code, resp.content)
call_data = mock_insert_data_to_database.call_args[0][0]
- assert call_data['sentry.interfaces.Http']['data'] == {
+ assert call_data['request']['data'] == {
'password': ['[Filtered]'],
'foo': ['[Filtered]'],
'bar': ['[Filtered]'],
@@ -626,7 +626,7 @@ def test_accepted_signal(self):
event_accepted.connect(mock_event_accepted)
- resp = self._postWithHeader({'sentry.interfaces.Message': {'message': u'hello'}})
+ resp = self._postWithHeader({'logentry': {'message': u'hello'}})
assert resp.status_code == 200, resp.content
@@ -646,7 +646,7 @@ def test_dropped_signal(self, mock_is_rate_limited):
event_dropped.connect(mock_event_dropped)
- resp = self._postWithHeader({'sentry.interfaces.Message': {'message': u'hello'}})
+ resp = self._postWithHeader({'logentry': {'message': u'hello'}})
assert resp.status_code == 429, resp.content
@@ -666,7 +666,7 @@ def test_filtered_signal(self, mock_should_filter):
event_filtered.connect(mock_event_filtered)
- resp = self._postWithHeader({'sentry.interfaces.Message': {'message': u'hello'}})
+ resp = self._postWithHeader({'logentry': {'message': u'hello'}})
assert resp.status_code == 403, resp.content
diff --git a/tests/snuba/tagstore/test_tagstore_backend.py b/tests/snuba/tagstore/test_tagstore_backend.py
index 61d260a2262f99..8836bbe53acea6 100644
--- a/tests/snuba/tagstore/test_tagstore_backend.py
+++ b/tests/snuba/tagstore/test_tagstore_backend.py
@@ -56,7 +56,7 @@ def setUp(self):
'sentry:release': 100 * r,
'sentry:user': u"id:user{}".format(r),
},
- 'sentry.interfaces.User': {
+ 'user': {
'id': u"user{}".format(r),
'email': u"user{}@sentry.io".format(r)
}
@@ -76,7 +76,7 @@ def setUp(self):
'environment': self.proj1env1.name,
'sentry:user': "id:user1",
},
- 'sentry.interfaces.User': {
+ 'user': {
'id': "user1"
}
},
diff --git a/tests/snuba/test_organization_discover_query.py b/tests/snuba/test_organization_discover_query.py
index a9ec5875d97ca1..a63ddf55b1c508 100644
--- a/tests/snuba/test_organization_discover_query.py
+++ b/tests/snuba/test_organization_discover_query.py
@@ -31,7 +31,7 @@ def setUp(self):
datetime=one_second_ago,
tags={'environment': 'production'},
data={
- 'sentry.interfaces.Exception': {
+ 'exception': {
'values': [
{
'type': 'ValidationError',
diff --git a/tests/snuba/tsdb/test_tsdb_backend.py b/tests/snuba/tsdb/test_tsdb_backend.py
index 39f90caedff178..f8f9fcdc93f638 100644
--- a/tests/snuba/tsdb/test_tsdb_backend.py
+++ b/tests/snuba/tsdb/test_tsdb_backend.py
@@ -124,7 +124,7 @@ def setUp(self):
'sentry:user': u'id:user{}'.format(r // 3300),
'sentry:release': six.text_type(r // 3600) * 10, # 1 per hour
},
- 'sentry.interfaces.User': {
+ 'user': {
# change every 55 min so some hours have 1 user, some have 2
'id': u"user{}".format(r // 3300),
'email': u"user{}@sentry.io".format(r)
|
1da8737bcb1a016382e5c7757d913f19a3d0e217
|
2019-05-28 22:29:00
|
Evan Purkhiser
|
ref(onboarding): Simplify SetupChoices component (#13398)
| false
|
Simplify SetupChoices component (#13398)
|
ref
|
diff --git a/src/sentry/static/sentry/app/views/onboarding/projectSetup/setupChoices.jsx b/src/sentry/static/sentry/app/views/onboarding/projectSetup/setupChoices.jsx
index 63af66f7769060..67841ce94a0308 100644
--- a/src/sentry/static/sentry/app/views/onboarding/projectSetup/setupChoices.jsx
+++ b/src/sentry/static/sentry/app/views/onboarding/projectSetup/setupChoices.jsx
@@ -7,39 +7,28 @@ const itemsShape = PropTypes.shape({
title: PropTypes.string.isRequired,
});
-/**
- * Visually fancy choice-card component with an animated hover effect that
- * follows the focused choice. Uses react-pose to handle animations of the
- * background element by passing the computed rect
- */
-class SetupChoices extends React.Component {
- static propTypes = {
- choices: PropTypes.arrayOf(itemsShape),
- selectedChoice: PropTypes.string,
- onSelect: PropTypes.func,
- };
+const SetupChoices = ({choices, selectedChoice, onSelect}) => (
+ <NavTabs underlined={true}>
+ {choices.map(({id, title}) => (
+ <li key={id} className={id === selectedChoice ? 'active' : null}>
+ <a
+ href="#"
+ onClick={e => {
+ onSelect(id);
+ e.preventDefault();
+ }}
+ >
+ {title}
+ </a>
+ </li>
+ ))}
+ </NavTabs>
+);
- render() {
- const {choices, selectedChoice, onSelect} = this.props;
-
- return (
- <NavTabs underlined={true}>
- {choices.map(({id, title}) => (
- <li key={id} className={id === selectedChoice ? 'active' : null}>
- <a
- href="#"
- onClick={e => {
- onSelect(id);
- e.preventDefault();
- }}
- >
- {title}
- </a>
- </li>
- ))}
- </NavTabs>
- );
- }
-}
+SetupChoices.propTypes = {
+ choices: PropTypes.arrayOf(itemsShape),
+ selectedChoice: PropTypes.string,
+ onSelect: PropTypes.func,
+};
export default SetupChoices;
|
370f111761e272d0c7d5f96a74549fdf5e599466
|
2023-03-29 03:04:09
|
Evan Purkhiser
|
fix(ui): Size of auth token remove buttons (#46474)
| false
|
Size of auth token remove buttons (#46474)
|
fix
|
diff --git a/static/app/views/settings/account/apiTokenRow.tsx b/static/app/views/settings/account/apiTokenRow.tsx
index 4913b25447db54..e23e7aee64e3e9 100644
--- a/static/app/views/settings/account/apiTokenRow.tsx
+++ b/static/app/views/settings/account/apiTokenRow.tsx
@@ -25,7 +25,6 @@ function ApiTokenRow({token, onRemove}: Props) {
</TextCopyInput>
</InputWrapper>
<Button
- size="sm"
onClick={() => onRemove(token)}
icon={<IconSubtract isCircled size="xs" />}
>
|
eb934a4fcfe5df371f461e4cb321dd690be0398a
|
2022-01-27 05:31:20
|
Leander Rodrigues
|
ref(codeowners): Bug fixing on results for SelectAsync settings form (#31383)
| false
|
Bug fixing on results for SelectAsync settings form (#31383)
|
ref
|
diff --git a/static/app/components/forms/selectAsyncControl.tsx b/static/app/components/forms/selectAsyncControl.tsx
index be87a044df1609..f431b24968ab2b 100644
--- a/static/app/components/forms/selectAsyncControl.tsx
+++ b/static/app/components/forms/selectAsyncControl.tsx
@@ -4,22 +4,25 @@ import debounce from 'lodash/debounce';
import {addErrorMessage} from 'sentry/actionCreators/indicator';
import {Client} from 'sentry/api';
+import SelectControl, {
+ ControlProps,
+ GeneralSelectValue,
+} from 'sentry/components/forms/selectControl';
import {t} from 'sentry/locale';
import handleXhrErrorResponse from 'sentry/utils/handleXhrErrorResponse';
-import SelectControl, {ControlProps, GeneralSelectValue} from './selectControl';
-
-type Result = {
+export type Result = {
value: string;
label: string;
};
-type Props = {
+export type SelectAsyncControlProps = {
url: string;
onResults: (data: any) => Result[]; // TODO(ts): Improve data type
onQuery: (query: string | undefined) => {};
forwardedRef: React.Ref<ReactSelect<GeneralSelectValue>>;
value: ControlProps['value'];
+ defaultOptions?: boolean | GeneralSelectValue[];
};
type State = {
@@ -27,11 +30,12 @@ type State = {
};
/**
- * Performs an API request to `url` when menu is initially opened
+ * Performs an API request to `url` to fetch the options
*/
-class SelectAsyncControl extends React.Component<Props> {
+class SelectAsyncControl extends React.Component<SelectAsyncControlProps> {
static defaultProps = {
placeholder: '--',
+ defaultOptions: true,
};
constructor(props) {
@@ -101,7 +105,7 @@ class SelectAsyncControl extends React.Component<Props> {
};
render() {
- const {value, forwardedRef, ...props} = this.props;
+ const {value, forwardedRef, defaultOptions, ...props} = this.props;
return (
<SelectControl
// The key is used as a way to force a reload of the options:
@@ -109,7 +113,7 @@ class SelectAsyncControl extends React.Component<Props> {
key={value}
ref={forwardedRef}
value={value}
- defaultOptions
+ defaultOptions={defaultOptions}
loadOptions={this.handleLoadOptions}
onInputChange={this.handleInputChange}
async
diff --git a/static/app/components/integrationExternalMappingForm.tsx b/static/app/components/integrationExternalMappingForm.tsx
index 691ed2a319608e..524fb9189c017d 100644
--- a/static/app/components/integrationExternalMappingForm.tsx
+++ b/static/app/components/integrationExternalMappingForm.tsx
@@ -2,25 +2,30 @@ import {Component} from 'react';
import styled from '@emotion/styled';
import capitalize from 'lodash/capitalize';
+import {SelectAsyncControlProps} from 'sentry/components/forms/selectAsyncControl';
import {t, tct} from 'sentry/locale';
import {ExternalActorMapping, Integration} from 'sentry/types';
-import {getExternalActorEndpointDetails} from 'sentry/utils/integrationUtil';
+import {
+ getExternalActorEndpointDetails,
+ sentryNameToOption,
+} from 'sentry/utils/integrationUtil';
import {FieldFromConfig} from 'sentry/views/settings/components/forms';
import Form from 'sentry/views/settings/components/forms/form';
import FormModel from 'sentry/views/settings/components/forms/model';
import {Field} from 'sentry/views/settings/components/forms/type';
-type Props = Pick<Form['props'], 'onCancel' | 'onSubmitSuccess' | 'onSubmitError'> & {
- integration: Integration;
- mapping?: ExternalActorMapping;
- type: 'user' | 'team';
- getBaseFormEndpoint: (mapping?: ExternalActorMapping) => string;
- sentryNamesMapper: (v: any) => {id: string; name: string}[];
- dataEndpoint: string;
- onResults?: (data: any, mappingKey?: string) => void;
- isInline?: boolean;
- mappingKey?: string;
-};
+type Props = Pick<Form['props'], 'onCancel' | 'onSubmitSuccess' | 'onSubmitError'> &
+ Pick<SelectAsyncControlProps, 'defaultOptions'> & {
+ integration: Integration;
+ mapping?: ExternalActorMapping;
+ type: 'user' | 'team';
+ getBaseFormEndpoint: (mapping?: ExternalActorMapping) => string;
+ sentryNamesMapper: (v: any) => {id: string; name: string}[];
+ dataEndpoint: string;
+ onResults?: (data: any, mappingKey?: string) => void;
+ isInline?: boolean;
+ mappingKey?: string;
+ };
export default class IntegrationExternalMappingForm extends Component<Props> {
model = new FormModel();
@@ -34,6 +39,25 @@ export default class IntegrationExternalMappingForm extends Component<Props> {
};
}
+ getDefaultOptions(mapping?: ExternalActorMapping) {
+ const {defaultOptions, type} = this.props;
+ if (typeof defaultOptions === 'boolean') {
+ return defaultOptions;
+ }
+ const options = [...(defaultOptions ?? [])];
+ if (!mapping) {
+ return options;
+ }
+ // For organizations with >100 entries, we want to make sure their
+ // saved mapping gets populated in the results if it wouldn't have
+ // been in the initial 100 API results, which is why we add it here
+ const mappingId = mapping[`${type}Id`];
+ const mappingOption = options.find(({value}) => mappingId && value === mappingId);
+ return !!mappingOption
+ ? options
+ : [{value: mappingId, label: mapping.sentryName}, ...options];
+ }
+
get formFields(): Field[] {
const {
dataEndpoint,
@@ -44,8 +68,6 @@ export default class IntegrationExternalMappingForm extends Component<Props> {
sentryNamesMapper,
type,
} = this.props;
- const optionMapper = sentryNames =>
- sentryNames.map(({name, id}) => ({value: id, label: name}));
const fields: Field[] = [
{
name: `${type}Id`,
@@ -54,27 +76,10 @@ export default class IntegrationExternalMappingForm extends Component<Props> {
label: isInline ? undefined : tct('Sentry [type]', {type: capitalize(type)}),
placeholder: t(`Select Sentry ${capitalize(type)}`),
url: dataEndpoint,
+ defaultOptions: this.getDefaultOptions(mapping),
onResults: result => {
onResults?.(result, isInline ? mapping?.externalName : mappingKey);
- // TODO(Leander): The code below only fixes the problem when viewed, not when edited
- // Pagination still has bugs for results not on initial return of the query
-
- // For organizations with >100 entries, we want to make sure their
- // saved mapping gets populated in the results if it wouldn't have
- // been in the initial 100 API results, which is why we add it here
- if (
- mapping &&
- !result.find(entry => {
- const id = type === 'user' ? entry.user.id : entry.id;
- return id === mapping[`${type}Id`];
- })
- ) {
- return optionMapper([
- {id: mapping[`${type}Id`], name: mapping.sentryName},
- ...sentryNamesMapper(result),
- ]);
- }
- return optionMapper(sentryNamesMapper(result));
+ return sentryNamesMapper(result).map(sentryNameToOption);
},
},
];
diff --git a/static/app/components/integrationExternalMappings.tsx b/static/app/components/integrationExternalMappings.tsx
index 3c5e40f2937f55..b73c5b73083897 100644
--- a/static/app/components/integrationExternalMappings.tsx
+++ b/static/app/components/integrationExternalMappings.tsx
@@ -20,7 +20,11 @@ import EmptyMessage from 'sentry/views/settings/components/emptyMessage';
type Props = Pick<
IntegrationExternalMappingForm['props'],
- 'dataEndpoint' | 'getBaseFormEndpoint' | 'sentryNamesMapper' | 'onResults'
+ | 'dataEndpoint'
+ | 'getBaseFormEndpoint'
+ | 'sentryNamesMapper'
+ | 'onResults'
+ | 'defaultOptions'
> & {
organization: Organization;
integration: Integration;
@@ -41,6 +45,7 @@ class IntegrationExternalMappings extends Component<Props, State> {
dataEndpoint,
sentryNamesMapper,
onResults,
+ defaultOptions,
} = this.props;
const mappingName = mapping.sentryName ?? '';
return hasAccess ? (
@@ -53,6 +58,7 @@ class IntegrationExternalMappings extends Component<Props, State> {
sentryNamesMapper={sentryNamesMapper}
onResults={onResults}
isInline
+ defaultOptions={defaultOptions}
/>
) : (
mappingName
diff --git a/static/app/utils/integrationUtil.tsx b/static/app/utils/integrationUtil.tsx
index f6c92ba67c58ec..1e99510e72a175 100644
--- a/static/app/utils/integrationUtil.tsx
+++ b/static/app/utils/integrationUtil.tsx
@@ -1,6 +1,7 @@
import capitalize from 'lodash/capitalize';
import * as qs from 'query-string';
+import {Result} from 'sentry/components/forms/selectAsyncControl';
import {
IconBitbucket,
IconGeneric,
@@ -246,3 +247,8 @@ export const getExternalActorEndpointDetails = (
apiEndpoint: isValidMapping ? `${baseEndpoint}${mapping.id}/` : baseEndpoint,
};
};
+
+export const sentryNameToOption = ({id, name}): Result => ({
+ value: id,
+ label: name,
+});
diff --git a/static/app/views/organizationIntegrations/integrationExternalTeamMappings.tsx b/static/app/views/organizationIntegrations/integrationExternalTeamMappings.tsx
index 822a43fa638ed4..8214965a2d02cc 100644
--- a/static/app/views/organizationIntegrations/integrationExternalTeamMappings.tsx
+++ b/static/app/views/organizationIntegrations/integrationExternalTeamMappings.tsx
@@ -1,5 +1,6 @@
import {Fragment} from 'react';
import {withRouter, WithRouterProps} from 'react-router';
+import uniqBy from 'lodash/uniqBy';
import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
import {openModal} from 'sentry/actionCreators/modal';
@@ -8,6 +9,7 @@ import IntegrationExternalMappingForm from 'sentry/components/integrationExterna
import IntegrationExternalMappings from 'sentry/components/integrationExternalMappings';
import {t} from 'sentry/locale';
import {ExternalActorMapping, Integration, Organization, Team} from 'sentry/types';
+import {sentryNameToOption} from 'sentry/utils/integrationUtil';
import withOrganization from 'sentry/utils/withOrganization';
type Props = AsyncComponent['props'] &
@@ -18,6 +20,7 @@ type Props = AsyncComponent['props'] &
type State = AsyncComponent['state'] & {
teams: Team[];
+ initialResults: Team[];
queryResults: {
// For inline forms, the mappingKey will be the external name (since multiple will be rendered at one time)
// For the modal form, the mappingKey will be this.modalMappingKey (since only one modal form is rendered at any time)
@@ -30,6 +33,7 @@ class IntegrationExternalTeamMappings extends AsyncComponent<Props, State> {
return {
...super.getDefaultState(),
teams: [],
+ initialResults: [],
queryResults: {},
};
}
@@ -37,11 +41,14 @@ class IntegrationExternalTeamMappings extends AsyncComponent<Props, State> {
getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
const {organization, location} = this.props;
return [
+ // We paginate on this query, since we're filtering by hasExternalTeams:true
[
'teams',
`/organizations/${organization.slug}/teams/`,
{query: {...location?.query, query: 'hasExternalTeams:true'}},
],
+ // We use this query as defaultOptions to reduce identical API calls
+ ['initialResults', `/organizations/${organization.slug}/teams/`],
];
}
@@ -86,22 +93,31 @@ class IntegrationExternalTeamMappings extends AsyncComponent<Props, State> {
return externalTeamMappings.sort((a, b) => parseInt(a.id, 10) - parseInt(b.id, 10));
}
- modalMappingKey = 'MODAL_RESULTS';
+ modalMappingKey = '__MODAL_RESULTS__';
get dataEndpoint() {
const {organization} = this.props;
return `/organizations/${organization.slug}/teams/`;
}
+ get defaultTeamOptions() {
+ const {initialResults} = this.state;
+ return this.sentryNamesMapper(initialResults).map(sentryNameToOption);
+ }
+
getBaseFormEndpoint(mapping?: ExternalActorMapping) {
if (!mapping) {
return '';
}
const {organization} = this.props;
- const {queryResults} = this.state;
- const mappingResults =
+ const {queryResults, initialResults} = this.state;
+ const fieldResults =
queryResults[mapping.externalName] ?? queryResults[this.modalMappingKey];
- const team = mappingResults?.find(item => item.id === mapping.teamId);
+ const team =
+ // First, search for the team in the query results...
+ fieldResults?.find(item => item.id === mapping.teamId) ??
+ // Then in the initial results, if nothing was found.
+ initialResults?.find(item => item.id === mapping.teamId);
return `/teams/${organization.slug}/${team?.slug ?? ''}/external-teams/`;
}
@@ -109,12 +125,26 @@ class IntegrationExternalTeamMappings extends AsyncComponent<Props, State> {
return teams.map(({id, slug}) => ({id, name: slug}));
}
+ /**
+ * This method combines the results from searches made on a form dropping repeated entries
+ * that have identical 'id's. This is because we need the result of the the search query when
+ * the user submits to get the team slug, but it won't always be the last query they've made.
+ *
+ * If they search (but not select) after making a selection, and we didn't keep a running collection of results,
+ * we wouldn't have the team to generate the endpoint from.
+ */
+ combineResultsById = (resultList1, resultList2) => {
+ return uniqBy([...resultList1, ...resultList2], 'id');
+ };
+
handleResults = (results, mappingKey?: string) => {
if (mappingKey) {
+ const {queryResults} = this.state;
this.setState({
queryResults: {
- ...this.state.queryResults,
- [mappingKey]: results,
+ ...queryResults,
+ // Ensure we always have a team to pull the slug from
+ [mappingKey]: this.combineResultsById(results, queryResults[mappingKey] ?? []),
},
});
}
@@ -131,6 +161,7 @@ class IntegrationExternalTeamMappings extends AsyncComponent<Props, State> {
integration={integration}
dataEndpoint={this.dataEndpoint}
getBaseFormEndpoint={map => this.getBaseFormEndpoint(map)}
+ defaultOptions={this.defaultTeamOptions}
mapping={mapping}
mappingKey={this.modalMappingKey}
sentryNamesMapper={this.sentryNamesMapper}
@@ -157,6 +188,7 @@ class IntegrationExternalTeamMappings extends AsyncComponent<Props, State> {
mappings={this.mappings}
dataEndpoint={this.dataEndpoint}
getBaseFormEndpoint={mapping => this.getBaseFormEndpoint(mapping)}
+ defaultOptions={this.defaultTeamOptions}
sentryNamesMapper={this.sentryNamesMapper}
onCreate={this.openModal}
onDelete={this.handleDelete}
diff --git a/static/app/views/organizationIntegrations/integrationExternalUserMappings.tsx b/static/app/views/organizationIntegrations/integrationExternalUserMappings.tsx
index e470b0aafa0f72..c55340b9106be8 100644
--- a/static/app/views/organizationIntegrations/integrationExternalUserMappings.tsx
+++ b/static/app/views/organizationIntegrations/integrationExternalUserMappings.tsx
@@ -14,6 +14,7 @@ import {
Member,
Organization,
} from 'sentry/types';
+import {sentryNameToOption} from 'sentry/utils/integrationUtil';
import withOrganization from 'sentry/utils/withOrganization';
type Props = AsyncComponent['props'] &
@@ -24,17 +25,21 @@ type Props = AsyncComponent['props'] &
type State = AsyncComponent['state'] & {
members: (Member & {externalUsers: ExternalUser[]})[];
+ initialResults: Member[];
};
class IntegrationExternalUserMappings extends AsyncComponent<Props, State> {
getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
const {organization} = this.props;
return [
+ // We paginate on this query, since we're filtering by hasExternalUsers:true
[
'members',
`/organizations/${organization.slug}/members/`,
{query: {query: 'hasExternalUsers:true', expand: 'externalUsers'}},
],
+ // We use this query as defaultOptions to reduce identical API calls
+ ['initialResults', `/organizations/${organization.slug}/members/`],
];
}
@@ -88,6 +93,11 @@ class IntegrationExternalUserMappings extends AsyncComponent<Props, State> {
return `/organizations/${organization.slug}/external-users/`;
}
+ get defaultUserOptions() {
+ const {initialResults} = this.state;
+ return this.sentryNamesMapper(initialResults).map(sentryNameToOption);
+ }
+
sentryNamesMapper(members: Member[]) {
return members
.filter(member => member.user)
@@ -108,6 +118,7 @@ class IntegrationExternalUserMappings extends AsyncComponent<Props, State> {
integration={integration}
dataEndpoint={this.dataEndpoint}
getBaseFormEndpoint={() => this.baseFormEndpoint}
+ defaultOptions={this.defaultUserOptions}
mapping={mapping}
sentryNamesMapper={this.sentryNamesMapper}
onCancel={closeModal}
@@ -133,6 +144,7 @@ class IntegrationExternalUserMappings extends AsyncComponent<Props, State> {
mappings={this.mappings}
dataEndpoint={this.dataEndpoint}
getBaseFormEndpoint={() => this.baseFormEndpoint}
+ defaultOptions={this.defaultUserOptions}
sentryNamesMapper={this.sentryNamesMapper}
onCreate={this.openModal}
onDelete={this.handleDelete}
diff --git a/static/app/views/settings/components/forms/selectAsyncField.tsx b/static/app/views/settings/components/forms/selectAsyncField.tsx
index 0bd4804c04b32f..71cc40a1104c2a 100644
--- a/static/app/views/settings/components/forms/selectAsyncField.tsx
+++ b/static/app/views/settings/components/forms/selectAsyncField.tsx
@@ -1,26 +1,38 @@
import * as React from 'react';
-import SelectAsyncControl from 'sentry/components/forms/selectAsyncControl';
+import SelectAsyncControl, {Result} from 'sentry/components/forms/selectAsyncControl';
import InputField from 'sentry/views/settings/components/forms/inputField';
// projects can be passed as a direct prop as well
type Props = Omit<InputField['props'], 'highlighted' | 'visible' | 'required'>;
+import {GeneralSelectValue} from 'sentry/components/forms/selectControl';
export type SelectAsyncFieldProps = React.ComponentPropsWithoutRef<
typeof SelectAsyncControl
> &
Props;
-class SelectAsyncField extends React.Component<SelectAsyncFieldProps> {
+type SelectAsyncFieldState = {
+ results: Result[];
+ latestSelection?: GeneralSelectValue;
+};
+class SelectAsyncField extends React.Component<
+ SelectAsyncFieldProps,
+ SelectAsyncFieldState
+> {
state = {
results: [],
+ latestSelection: undefined,
};
+
+ componentDidMount() {}
+
// need to map the option object to the value
// this is essentially the same code from ./selectField handleChange()
handleChange = (
onBlur: Props['onBlur'],
onChange: Props['onChange'],
- optionObj: {value: string | any[]},
+ optionObj: GeneralSelectValue,
event: React.MouseEvent
) => {
let {value} = optionObj;
@@ -32,18 +44,26 @@ class SelectAsyncField extends React.Component<SelectAsyncFieldProps> {
} else if (!Array.isArray(optionObj)) {
value = optionObj.value;
}
+ this.setState({latestSelection: optionObj});
onChange?.(value, event);
onBlur?.(value, event);
};
- findValue(propsValue) {
+ findValue(propsValue: string): GeneralSelectValue {
+ const {defaultOptions} = this.props;
+ const {results, latestSelection} = this.state;
/**
* The propsValue is the `id` of the object (user, team, etc), and
* react-select expects a full value object: {value: "id", label: "name"}
- *
- * Returning {} here will show the user a dropdown with "No options".
**/
- return this.state.results.find(({value}) => value === propsValue) || {};
+ return (
+ // When rendering the selected value, first look at the API results...
+ results.find(({value}) => value === propsValue) ??
+ // Then at the defaultOptions passed in props...
+ defaultOptions?.find(({value}) => value === propsValue) ??
+ // Then at the latest value selected in the form
+ latestSelection
+ );
}
render() {
@@ -57,7 +77,15 @@ class SelectAsyncField extends React.Component<SelectAsyncFieldProps> {
onChange={this.handleChange.bind(this, onBlur, onChange)}
onResults={data => {
const results = onResults(data);
- this.setState({results});
+ const resultSelection = results.find(result => result.value === value);
+ this.setState(
+ resultSelection
+ ? {
+ results,
+ latestSelection: resultSelection,
+ }
+ : {results}
+ );
return results;
}}
onSelectResetsInput
|
832d9207168b7f6c4ec8d2c389e7e4dd01ddc8e4
|
2024-01-30 04:14:40
|
Leander Rodrigues
|
chore(hybrid-cloud): Region-by-default test changes for auth/releases serializer (#64100)
| false
|
Region-by-default test changes for auth/releases serializer (#64100)
|
chore
|
diff --git a/src/sentry/services/hybrid_cloud/organization/impl.py b/src/sentry/services/hybrid_cloud/organization/impl.py
index 3adccbcd80428d..75a66db6ad1527 100644
--- a/src/sentry/services/hybrid_cloud/organization/impl.py
+++ b/src/sentry/services/hybrid_cloud/organization/impl.py
@@ -45,12 +45,14 @@
RpcAuditLogEntryActor,
RpcOrganizationDeleteResponse,
RpcOrganizationDeleteState,
+ RpcOrganizationMemberSummary,
)
from sentry.services.hybrid_cloud.organization.serial import (
serialize_member,
serialize_organization_summary,
serialize_rpc_organization,
serialize_rpc_team,
+ summarize_member,
)
from sentry.services.hybrid_cloud.organization_actions.impl import (
mark_organization_as_pending_deletion_with_outbox_message,
@@ -75,6 +77,14 @@ def check_membership_by_id(
return serialize_member(member)
+ def get_member_summaries_by_ids(
+ self, *, organization_id: int, user_ids: List[int]
+ ) -> List[RpcOrganizationMemberSummary]:
+ members = OrganizationMember.objects.filter(
+ organization_id=organization_id, user_id__in=user_ids
+ )
+ return [summarize_member(m) for m in members]
+
def serialize_organization(
self, *, id: int, as_user: Optional[RpcUser] = None
) -> Optional[Any]:
diff --git a/src/sentry/services/hybrid_cloud/organization/service.py b/src/sentry/services/hybrid_cloud/organization/service.py
index 4e7eeec3a3b56d..2946b38a83748b 100644
--- a/src/sentry/services/hybrid_cloud/organization/service.py
+++ b/src/sentry/services/hybrid_cloud/organization/service.py
@@ -17,6 +17,7 @@
RpcOrganizationFlagsUpdate,
RpcOrganizationMember,
RpcOrganizationMemberFlags,
+ RpcOrganizationMemberSummary,
RpcOrganizationSignal,
RpcOrganizationSummary,
RpcRegionUser,
@@ -133,6 +134,16 @@ def check_membership_by_id(
"""
pass
+ @regional_rpc_method(resolve=ByOrganizationId())
+ @abstractmethod
+ def get_member_summaries_by_ids(
+ self, *, organization_id: int, user_ids: List[int]
+ ) -> List[RpcOrganizationMemberSummary]:
+ """
+ Used to look up multiple membership summaries by users' id.
+ """
+ pass
+
@regional_rpc_method(resolve=ByOrganizationId())
@abstractmethod
def get_invite_by_id(
diff --git a/src/sentry/testutils/factories.py b/src/sentry/testutils/factories.py
index c95e85813a8c5b..26fef06d4f6cf9 100644
--- a/src/sentry/testutils/factories.py
+++ b/src/sentry/testutils/factories.py
@@ -93,6 +93,7 @@
from sentry.models.organizationmember import OrganizationMember
from sentry.models.organizationmemberteam import OrganizationMemberTeam
from sentry.models.organizationslugreservation import OrganizationSlugReservation
+from sentry.models.orgauthtoken import OrgAuthToken
from sentry.models.outbox import OutboxCategory, OutboxScope, RegionOutbox, outbox_context
from sentry.models.platformexternalissue import PlatformExternalIssue
from sentry.models.project import Project
@@ -410,6 +411,11 @@ def create_user_auth_token(user, scope_list: List[str] = None, **kwargs) -> ApiT
**kwargs,
)
+ @staticmethod
+ @assume_test_silo_mode(SiloMode.CONTROL)
+ def create_org_auth_token(*args, **kwargs) -> OrgAuthToken:
+ return OrgAuthToken.objects.create(*args, **kwargs)
+
@staticmethod
@assume_test_silo_mode(SiloMode.REGION)
def create_team(organization, **kwargs):
diff --git a/src/sentry/testutils/fixtures.py b/src/sentry/testutils/fixtures.py
index ad6fc5ee9030e6..fa8285f3cb6a6a 100644
--- a/src/sentry/testutils/fixtures.py
+++ b/src/sentry/testutils/fixtures.py
@@ -139,6 +139,9 @@ def create_auth_identity(self, *args, **kwargs):
def create_user_auth_token(self, *args, **kwargs):
return Factories.create_user_auth_token(*args, **kwargs)
+ def create_org_auth_token(self, *args, **kwargs):
+ return Factories.create_org_auth_token(*args, **kwargs)
+
def create_team_membership(self, *args, **kwargs):
return Factories.create_team_membership(*args, **kwargs)
diff --git a/tests/sentry/api/serializers/test_release.py b/tests/sentry/api/serializers/test_release.py
index 3fe75049bb1a92..1491b05c99f58a 100644
--- a/tests/sentry/api/serializers/test_release.py
+++ b/tests/sentry/api/serializers/test_release.py
@@ -20,10 +20,13 @@
from sentry.models.releaseprojectenvironment import ReleaseProjectEnvironment, ReleaseStages
from sentry.models.user import User
from sentry.models.useremail import UserEmail
+from sentry.silo.base import SiloMode
from sentry.testutils.cases import SnubaTestCase, TestCase
from sentry.testutils.helpers.datetime import before_now, iso_format
+from sentry.testutils.silo import assume_test_silo_mode, region_silo_test
+@region_silo_test
class ReleaseSerializerTest(TestCase, SnubaTestCase):
def test_simple(self):
user = self.create_user()
@@ -199,10 +202,8 @@ def test_no_tag_data(self):
assert not result["lastEvent"]
def test_get_user_from_email(self):
- user = User.objects.create(
- email="[email protected]"
- ) # upper case so we can test case sensitivity
- UserEmail.objects.get_primary_email(user=user)
+ # upper case so we can test case sensitivity
+ user = self.create_user(email="[email protected]")
project = self.create_project()
self.create_member(user=user, organization=project.organization)
release = Release.objects.create(
@@ -239,9 +240,9 @@ def test_get_single_user_from_email(self):
Tests that the first useremail will be used to
associate a user with a commit author email
"""
- user = User.objects.create(email="[email protected]")
- otheruser = User.objects.create(email="[email protected]")
- UserEmail.objects.create(email="[email protected]", user=otheruser)
+ user = self.create_user(email="[email protected]")
+ otheruser = self.create_user(email="[email protected]")
+ self.create_useremail(email="[email protected]", user=otheruser)
project = self.create_project()
self.create_member(user=user, organization=project.organization)
self.create_member(user=otheruser, organization=project.organization)
@@ -281,10 +282,11 @@ def test_select_user_from_appropriate_org(self):
Tests that a user not belonging to the organization
is not returned as the author
"""
- user = User.objects.create(email="[email protected]")
- email = UserEmail.objects.get(user=user, email="[email protected]")
- otheruser = User.objects.create(email="[email protected]")
- otheremail = UserEmail.objects.create(email="[email protected]", user=otheruser)
+ user = self.create_user(email="[email protected]")
+ with assume_test_silo_mode(SiloMode.CONTROL):
+ email = UserEmail.objects.get(user=user, email="[email protected]")
+ otheruser = self.create_user(email="[email protected]")
+ otheremail = self.create_useremail(email="[email protected]", user=otheruser)
project = self.create_project()
self.create_member(user=otheruser, organization=project.organization)
release = Release.objects.create(
@@ -320,8 +322,8 @@ def test_select_user_from_appropriate_org(self):
assert result_author["username"] == otheruser.username
def test_no_commit_author(self):
- user = User.objects.create(email="[email protected]")
- otheruser = User.objects.create(email="[email protected]")
+ user = self.create_user(email="[email protected]")
+ otheruser = self.create_user(email="[email protected]")
project = self.create_project()
self.create_member(user=otheruser, organization=project.organization)
release = Release.objects.create(
@@ -348,9 +350,9 @@ def test_deduplicate_users(self):
if there are commits associated with multiple of their
emails
"""
- user = User.objects.create(email="[email protected]")
- email = UserEmail.objects.get(user=user, email="[email protected]")
- otheremail = UserEmail.objects.create(email="[email protected]", user=user)
+ email = "[email protected]"
+ user = self.create_user(email=email)
+ new_useremail = self.create_useremail(email="[email protected]", user=user)
project = self.create_project()
self.create_member(user=user, organization=project.organization)
release = Release.objects.create(
@@ -358,10 +360,10 @@ def test_deduplicate_users(self):
)
release.add_project(project)
commit_author1 = CommitAuthor.objects.create(
- name="stebe", email=email.email, organization_id=project.organization_id
+ name="stebe", email=email, organization_id=project.organization_id
)
commit_author2 = CommitAuthor.objects.create(
- name="stebe", email=otheremail.email, organization_id=project.organization_id
+ name="stebe", email=new_useremail.email, organization_id=project.organization_id
)
commit1 = Commit.objects.create(
organization_id=project.organization_id,
@@ -445,7 +447,7 @@ def test_release_no_users(self):
serialize(release)
def test_get_user_for_authors_simple(self):
- user = User.objects.create(email="[email protected]")
+ user = self.create_user(email="[email protected]")
project = self.create_project()
self.create_member(user=user, organization=project.organization)
users = get_users_for_authors(organization_id=project.organization_id, authors=[user])
@@ -462,8 +464,8 @@ def test_get_user_for_authors_no_user(self):
@patch("sentry.api.serializers.models.release.serialize")
def test_get_user_for_authors_caching(self, patched_serialize_base):
# Ensure the fetched/miss caching logic works.
- user = User.objects.create(email="[email protected]")
- user2 = User.objects.create(email="[email protected]")
+ user = self.create_user(email="[email protected]")
+ user2 = self.create_user(email="[email protected]")
project = self.create_project()
self.create_member(user=user, organization=project.organization)
self.create_member(user=user2, organization=project.organization)
diff --git a/tests/sentry/api/test_authentication.py b/tests/sentry/api/test_authentication.py
index 578243cc3b6654..56e929c81a3845 100644
--- a/tests/sentry/api/test_authentication.py
+++ b/tests/sentry/api/test_authentication.py
@@ -123,14 +123,16 @@ def test_inactive_key(self):
self.auth.authenticate(request)
+@control_silo_test
class TestOrgAuthTokenAuthentication(TestCase):
def setUp(self):
super().setUp()
self.auth = OrgAuthTokenAuthentication()
self.org = self.create_organization(owner=self.user)
+
self.token = "sntrys_abc123_xyz"
- self.org_auth_token = OrgAuthToken.objects.create(
+ self.org_auth_token = self.create_org_auth_token(
name="Test Token 1",
token_hashed=hash_token(self.token),
organization_id=self.org.id,
diff --git a/tests/sentry/auth/test_helper.py b/tests/sentry/auth/test_helper.py
index 1269fed9181d9a..1d0069cec46fac 100644
--- a/tests/sentry/auth/test_helper.py
+++ b/tests/sentry/auth/test_helper.py
@@ -17,7 +17,6 @@
from sentry.models.authprovider import AuthProvider
from sentry.models.organizationmember import InviteStatus, OrganizationMember
from sentry.models.outbox import outbox_context
-from sentry.models.useremail import UserEmail
from sentry.services.hybrid_cloud.organization.serial import serialize_rpc_organization
from sentry.silo import SiloMode
from sentry.testutils.cases import TestCase
@@ -39,7 +38,7 @@ def setUp(self):
self.provider = "dummy"
self.request = _set_up_request()
- self.auth_provider_inst = AuthProvider.objects.create(
+ self.auth_provider_inst = self.create_auth_provider(
organization_id=self.organization.id, provider=self.provider
)
self.email = "[email protected]"
@@ -81,7 +80,7 @@ def set_up_user(self):
def set_up_user_identity(self):
"""Set up a persistent user who already has an auth identity."""
user = self.set_up_user()
- auth_identity = AuthIdentity.objects.create(
+ auth_identity = self.create_auth_identity(
user=user, auth_provider=self.auth_provider_inst, ident="test_ident"
)
return user, auth_identity
@@ -91,7 +90,6 @@ def set_up_user_identity(self):
class HandleNewUserTest(AuthIdentityHandlerTest, HybridCloudTestMixin):
@mock.patch("sentry.analytics.record")
def test_simple(self, mock_record):
-
auth_identity = self.handler.handle_new_user()
user = auth_identity.user
@@ -494,12 +492,14 @@ def test_referrer_state(self, mock_messages):
assert final_step.url == f"/settings/{self.organization.slug}/auth/"
+@control_silo_test
class HasVerifiedAccountTest(AuthIdentityHandlerTest):
def setUp(self):
super().setUp()
- member = OrganizationMember.objects.get(
- organization=self.organization, user_id=self.user.id
- )
+ with assume_test_silo_mode(SiloMode.REGION):
+ member = OrganizationMember.objects.get(
+ organization=self.organization, user_id=self.user.id
+ )
self.identity_id = self.identity["id"]
self.verification_value = {
"user_id": self.user.id,
@@ -509,11 +509,11 @@ def setUp(self):
}
def test_has_verified_account_success(self):
- UserEmail.objects.create(email=self.email, user=self.user)
+ self.create_useremail(email=self.email, user=self.user)
assert self.handler.has_verified_account(self.verification_value) is True
def test_has_verified_account_fail_email(self):
- UserEmail.objects.create(email=self.email, user=self.user)
+ self.create_useremail(email=self.email, user=self.user)
identity = {
"id": "1234",
"email": "[email protected]",
@@ -524,5 +524,5 @@ def test_has_verified_account_fail_email(self):
def test_has_verified_account_fail_user_id(self):
wrong_user = self.create_user()
- UserEmail.objects.create(email=self.email, user=wrong_user)
+ self.create_useremail(email=self.email, user=wrong_user)
assert self.handler.has_verified_account(self.verification_value) is False
|
4f2eb9f7d25871d175da6e93780804a0072337f4
|
2019-11-04 23:43:26
|
Billy Vong
|
ref(ui): Refactor `<FrameRegisters>` (#15416)
| false
|
Refactor `<FrameRegisters>` (#15416)
|
ref
|
diff --git a/src/sentry/static/sentry/app/components/events/interfaces/frameRegisters.jsx b/src/sentry/static/sentry/app/components/events/interfaces/frameRegisters.jsx
deleted file mode 100644
index 7b3e5f91000db7..00000000000000
--- a/src/sentry/static/sentry/app/components/events/interfaces/frameRegisters.jsx
+++ /dev/null
@@ -1,149 +0,0 @@
-import {Flex, Box} from 'grid-emotion';
-import PropTypes from 'prop-types';
-import React from 'react';
-import styled from 'react-emotion';
-
-import Tooltip from 'app/components/tooltip';
-import {t} from 'app/locale';
-import {defined} from 'app/utils';
-
-const REGISTER_VIEWS = [t('Hexadecimal'), t('Numeric')];
-
-export class RegisterValue extends React.Component {
- static propTypes = {
- value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
- };
-
- constructor(props) {
- super(props);
- this.state = {
- view: 0,
- };
- }
-
- toggleView = () => {
- this.setState(state => ({view: (state.view + 1) % REGISTER_VIEWS.length}));
- };
-
- formatValue = value => {
- try {
- const parsed = typeof value === 'string' ? parseInt(value, 16) : value;
- if (isNaN(parsed)) {
- return value;
- }
-
- switch (this.state.view) {
- case 1:
- return `${parsed}`;
- case 0:
- default:
- return `0x${('0000000000000000' + parsed.toString(16)).substr(-16)}`;
- }
- } catch (e) {
- return value;
- }
- };
-
- render() {
- return (
- <InlinePre>
- <FixedWidth>{this.formatValue(this.props.value)}</FixedWidth>
- <Tooltip title={REGISTER_VIEWS[this.state.view]}>
- <Toggle className="icon-filter" onClick={this.toggleView} />
- </Tooltip>
- </InlinePre>
- );
- }
-}
-
-class FrameRegisters extends React.Component {
- static propTypes = {
- data: PropTypes.object.isRequired,
- };
-
- // make sure that clicking on the registers does not actually do
- // anything on the containing element.
- preventToggling = evt => {
- evt.stopPropagation();
- };
-
- render() {
- const registers = Object.entries(this.props.data).filter(register =>
- defined(register[1])
- );
-
- return (
- <RegistersWrapper>
- <RegistersHeading>{t('registers')}</RegistersHeading>
- <Registers>
- {registers.map(register => (
- <Register key={register[0]} onClick={this.preventToggling}>
- <RegisterName>{register[0]}</RegisterName>{' '}
- <RegisterValue value={register[1]} />
- </Register>
- ))}
- </Registers>
- </RegistersWrapper>
- );
- }
-}
-
-const RegistersWrapper = styled('div')`
- border-top: 1px solid @trim;
- padding-top: 10px;
-
- .traceback .frame .box-clippable:first-child > & {
- border-top: none;
- padding-top: 0;
- }
-`;
-
-const Registers = styled(Flex)`
- flex-wrap: wrap;
- margin-left: 125px;
- padding: 2px 0px;
-`;
-
-const Register = styled(Box)`
- padding: 4px 5px;
-`;
-
-const RegistersHeading = styled('strong')`
- font-weight: 600;
- font-size: 13px;
- width: 125px;
- max-width: 125px;
- word-wrap: break-word;
- padding: 10px 15px 10px 0;
- line-height: 1.4;
- float: left;
-`;
-
-const RegisterName = styled('span')`
- display: inline-block;
- font-size: 13px;
- font-weight: 600;
- text-align: right;
- width: 4em;
-`;
-
-const InlinePre = styled('pre')`
- display: inline;
-`;
-
-const FixedWidth = styled('span')`
- width: 12em;
- text-align: right;
-`;
-
-const Toggle = styled('span')`
- opacity: 0.33;
- margin-left: 1ex;
- cursor: pointer;
-
- &:hover {
- opacity: 1;
- }
-`;
-
-export default FrameRegisters;
diff --git a/src/sentry/static/sentry/app/components/events/interfaces/frameRegisters/index.tsx b/src/sentry/static/sentry/app/components/events/interfaces/frameRegisters/index.tsx
new file mode 100644
index 00000000000000..c191c71c8615f0
--- /dev/null
+++ b/src/sentry/static/sentry/app/components/events/interfaces/frameRegisters/index.tsx
@@ -0,0 +1,81 @@
+import React from 'react';
+import styled from 'react-emotion';
+
+import {defined} from 'app/utils';
+import {t} from 'app/locale';
+import RegisterValue from 'app/components/events/interfaces/frameRegisters/registerValue';
+
+type Props = {
+ data: {[key: string]: string};
+};
+
+class FrameRegisters extends React.Component<Props> {
+ // make sure that clicking on the registers does not actually do
+ // anything on the containing element.
+ preventToggling = (evt: React.MouseEvent<HTMLDivElement>) => {
+ evt.stopPropagation();
+ };
+
+ render() {
+ return (
+ <RegistersWrapper>
+ <RegistersHeading>{t('registers')}</RegistersHeading>
+ <Registers>
+ {Object.entries(this.props.data).map(([name, value]) => {
+ if (defined(value)) {
+ return (
+ <Register key={name} onClick={this.preventToggling}>
+ <RegisterName>{name}</RegisterName> <RegisterValue value={value} />
+ </Register>
+ );
+ }
+
+ return null;
+ })}
+ </Registers>
+ </RegistersWrapper>
+ );
+ }
+}
+
+const RegistersWrapper = styled('div')`
+ border-top: 1px solid ${p => p.theme.borderLight};
+ padding-top: 10px;
+
+ .traceback .frame .box-clippable:first-child > & {
+ border-top: none;
+ padding-top: 0;
+ }
+`;
+
+const Registers = styled('div')`
+ display: flex;
+ flex-wrap: wrap;
+ margin-left: 125px;
+ padding: 2px 0px;
+`;
+
+const Register = styled('div')`
+ padding: 4px 5px;
+`;
+
+const RegistersHeading = styled('strong')`
+ font-weight: 600;
+ font-size: 13px;
+ width: 125px;
+ max-width: 125px;
+ word-wrap: break-word;
+ padding: 10px 15px 10px 0;
+ line-height: 1.4;
+ float: left;
+`;
+
+const RegisterName = styled('span')`
+ display: inline-block;
+ font-size: 13px;
+ font-weight: 600;
+ text-align: right;
+ width: 4em;
+`;
+
+export default FrameRegisters;
diff --git a/src/sentry/static/sentry/app/components/events/interfaces/frameRegisters/registerValue.tsx b/src/sentry/static/sentry/app/components/events/interfaces/frameRegisters/registerValue.tsx
new file mode 100644
index 00000000000000..dad01cd8531db5
--- /dev/null
+++ b/src/sentry/static/sentry/app/components/events/interfaces/frameRegisters/registerValue.tsx
@@ -0,0 +1,74 @@
+import React from 'react';
+import styled from 'react-emotion';
+
+import Tooltip from 'app/components/tooltip';
+import {t} from 'app/locale';
+
+const REGISTER_VIEWS = [t('Hexadecimal'), t('Numeric')];
+
+type Props = {
+ value: string | number;
+};
+
+type State = {
+ view: number;
+};
+
+export default class RegisterValue extends React.Component<Props, State> {
+ state = {
+ view: 0,
+ };
+
+ toggleView = () => {
+ this.setState(state => ({view: (state.view + 1) % REGISTER_VIEWS.length}));
+ };
+
+ formatValue = (value: Props['value']) => {
+ try {
+ const parsed = typeof value === 'string' ? parseInt(value, 16) : value;
+ if (isNaN(parsed)) {
+ return value;
+ }
+
+ switch (this.state.view) {
+ case 1:
+ return `${parsed}`;
+ case 0:
+ default:
+ return `0x${('0000000000000000' + parsed.toString(16)).substr(-16)}`;
+ }
+ } catch (e) {
+ return value;
+ }
+ };
+
+ render() {
+ return (
+ <InlinePre>
+ <FixedWidth>{this.formatValue(this.props.value)}</FixedWidth>
+ <Tooltip title={REGISTER_VIEWS[this.state.view]}>
+ <Toggle className="icon-filter" onClick={this.toggleView} />
+ </Tooltip>
+ </InlinePre>
+ );
+ }
+}
+
+const InlinePre = styled('pre')`
+ display: inline;
+`;
+
+const FixedWidth = styled('span')`
+ width: 12em;
+ text-align: right;
+`;
+
+const Toggle = styled('span')`
+ opacity: 0.33;
+ margin-left: 1ex;
+ cursor: pointer;
+
+ &:hover {
+ opacity: 1;
+ }
+`;
diff --git a/tests/js/spec/components/events/interfaces/frameRegisters.spec.jsx b/tests/js/spec/components/events/interfaces/frameRegisters.spec.jsx
index 41090fa3da5f51..3ed2daecb7ff31 100644
--- a/tests/js/spec/components/events/interfaces/frameRegisters.spec.jsx
+++ b/tests/js/spec/components/events/interfaces/frameRegisters.spec.jsx
@@ -1,9 +1,8 @@
import React from 'react';
import {shallow, mount} from 'sentry-test/enzyme';
-import FrameRegisters, {
- RegisterValue,
-} from 'app/components/events/interfaces/frameRegisters';
+import FrameRegisters from 'app/components/events/interfaces/frameRegisters';
+import RegisterValue from 'app/components/events/interfaces/frameRegisters/registerValue';
describe('FrameRegisters', () => {
it('should render registers', () => {
|
6c615f718fd18eb64f5573aea52e9c2919bc6f04
|
2018-06-27 21:07:21
|
Brett Hoerner
|
ref(snuba): Add project_id to `issues` in request. (#8855)
| false
|
Add project_id to `issues` in request. (#8855)
|
ref
|
diff --git a/src/sentry/utils/snuba.py b/src/sentry/utils/snuba.py
index acefcc438cbf82..29317d926d4c83 100644
--- a/src/sentry/utils/snuba.py
+++ b/src/sentry/utils/snuba.py
@@ -346,13 +346,16 @@ def get_project_issues(project_ids, issue_ids=None):
tombstone.project_id, {}
)[tombstone.hash] = tombstone.deleted_at
- # return [(gid, [(hash, tombstone_date), (hash, tombstone_date), ...]), ...]
+ # return [(gid, pid, [(hash, tombstone_date), (hash, tombstone_date), ...]), ...]
result = {}
for h in hashes:
tombstone_date = tombstones_by_project.get(h.project_id, {}).get(h.hash, None)
- pair = (h.hash, tombstone_date.strftime("%Y-%m-%d %H:%M:%S") if tombstone_date else None)
- result.setdefault(h.group_id, []).append(pair)
- return list(result.items())[:MAX_ISSUES]
+ pair = (
+ h.hash,
+ tombstone_date.strftime("%Y-%m-%d %H:%M:%S") if tombstone_date else None
+ )
+ result.setdefault((h.group_id, h.project_id), []).append(pair)
+ return [k + (v,) for k, v in result.items()][:MAX_ISSUES]
def get_related_project_ids(column, ids):
diff --git a/tests/snuba/test_snuba.py b/tests/snuba/test_snuba.py
index aa402462b0cd1d..81651294a63e0f 100644
--- a/tests/snuba/test_snuba.py
+++ b/tests/snuba/test_snuba.py
@@ -58,7 +58,7 @@ def test_project_issues_with_legacy_hash(self):
)
assert snuba.get_project_issues([self.project], [self.group.id]) == \
- [(self.group.id, [('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', None)])]
+ [(self.group.id, self.group.project_id, [('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', None)])]
# GroupHash without a group_id, should not be included in get_project_issues
GroupHash.objects.create(
@@ -66,8 +66,9 @@ def test_project_issues_with_legacy_hash(self):
hash='0' * 32,
)
- assert self.group.id in dict(snuba.get_project_issues([self.project]))
- assert None not in dict(snuba.get_project_issues([self.project]))
+ group_ids = [i[0] for i in (snuba.get_project_issues([self.project]))]
+ assert self.group.id in group_ids
+ assert None not in group_ids
def test_project_issues_with_tombstones(self):
base_time = datetime.utcnow()
@@ -106,7 +107,7 @@ def _query_for_issue(group_id):
hash=a_hash
)
assert snuba.get_project_issues([self.project], [group1.id]) == \
- [(group1.id, [('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', None)])]
+ [(group1.id, group1.project_id, [('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', None)])]
# 1 event in the groups, no deletes have happened
_insert_event_for_time(base_time)
@@ -126,7 +127,7 @@ def _query_for_issue(group_id):
# tombstone time is returned as expected
assert snuba.get_project_issues([self.project], [group2.id]) == \
- [(group2.id, [('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
+ [(group2.id, group2.project_id, [('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
ght.deleted_at.strftime("%Y-%m-%d %H:%M:%S"))])]
# events <= to the tombstone date aren't returned
|
f260b14c3ec53d88bb69db82e64591450084d82b
|
2022-10-28 21:24:04
|
Ryan Albrecht
|
feat(replays): Allow replay as a search type, ex for /recent-searches/ (#40677)
| false
|
Allow replay as a search type, ex for /recent-searches/ (#40677)
|
feat
|
diff --git a/static/app/types/group.tsx b/static/app/types/group.tsx
index e31d58de7090aa..b8848f5d40ac97 100644
--- a/static/app/types/group.tsx
+++ b/static/app/types/group.tsx
@@ -40,6 +40,7 @@ export enum SavedSearchType {
ISSUE = 0,
EVENT = 1,
SESSION = 2,
+ REPLAY = 3,
}
export enum IssueCategory {
|
f66fabd780e155555fb917b5f2f394fbc97883e4
|
2020-02-26 06:35:58
|
Billy Vong
|
ref(ts): Convert `<AccountSecurityWrapper>` (#17272)
| false
|
Convert `<AccountSecurityWrapper>` (#17272)
|
ref
|
diff --git a/src/sentry/static/sentry/app/types/index.tsx b/src/sentry/static/sentry/app/types/index.tsx
index 7352072152c214..90de7def716db5 100644
--- a/src/sentry/static/sentry/app/types/index.tsx
+++ b/src/sentry/static/sentry/app/types/index.tsx
@@ -251,6 +251,16 @@ export type AvatarUser = {
lastSeen?: string;
};
+/**
+ * This is an authenticator that a user is enrolled in
+ */
+type UserEnrolledAuthenticator = {
+ dateUsed: EnrolledAuthenticator['lastUsedAt'];
+ dateCreated: EnrolledAuthenticator['createdAt'];
+ type: Authenticator['id'];
+ id: EnrolledAuthenticator['authId'];
+};
+
export type User = AvatarUser & {
lastLogin: string;
isSuperuser: boolean;
@@ -266,7 +276,7 @@ export type User = AvatarUser & {
isActive: boolean;
has2fa: boolean;
canReset2fa: boolean;
- authenticators: Authenticator[];
+ authenticators: UserEnrolledAuthenticator[];
dateJoined: string;
options: {
timezone: string;
@@ -346,12 +356,59 @@ export type GlobalSelection = {
};
};
-type Authenticator = {
- dateUsed: string | null;
- dateCreated: string;
- type: string; // i.e. 'u2f'
- id: string;
+export type Authenticator = {
+ /**
+ * String used to display on button for user as CTA to enroll
+ */
+ enrollButton: string;
+
+ /**
+ * Display name for the authenticator
+ */
name: string;
+
+ /**
+ * Allows multiple enrollments to authenticator
+ */
+ allowMultiEnrollment: boolean;
+
+ /**
+ * String to display on button for user to remove authenticator
+ */
+ removeButton: string | null;
+
+ canValidateOtp: boolean;
+
+ /**
+ * Is user enrolled to this authenticator
+ */
+ isEnrolled: boolean;
+
+ /**
+ * String to display on button for additional information about authenticator
+ */
+ configureButton: string;
+
+ /**
+ * Type of authenticator
+ */
+ id: string;
+
+ /**
+ * Is this used as a backup interface?
+ */
+ isBackupInterface: boolean;
+
+ /**
+ * Description of the authenticator
+ */
+ description: string;
+} & Partial<EnrolledAuthenticator>;
+
+export type EnrolledAuthenticator = {
+ lastUsedAt: string | null;
+ createdAt: string;
+ authId: string;
};
export type Config = {
diff --git a/src/sentry/static/sentry/app/views/settings/account/accountSecurity/accountSecurityWrapper.jsx b/src/sentry/static/sentry/app/views/settings/account/accountSecurity/accountSecurityWrapper.jsx
deleted file mode 100644
index 55d2f7b0fdf928..00000000000000
--- a/src/sentry/static/sentry/app/views/settings/account/accountSecurity/accountSecurityWrapper.jsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import {withRouter} from 'react-router';
-import React from 'react';
-import AsyncComponent from 'app/components/asyncComponent';
-
-import {addErrorMessage} from 'app/actionCreators/indicator';
-import {t} from 'app/locale';
-
-const ENDPOINT = '/users/me/authenticators/';
-
-class AccountSecurityWrapper extends AsyncComponent {
- getEndpoints() {
- return [
- ['authenticators', ENDPOINT],
- ['organizations', '/organizations/'],
- ];
- }
-
- handleDisable = auth => {
- if (!auth || !auth.authId) {
- return;
- }
-
- this.setState({loading: true});
-
- this.api
- .requestPromise(`${ENDPOINT}${auth.authId}/`, {method: 'DELETE'})
- .then(this.remountComponent, () => {
- this.setState({loading: false});
- addErrorMessage(t('Error disabling', auth.name));
- });
- };
-
- handleRegenerateBackupCodes = () => {
- this.setState({loading: true});
-
- this.api
- .requestPromise(`${ENDPOINT}${this.props.params.authId}/`, {method: 'PUT'})
- .then(this.remountComponent, () =>
- this.addError(t('Error regenerating backup codes'))
- );
- };
-
- renderBody() {
- const {authenticators, organizations} = this.state;
-
- const countEnrolled = authenticators.filter(
- auth => auth.isEnrolled && !auth.isBackupInterface
- ).length;
- const orgsRequire2fa = organizations.filter(org => org.require2FA);
- const deleteDisabled = orgsRequire2fa.length > 0 && countEnrolled === 1;
-
- // This happens when you switch between children views and the next child
- // view is lazy loaded, it can potentially be `null` while the code split
- // package is being fetched
- if (this.props.children === null) {
- return null;
- }
-
- return React.cloneElement(this.props.children, {
- onDisable: this.handleDisable,
- onRegenerateBackupCodes: this.handleRegenerateBackupCodes,
- authenticators,
- deleteDisabled,
- orgsRequire2fa,
- countEnrolled,
- });
- }
-}
-
-export default withRouter(AccountSecurityWrapper);
diff --git a/src/sentry/static/sentry/app/views/settings/account/accountSecurity/accountSecurityWrapper.tsx b/src/sentry/static/sentry/app/views/settings/account/accountSecurity/accountSecurityWrapper.tsx
new file mode 100644
index 00000000000000..147584ce3a3a27
--- /dev/null
+++ b/src/sentry/static/sentry/app/views/settings/account/accountSecurity/accountSecurityWrapper.tsx
@@ -0,0 +1,90 @@
+import {RouteComponentProps} from 'react-router/lib/Router';
+import React from 'react';
+
+import {Authenticator, OrganizationSummary} from 'app/types';
+import {addErrorMessage} from 'app/actionCreators/indicator';
+import {defined} from 'app/utils';
+import {t} from 'app/locale';
+import AsyncComponent from 'app/components/asyncComponent';
+
+const ENDPOINT = '/users/me/authenticators/';
+
+type Props = {
+ children: React.ReactElement;
+} & RouteComponentProps<{authId: string}, {}> &
+ AsyncComponent['props'];
+
+type State = {
+ authenticators?: Authenticator[];
+ organizations?: OrganizationSummary[];
+} & AsyncComponent['state'];
+
+class AccountSecurityWrapper extends AsyncComponent<Props, State> {
+ getEndpoints(): [string, string][] {
+ return [
+ ['authenticators', ENDPOINT],
+ ['organizations', '/organizations/'],
+ ];
+ }
+
+ handleDisable = async (auth: Authenticator) => {
+ if (!auth || !auth.authId) {
+ return;
+ }
+
+ this.setState({loading: true});
+
+ try {
+ await this.api.requestPromise(`${ENDPOINT}${auth.authId}/`, {method: 'DELETE'});
+ this.remountComponent();
+ } catch (_err) {
+ addErrorMessage(t('Error disabling %s', auth.name));
+ }
+
+ this.setState({loading: false});
+ };
+
+ handleRegenerateBackupCodes = async () => {
+ this.setState({loading: true});
+
+ try {
+ await this.api.requestPromise(`${ENDPOINT}${this.props.params.authId}/`, {
+ method: 'PUT',
+ });
+ this.remountComponent();
+ } catch (_err) {
+ addErrorMessage(t('Error regenerating backup codes'));
+ }
+
+ this.setState({loading: false});
+ };
+
+ renderBody() {
+ const {children} = this.props;
+ const {authenticators, organizations} = this.state;
+
+ const enrolled =
+ authenticators?.filter(auth => auth.isEnrolled && !auth.isBackupInterface) || [];
+ const countEnrolled = enrolled.length;
+ const orgsRequire2fa = organizations?.filter(org => org.require2FA) || [];
+ const deleteDisabled = orgsRequire2fa.length > 0 && countEnrolled === 1;
+
+ // This happens when you switch between children views and the next child
+ // view is lazy loaded, it can potentially be `null` while the code split
+ // package is being fetched
+ if (!defined(children)) {
+ return null;
+ }
+
+ return React.cloneElement(this.props.children, {
+ onDisable: this.handleDisable,
+ onRegenerateBackupCodes: this.handleRegenerateBackupCodes,
+ authenticators,
+ deleteDisabled,
+ orgsRequire2fa,
+ countEnrolled,
+ });
+ }
+}
+
+export default AccountSecurityWrapper;
diff --git a/tests/js/spec/views/accountSecurityDetails.spec.jsx b/tests/js/spec/views/accountSecurityDetails.spec.jsx
index a837526ea10f03..1c07df6e41b1a4 100644
--- a/tests/js/spec/views/accountSecurityDetails.spec.jsx
+++ b/tests/js/spec/views/accountSecurityDetails.spec.jsx
@@ -41,7 +41,7 @@ describe('AccountSecurityDetails', function() {
body: TestStubs.Authenticators().Totp(),
});
wrapper = mountWithTheme(
- <AccountSecurityWrapper>
+ <AccountSecurityWrapper router={router} params={params}>
<AccountSecurityDetails router={router} params={params} />
</AccountSecurityWrapper>,
routerContext
@@ -82,7 +82,7 @@ describe('AccountSecurityDetails', function() {
});
wrapper = mountWithTheme(
- <AccountSecurityWrapper>
+ <AccountSecurityWrapper router={router} params={params}>
<AccountSecurityDetails router={router} params={params} />
</AccountSecurityWrapper>,
routerContext
@@ -112,7 +112,7 @@ describe('AccountSecurityDetails', function() {
});
wrapper = mountWithTheme(
- <AccountSecurityWrapper>
+ <AccountSecurityWrapper router={router} params={params}>
<AccountSecurityDetails router={router} params={params} />
</AccountSecurityWrapper>,
routerContext
@@ -148,7 +148,7 @@ describe('AccountSecurityDetails', function() {
});
wrapper = mountWithTheme(
- <AccountSecurityWrapper>
+ <AccountSecurityWrapper router={router} params={params}>
<AccountSecurityDetails router={router} params={params} />
</AccountSecurityWrapper>,
routerContext
|
3179ba56e9ab6a9e6daf73fae4f378fbd2473755
|
2023-10-10 19:40:26
|
Nar Saynorath
|
fix(adv-analysis): Assign score_delta default value (#57813)
| false
|
Assign score_delta default value (#57813)
|
fix
|
diff --git a/src/sentry/api/helpers/span_analysis.py b/src/sentry/api/helpers/span_analysis.py
index d410b3fb9eda85..eba99098ec7898 100644
--- a/src/sentry/api/helpers/span_analysis.py
+++ b/src/sentry/api/helpers/span_analysis.py
@@ -57,6 +57,7 @@ def span_analysis(data: List[Row]):
row1 = span_data_p0.get(key)
row2 = span_data_p1.get(key)
new_span = False
+ score_delta = 0.0
if row1 and row2:
score_delta = row2["score"] - row1["score"]
|
bc245aab4efd9c6c99a131a3e78b4d284e11edab
|
2023-06-23 20:47:27
|
Nar Saynorath
|
fix(events-facets): Force pagination limit to 11 (#51520)
| false
|
Force pagination limit to 11 (#51520)
|
fix
|
diff --git a/src/sentry/api/endpoints/organization_events_facets.py b/src/sentry/api/endpoints/organization_events_facets.py
index e02dc88b348546..877cad210cad58 100644
--- a/src/sentry/api/endpoints/organization_events_facets.py
+++ b/src/sentry/api/endpoints/organization_events_facets.py
@@ -10,6 +10,7 @@
from sentry.api.paginator import GenericOffsetPaginator
from sentry.search.utils import DEVICE_CLASS
from sentry.snuba import discover
+from sentry.snuba.discover import TOP_KEYS_DEFAULT_LIMIT
@region_silo_endpoint
@@ -30,7 +31,8 @@ def data_fn(offset, limit):
query=request.GET.get("query"),
params=params,
referrer="api.organization-events-facets.top-tags",
- per_page=limit,
+ # TODO(nar): Remove this hardcoded limit and pass in the limit from the paginator
+ per_page=TOP_KEYS_DEFAULT_LIMIT + 1,
cursor=offset,
)
|
dfc77cb75f7f7a043984c8c33ae47de569225142
|
2021-11-04 22:59:28
|
Kelly Carino
|
feat(workflow): Handle data to performance section on release details (#29426)
| false
|
Handle data to performance section on release details (#29426)
|
feat
|
diff --git a/static/app/components/discover/performanceCardTable.tsx b/static/app/components/discover/performanceCardTable.tsx
index b4541a26188cdd..afe688bb36120d 100644
--- a/static/app/components/discover/performanceCardTable.tsx
+++ b/static/app/components/discover/performanceCardTable.tsx
@@ -1,100 +1,209 @@
import {Fragment} from 'react';
import * as React from 'react';
import {Link} from 'react-router';
+import {css} from '@emotion/react';
import styled from '@emotion/styled';
+import {Location} from 'history';
import Alert from 'app/components/alert';
+import AsyncComponent from 'app/components/asyncComponent';
import LoadingIndicator from 'app/components/loadingIndicator';
+import NotAvailable from 'app/components/notAvailable';
import {PanelItem} from 'app/components/panels';
import PanelTable from 'app/components/panels/panelTable';
-import UserMisery from 'app/components/userMisery';
-import {backend, frontend, mobile, serverless} from 'app/data/platformCategories';
-import {IconWarning} from 'app/icons';
-import {t} from 'app/locale';
+import {IconArrow, IconWarning} from 'app/icons';
+import {t, tct} from 'app/locale';
import overflowEllipsis from 'app/styles/overflowEllipsis';
import space from 'app/styles/space';
import {Organization, ReleaseProject} from 'app/types';
+import DiscoverQuery, {TableData} from 'app/utils/discover/discoverQuery';
+import EventView from 'app/utils/discover/eventView';
+import {getFieldRenderer} from 'app/utils/discover/fieldRenderers';
import {MobileVital, WebVital} from 'app/utils/discover/fields';
import {
MOBILE_VITAL_DETAILS,
WEB_VITAL_DETAILS,
} from 'app/utils/performance/vitals/constants';
+import {PROJECT_PERFORMANCE_TYPE} from 'app/views/performance/utils';
-const FRONTEND_PLATFORMS: string[] = [...frontend];
-const BACKEND_PLATFORMS: string[] = [...backend, ...serverless];
-const MOBILE_PLATFORMS: string[] = [...mobile];
-
-type Props = {
+type PerformanceCardTableProps = {
organization: Organization;
+ location: Location;
project: ReleaseProject;
+ allReleasesEventView: EventView;
+ releaseEventView: EventView;
+ allReleasesTableData: TableData | null;
+ thisReleaseTableData: TableData | null;
+ performanceType: string;
isLoading: boolean;
- isEmpty: boolean;
};
-class PerformanceCardTable extends React.PureComponent<Props> {
- userMiseryField() {
+function PerformanceCardTable({
+ organization,
+ location,
+ project,
+ releaseEventView,
+ allReleasesTableData,
+ thisReleaseTableData,
+ performanceType,
+ isLoading,
+}: PerformanceCardTableProps) {
+ const miseryRenderer =
+ allReleasesTableData?.meta &&
+ getFieldRenderer('user_misery', allReleasesTableData.meta);
+
+ function renderChange(
+ allReleasesScore: number,
+ thisReleaseScore: number,
+ meta: string
+ ) {
+ if (allReleasesScore === undefined || thisReleaseScore === undefined) {
+ return <StyledNotAvailable />;
+ }
+
+ const trend = allReleasesScore - thisReleaseScore;
+ const trendSeconds = trend >= 1000 ? trend / 1000 : trend;
+ const trendPercentage = (allReleasesScore - thisReleaseScore) * 100;
+ const valPercentage = Math.round(Math.abs(trendPercentage));
+ const val = Math.abs(trendSeconds).toFixed(2);
+
+ if (trend === 0) {
+ return <SubText>{`0${meta === 'duration' ? 'ms' : '%'}`}</SubText>;
+ }
+
return (
- <UserMiseryPanelItem>
- <StyledUserMisery
- bars={10}
- barHeight={20}
- miseryLimit={1000}
- totalUsers={500}
- userMisery={300}
- miserableUsers={200}
+ <TrendText color={trend >= 0 ? 'success' : 'error'}>
+ {`${meta === 'duration' ? val : valPercentage}${
+ meta === 'duration' ? (trend >= 1000 ? 's' : 'ms') : '%'
+ }`}
+ <StyledIconArrow
+ color={trend >= 0 ? 'success' : 'error'}
+ direction={trend >= 0 ? 'down' : 'up'}
+ size="xs"
/>
- </UserMiseryPanelItem>
+ </TrendText>
);
}
- sectionField(field: JSX.Element[]) {
+ function userMiseryTrend() {
+ const allReleasesUserMisery = allReleasesTableData?.data?.[0]?.user_misery;
+ const thisReleaseUserMisery = thisReleaseTableData?.data?.[0]?.user_misery;
return (
<StyledPanelItem>
- <TitleSpace />
- {field}
+ {renderChange(
+ allReleasesUserMisery as number,
+ thisReleaseUserMisery as number,
+ 'number' as string
+ )}
</StyledPanelItem>
);
}
- renderFrontendPerformance() {
- const vitals = [WebVital.FCP, WebVital.FID, WebVital.LCP, WebVital.CLS];
- const webVitalTitles = vitals.map(vital => {
+ function renderFrontendPerformance() {
+ const webVitals = [
+ {title: WebVital.FCP, field: 'p75_measurements_fcp'},
+ {title: WebVital.FID, field: 'p75_measurements_fid'},
+ {title: WebVital.LCP, field: 'p75_measurements_lcp'},
+ {title: WebVital.CLS, field: 'p75_measurements_cls'},
+ ];
+
+ const spans = [
+ {title: 'HTTP', column: 'p75(spans.http)', field: 'p75_spans_http'},
+ {title: 'Browser', column: 'p75(spans.browser)', field: 'p75_spans_browser'},
+ {title: 'Resource', column: 'p75(spans.resource)', field: 'p75_spans_resource'},
+ ];
+
+ const webVitalTitles = webVitals.map((vital, idx) => {
+ const newView = releaseEventView.withColumns([
+ {kind: 'field', field: `p75(${vital.title})`},
+ ]);
return (
- <SubTitle key={vital}>
- {WEB_VITAL_DETAILS[vital].name} ({WEB_VITAL_DETAILS[vital].acronym})
+ <SubTitle key={idx}>
+ <Link to={newView.getResultsViewUrlTarget(organization.slug)}>
+ {WEB_VITAL_DETAILS[vital.title].name} (
+ {WEB_VITAL_DETAILS[vital.title].acronym})
+ </Link>
</SubTitle>
);
});
- const spans = ['HTTP', 'DB', 'Browser', 'Resource'];
- const spanTitles = spans.map(span => {
- return <SubTitle key={span}>{t(span)}</SubTitle>;
- });
-
- // TODO(kelly): placeholder data. will need to add discover data for webvitals and span operations in follow-up pr
- const fieldData = ['0ms', '0ms', '0ms', '0ms'];
- const field = fieldData.map(data => {
+ const spanTitles = spans.map((span, idx) => {
+ const newView = releaseEventView.withColumns([
+ {kind: 'field', field: `${span.column}`},
+ ]);
return (
- <Field key={data} align="right">
- {data}
- </Field>
+ <SubTitle key={idx}>
+ <Link to={newView.getResultsViewUrlTarget(organization.slug)}>
+ {t(span.title)}
+ </Link>
+ </SubTitle>
);
});
- const columnData = () => {
- return (
- <div>
- {this.userMiseryField()}
- {this.sectionField(field)}
- {this.sectionField(field)}
- </div>
- );
- };
+ const webVitalsRenderer = webVitals.map(
+ vital =>
+ allReleasesTableData?.meta &&
+ getFieldRenderer(vital.field, allReleasesTableData?.meta)
+ );
+
+ const spansRenderer = spans.map(
+ span =>
+ allReleasesTableData?.meta &&
+ getFieldRenderer(span.field, allReleasesTableData?.meta)
+ );
+
+ const webReleaseTrend = webVitals.map(vital => {
+ return {
+ allReleasesRow: {
+ data: allReleasesTableData?.data?.[0]?.[vital.field],
+ meta: allReleasesTableData?.meta?.[vital.field],
+ },
+ thisReleaseRow: {
+ data: thisReleaseTableData?.data?.[0]?.[vital.field],
+ meta: thisReleaseTableData?.meta?.[vital.field],
+ },
+ };
+ });
+ const spansReleaseTrend = spans.map(span => {
+ return {
+ allReleasesRow: {
+ data: allReleasesTableData?.data?.[0]?.[span.field],
+ meta: allReleasesTableData?.meta?.[span.field],
+ },
+ thisReleaseRow: {
+ data: thisReleaseTableData?.data?.[0]?.[span.field],
+ meta: thisReleaseTableData?.meta?.[span.field],
+ },
+ };
+ });
+
+ const emptyColumn = (
+ <div>
+ <SingleEmptySubText>
+ <StyledNotAvailable tooltip={t('No results found')} />
+ </SingleEmptySubText>
+ <StyledPanelItem>
+ <TitleSpace />
+ {webVitals.map((vital, index) => (
+ <MultipleEmptySubText key={vital[index]}>
+ {<StyledNotAvailable tooltip={t('No results found')} />}
+ </MultipleEmptySubText>
+ ))}
+ </StyledPanelItem>
+ <StyledPanelItem>
+ <TitleSpace />
+ {spans.map((span, index) => (
+ <MultipleEmptySubText key={span[index]}>
+ {<StyledNotAvailable tooltip={t('No results found')} />}
+ </MultipleEmptySubText>
+ ))}
+ </StyledPanelItem>
+ </div>
+ );
return (
<Fragment>
<div>
- {/* Table description column */}
<PanelItem>{t('User Misery')}</PanelItem>
<StyledPanelItem>
<div>{t('Web Vitals')}</div>
@@ -105,62 +214,167 @@ class PerformanceCardTable extends React.PureComponent<Props> {
{spanTitles}
</StyledPanelItem>
</div>
+ {allReleasesTableData?.data.length === 0
+ ? emptyColumn
+ : allReleasesTableData?.data.map((dataRow, idx) => {
+ const allReleasesMisery = miseryRenderer?.(dataRow, {
+ organization,
+ location,
+ });
+ const allReleasesWebVitals = webVitalsRenderer?.map(renderer =>
+ renderer?.(dataRow, {organization, location})
+ );
+ const allReleasesSpans = spansRenderer?.map(renderer =>
+ renderer?.(dataRow, {organization, location})
+ );
+
+ return (
+ <div key={idx}>
+ <UserMiseryPanelItem>{allReleasesMisery}</UserMiseryPanelItem>
+ <StyledPanelItem>
+ <TitleSpace />
+ {allReleasesWebVitals.map(webVital => webVital)}
+ </StyledPanelItem>
+ <StyledPanelItem>
+ <TitleSpace />
+ {allReleasesSpans.map(span => span)}
+ </StyledPanelItem>
+ </div>
+ );
+ })}
+ {thisReleaseTableData?.data.length === 0
+ ? emptyColumn
+ : thisReleaseTableData?.data.map((dataRow, idx) => {
+ const thisReleasesMisery = miseryRenderer?.(dataRow, {
+ organization,
+ location,
+ });
+ const thisReleasesWebVitals = webVitalsRenderer?.map(renderer =>
+ renderer?.(dataRow, {organization, location})
+ );
+ const thisReleasesSpans = spansRenderer?.map(renderer =>
+ renderer?.(dataRow, {organization, location})
+ );
+
+ return (
+ <div key={idx}>
+ <div>
+ <UserMiseryPanelItem>{thisReleasesMisery}</UserMiseryPanelItem>
+ <StyledPanelItem>
+ <TitleSpace />
+ {thisReleasesWebVitals.map(webVital => webVital)}
+ </StyledPanelItem>
+ <StyledPanelItem>
+ <TitleSpace />
+ {thisReleasesSpans.map(span => span)}
+ </StyledPanelItem>
+ </div>
+ </div>
+ );
+ })}
<div>
- {/* Table All Releases column */}
- {/* TODO(kelly): placeholder data. will need to add user misery data in follow-up pr */}
- {columnData()}
- </div>
- <div>
- {/* Table This Release column */}
- {columnData()}
- </div>
- <div>
- {/* Table Change column */}
- {columnData()}
+ {userMiseryTrend()}
+ <StyledPanelItem>
+ <TitleSpace />
+ {webReleaseTrend?.map(row =>
+ renderChange(
+ row.allReleasesRow?.data as number,
+ row.thisReleaseRow?.data as number,
+ row.allReleasesRow?.meta as string
+ )
+ )}
+ </StyledPanelItem>
+ <StyledPanelItem>
+ <TitleSpace />
+ {spansReleaseTrend?.map(row =>
+ renderChange(
+ row.allReleasesRow?.data as number,
+ row.thisReleaseRow?.data as number,
+ row.allReleasesRow?.meta as string
+ )
+ )}
+ </StyledPanelItem>
</div>
</Fragment>
);
}
- renderBackendPerformance() {
- const spans = ['HTTP', 'DB'];
- const spanTitles = spans.map(span => {
- return <SubTitle key={span}>{t(span)}</SubTitle>;
- });
+ function renderBackendPerformance() {
+ const spans = [
+ {title: 'HTTP', column: 'p75(spans.http)', field: 'p75_spans_http'},
+ {title: 'DB', column: 'p75(spans.db)', field: 'p75_spans_db'},
+ ];
- // TODO(kelly): placeholder data. will need to add discover data for webvitals and span operations in follow-up pr
- const apdexData = ['0ms'];
- const apdexField = apdexData.map(data => {
+ const spanTitles = spans.map((span, idx) => {
+ const newView = releaseEventView.withColumns([
+ {kind: 'field', field: `${span.column}`},
+ ]);
return (
- <Field key={data} align="right">
- {data}
- </Field>
+ <SubTitle key={idx}>
+ <Link to={newView.getResultsViewUrlTarget(organization.slug)}>
+ {t(span.title)}
+ </Link>
+ </SubTitle>
);
});
- const fieldData = ['0ms', '0ms'];
- const field = fieldData.map(data => {
- return (
- <Field key={data} align="right">
- {data}
- </Field>
- );
+ const apdexRenderer =
+ allReleasesTableData?.meta && getFieldRenderer('apdex', allReleasesTableData.meta);
+
+ const spansRenderer = spans.map(
+ span =>
+ allReleasesTableData?.meta &&
+ getFieldRenderer(span.field, allReleasesTableData?.meta)
+ );
+
+ const spansReleaseTrend = spans.map(span => {
+ return {
+ allReleasesRow: {
+ data: allReleasesTableData?.data?.[0]?.[span.field],
+ meta: allReleasesTableData?.meta?.[span.field],
+ },
+ thisReleaseRow: {
+ data: thisReleaseTableData?.data?.[0]?.[span.field],
+ meta: thisReleaseTableData?.meta?.[span.field],
+ },
+ };
});
- const columnData = () => {
+ function apdexTrend() {
+ const allReleasesApdex = allReleasesTableData?.data?.[0]?.apdex;
+ const thisReleaseApdex = thisReleaseTableData?.data?.[0]?.apdex;
return (
- <div>
- {this.userMiseryField()}
- <StyledPanelItem>{apdexField}</StyledPanelItem>
- {this.sectionField(field)}
- </div>
+ <StyledPanelItem>
+ {renderChange(
+ allReleasesApdex as number,
+ thisReleaseApdex as number,
+ 'string' as string
+ )}
+ </StyledPanelItem>
);
- };
-
+ }
+
+ const emptyColumn = (
+ <div>
+ <SingleEmptySubText>
+ <StyledNotAvailable tooltip={t('No results found')} />
+ </SingleEmptySubText>
+ <SingleEmptySubText>
+ <StyledNotAvailable tooltip={t('No results found')} />
+ </SingleEmptySubText>
+ <StyledPanelItem>
+ <TitleSpace />
+ {spans.map((span, index) => (
+ <MultipleEmptySubText key={span[index]}>
+ {<StyledNotAvailable tooltip={t('No results found')} />}
+ </MultipleEmptySubText>
+ ))}
+ </StyledPanelItem>
+ </div>
+ );
return (
<Fragment>
<div>
- {/* Table description column */}
<PanelItem>{t('User Misery')}</PanelItem>
<StyledPanelItem>
<div>{t('Apdex')}</div>
@@ -170,29 +384,79 @@ class PerformanceCardTable extends React.PureComponent<Props> {
{spanTitles}
</StyledPanelItem>
</div>
+ {allReleasesTableData?.data.length === 0
+ ? emptyColumn
+ : allReleasesTableData?.data.map((dataRow, idx) => {
+ const allReleasesMisery = miseryRenderer?.(dataRow, {
+ organization,
+ location,
+ });
+ const allReleasesApdex = apdexRenderer?.(dataRow, {organization, location});
+ const allReleasesSpans = spansRenderer?.map(renderer =>
+ renderer?.(dataRow, {organization, location})
+ );
+
+ return (
+ <div key={idx}>
+ <UserMiseryPanelItem>{allReleasesMisery}</UserMiseryPanelItem>
+ <ApdexPanelItem>{allReleasesApdex}</ApdexPanelItem>
+ <StyledPanelItem>
+ <TitleSpace />
+ {allReleasesSpans.map(span => span)}
+ </StyledPanelItem>
+ </div>
+ );
+ })}
+ {thisReleaseTableData?.data.length === 0
+ ? emptyColumn
+ : thisReleaseTableData?.data.map((dataRow, idx) => {
+ const thisReleasesMisery = miseryRenderer?.(dataRow, {
+ organization,
+ location,
+ });
+ const thisReleasesApdex = apdexRenderer?.(dataRow, {
+ organization,
+ location,
+ });
+ const thisReleasesSpans = spansRenderer?.map(renderer =>
+ renderer?.(dataRow, {organization, location})
+ );
+
+ return (
+ <div key={idx}>
+ <UserMiseryPanelItem>{thisReleasesMisery}</UserMiseryPanelItem>
+ <ApdexPanelItem>{thisReleasesApdex}</ApdexPanelItem>
+ <StyledPanelItem>
+ <TitleSpace />
+ {thisReleasesSpans.map(span => span)}
+ </StyledPanelItem>
+ </div>
+ );
+ })}
<div>
- {/* Table All Releases column */}
- {/* TODO(kelly): placeholder data. will need to add user misery data in follow-up pr */}
- {columnData()}
- </div>
- <div>
- {/* Table This Release column */}
- {columnData()}
- </div>
- <div>
- {/* Table Change column */}
- {columnData()}
+ {userMiseryTrend()}
+ {apdexTrend()}
+ <StyledPanelItem>
+ <TitleSpace />
+ {spansReleaseTrend?.map(row =>
+ renderChange(
+ row.allReleasesRow?.data as number,
+ row.thisReleaseRow?.data as number,
+ row.allReleasesRow?.meta as string
+ )
+ )}
+ </StyledPanelItem>
</div>
</Fragment>
);
}
- renderMobilePerformance() {
+ function renderMobilePerformance() {
const mobileVitals = [
MobileVital.AppStartCold,
MobileVital.AppStartWarm,
MobileVital.FramesSlow,
- MobileVital.FramesFrozenRate,
+ MobileVital.FramesFrozen,
];
const mobileVitalTitles = mobileVitals.map(mobileVital => {
return (
@@ -200,140 +464,279 @@ class PerformanceCardTable extends React.PureComponent<Props> {
);
});
- // TODO(kelly): placeholder data. will need to add mobile data for mobilevitals in follow-up pr
- const mobileData = ['0ms'];
- const mobileField = mobileData.map(data => {
- return (
- <Field key={data} align="right">
- {data}
- </Field>
- );
- });
- const field = mobileVitals.map(vital => {
- return <StyledPanelItem key={vital}>{mobileField}</StyledPanelItem>;
+ const mobileVitalFields = [
+ 'p75_measurements_app_start_cold',
+ 'p75_measurements_app_start_warm',
+ 'p75_measurements_frames_slow',
+ 'p75_measurements_frames_frozen',
+ ];
+ const mobileVitalsRenderer = mobileVitalFields.map(
+ field =>
+ allReleasesTableData?.meta && getFieldRenderer(field, allReleasesTableData?.meta)
+ );
+
+ const mobileReleaseTrend = mobileVitalFields.map(field => {
+ return {
+ allReleasesRow: {
+ data: allReleasesTableData?.data?.[0]?.[field],
+ meta: allReleasesTableData?.meta?.[field],
+ },
+ thisReleaseRow: {
+ data: thisReleaseTableData?.data?.[0]?.[field],
+ meta: thisReleaseTableData?.meta?.[field],
+ },
+ };
});
- const columnData = () => {
- return (
- <div>
- {this.userMiseryField()}
- {field}
- </div>
- );
- };
+ const emptyColumn = (
+ <div>
+ <SingleEmptySubText>
+ <StyledNotAvailable tooltip={t('No results found')} />
+ </SingleEmptySubText>
+ {mobileVitalFields.map((vital, index) => (
+ <SingleEmptySubText key={vital[index]}>
+ <StyledNotAvailable tooltip={t('No results found')} />
+ </SingleEmptySubText>
+ ))}
+ </div>
+ );
return (
<Fragment>
<div>
- {/* Table description column */}
<PanelItem>{t('User Misery')}</PanelItem>
{mobileVitalTitles}
</div>
+ {allReleasesTableData?.data.length === 0
+ ? emptyColumn
+ : allReleasesTableData?.data.map((dataRow, idx) => {
+ const allReleasesMisery = miseryRenderer?.(dataRow, {
+ organization,
+ location,
+ });
+ const allReleasesMobile = mobileVitalsRenderer?.map(renderer =>
+ renderer?.(dataRow, {organization, location})
+ );
+
+ return (
+ <div key={idx}>
+ <UserMiseryPanelItem>{allReleasesMisery}</UserMiseryPanelItem>
+ {allReleasesMobile.map((mobileVital, i) => (
+ <StyledPanelItem key={i}>{mobileVital}</StyledPanelItem>
+ ))}
+ </div>
+ );
+ })}
+ {thisReleaseTableData?.data.length === 0
+ ? emptyColumn
+ : thisReleaseTableData?.data.map((dataRow, idx) => {
+ const thisReleasesMisery = miseryRenderer?.(dataRow, {
+ organization,
+ location,
+ });
+ const thisReleasesMobile = mobileVitalsRenderer?.map(renderer =>
+ renderer?.(dataRow, {organization, location})
+ );
+
+ return (
+ <div key={idx}>
+ <UserMiseryPanelItem>{thisReleasesMisery}</UserMiseryPanelItem>
+ {thisReleasesMobile.map((mobileVital, i) => (
+ <StyledPanelItem key={i}>{mobileVital}</StyledPanelItem>
+ ))}
+ </div>
+ );
+ })}
<div>
- {/* Table All Releases column */}
- {/* TODO(kelly): placeholder data. will need to add user misery data in follow-up pr */}
- {columnData()}
- </div>
- <div>
- {/* Table This Release column */}
- {columnData()}
- </div>
- <div>
- {/* Table Change column */}
- {columnData()}
+ {userMiseryTrend()}
+ {mobileReleaseTrend?.map((row, idx) => (
+ <StyledPanelItem key={idx}>
+ {renderChange(
+ row.allReleasesRow?.data as number,
+ row.thisReleaseRow?.data as number,
+ row.allReleasesRow?.meta as string
+ )}
+ </StyledPanelItem>
+ ))}
</div>
</Fragment>
);
}
- renderUnknownPerformance() {
+ function renderUnknownPerformance() {
+ const emptyColumn = (
+ <div>
+ <SingleEmptySubText>
+ <StyledNotAvailable tooltip={t('No results found')} />
+ </SingleEmptySubText>
+ </div>
+ );
+
return (
<Fragment>
<div>
- {/* Table description column */}
<PanelItem>{t('User Misery')}</PanelItem>
</div>
- <div>
- {/* TODO(kelly): placeholder data. will need to add user misery data in follow-up pr */}
- {this.userMiseryField()}
- </div>
- <div>
- {/* Table All Releases column */}
- {this.userMiseryField()}
- </div>
- <div>
- {/* Table This Release column */}
- {this.userMiseryField()}
- </div>
+ {allReleasesTableData?.data.length === 0
+ ? emptyColumn
+ : allReleasesTableData?.data.map((dataRow, idx) => {
+ const allReleasesMisery = miseryRenderer?.(dataRow, {
+ organization,
+ location,
+ });
+
+ return (
+ <div key={idx}>
+ <UserMiseryPanelItem>{allReleasesMisery}</UserMiseryPanelItem>
+ </div>
+ );
+ })}
+ {thisReleaseTableData?.data.length === 0
+ ? emptyColumn
+ : thisReleaseTableData?.data.map((dataRow, idx) => {
+ const thisReleasesMisery = miseryRenderer?.(dataRow, {
+ organization,
+ location,
+ });
+
+ return (
+ <div key={idx}>
+ <UserMiseryPanelItem>{thisReleasesMisery}</UserMiseryPanelItem>
+ </div>
+ );
+ })}
+ <div>{userMiseryTrend()}</div>
</Fragment>
);
}
- render() {
- const {project, organization, isLoading, isEmpty} = this.props;
- // Custom set the height so we don't have layout shift when results are loaded.
- const loader = <LoadingIndicator style={{margin: '70px auto'}} />;
-
- const title = FRONTEND_PLATFORMS.includes(project.platform as string)
- ? t('Frontend Performance')
- : BACKEND_PLATFORMS.includes(project.platform as string)
- ? t('Backend Performance')
- : MOBILE_PLATFORMS.includes(project.platform as string)
- ? t('Mobile Performance')
- : t('[Unknown] Performance');
- const platformPerformance = FRONTEND_PLATFORMS.includes(project.platform as string)
- ? this.renderFrontendPerformance()
- : BACKEND_PLATFORMS.includes(project.platform as string)
- ? this.renderBackendPerformance()
- : MOBILE_PLATFORMS.includes(project.platform as string)
- ? this.renderMobilePerformance()
- : this.renderUnknownPerformance();
- const isUnknownPlatform = ![
- ...FRONTEND_PLATFORMS,
- ...BACKEND_PLATFORMS,
- ...MOBILE_PLATFORMS,
- ].includes(project.platform);
+ const loader = <StyledLoadingIndicator />;
+
+ const platformPerformanceRender = {
+ [PROJECT_PERFORMANCE_TYPE.FRONTEND]: {
+ title: t('Frontend Performance'),
+ section: renderFrontendPerformance(),
+ },
+ [PROJECT_PERFORMANCE_TYPE.BACKEND]: {
+ title: t('Backend Performance'),
+ section: renderBackendPerformance(),
+ },
+ [PROJECT_PERFORMANCE_TYPE.MOBILE]: {
+ title: t('Mobile Performance'),
+ section: renderMobilePerformance(),
+ },
+ [PROJECT_PERFORMANCE_TYPE.ANY]: {
+ title: t('[Unknown] Performance'),
+ section: renderUnknownPerformance(),
+ },
+ };
+
+ const isUnknownPlatform = performanceType === PROJECT_PERFORMANCE_TYPE.ANY;
+
+ return (
+ <Fragment>
+ <HeadCellContainer>
+ {platformPerformanceRender[performanceType].title}
+ </HeadCellContainer>
+ {isUnknownPlatform && (
+ <StyledAlert type="warning" icon={<IconWarning size="md" />} system>
+ {tct(
+ 'For more performance metrics, specify which platform this project is using in [link]',
+ {
+ link: (
+ <Link to={`/settings/${organization.slug}/projects/${project.slug}/`}>
+ {t('project settings.')}
+ </Link>
+ ),
+ }
+ )}
+ </StyledAlert>
+ )}
+ <StyledPanelTable
+ isLoading={isLoading}
+ headers={[
+ <Cell key="description" align="left">
+ {t('Description')}
+ </Cell>,
+ <Cell key="releases" align="right">
+ {t('All Releases')}
+ </Cell>,
+ <Cell key="release" align="right">
+ {t('This Release')}
+ </Cell>,
+ <Cell key="change" align="right">
+ {t('Change')}
+ </Cell>,
+ ]}
+ disablePadding
+ loader={loader}
+ disableTopBorder={isUnknownPlatform}
+ >
+ {platformPerformanceRender[performanceType].section}
+ </StyledPanelTable>
+ </Fragment>
+ );
+}
- return (
- <Fragment>
- <HeadCellContainer>{title}</HeadCellContainer>
- {isUnknownPlatform ? (
- <StyledAlert type="warning" icon={<IconWarning size="md" />} system>
- For more performance metrics, specify which platform this project is using in{' '}
- <Link to={`/settings/${organization.slug}/projects/${project.slug}/`}>
- project settings.
- </Link>
- </StyledAlert>
- ) : null}
- <StyledPanelTable
- isLoading={isLoading}
- isEmpty={isEmpty}
- emptyMessage={t('No transactions found')}
- headers={[
- <Cell key="description" align="left">
- {t('Description')}
- </Cell>,
- <Cell key="releases" align="right">
- {t('All Releases')}
- </Cell>,
- <Cell key="release" align="right">
- {t('This Release')}
- </Cell>,
- <Cell key="change" align="right">
- {t('Change')}
- </Cell>,
- ]}
- disablePadding
- loader={loader}
- disableTopBorder={isUnknownPlatform}
+type Props = AsyncComponent['props'] & {
+ organization: Organization;
+ allReleasesEventView: EventView;
+ releaseEventView: EventView;
+ performanceType: string;
+ project: ReleaseProject;
+ location: Location;
+};
+
+function PerformanceCardTableWrapper({
+ organization,
+ project,
+ allReleasesEventView,
+ releaseEventView,
+ performanceType,
+ location,
+}: Props) {
+ return (
+ <DiscoverQuery
+ eventView={allReleasesEventView}
+ orgSlug={organization.slug}
+ location={location}
+ >
+ {({isLoading, tableData: allReleasesTableData}) => (
+ <DiscoverQuery
+ eventView={releaseEventView}
+ orgSlug={organization.slug}
+ location={location}
>
- {platformPerformance}
- </StyledPanelTable>
- </Fragment>
- );
- }
+ {({isLoading: isReleaseLoading, tableData: thisReleaseTableData}) => (
+ <PerformanceCardTable
+ isLoading={isLoading || isReleaseLoading}
+ organization={organization}
+ location={location}
+ project={project}
+ allReleasesEventView={allReleasesEventView}
+ releaseEventView={releaseEventView}
+ allReleasesTableData={allReleasesTableData}
+ thisReleaseTableData={thisReleaseTableData}
+ performanceType={performanceType}
+ />
+ )}
+ </DiscoverQuery>
+ )}
+ </DiscoverQuery>
+ );
}
+export default PerformanceCardTableWrapper;
+
+const emptyFieldCss = p => css`
+ color: ${p.theme.chartOther};
+ text-align: right;
+`;
+
+const StyledLoadingIndicator = styled(LoadingIndicator)`
+ margin: 70px auto;
+`;
+
const HeadCellContainer = styled('div')`
font-size: ${p => p.theme.fontSizeExtraLarge};
padding: ${space(2)};
@@ -367,19 +770,21 @@ const TitleSpace = styled('div')`
height: 24px;
`;
-const StyledUserMisery = styled(UserMisery)`
- ${PanelItem} {
- justify-content: flex-end;
- }
-`;
-
const UserMiseryPanelItem = styled(PanelItem)`
justify-content: flex-end;
`;
-const Field = styled('div')<{align: 'left' | 'right'}>`
- text-align: ${p => p.align};
- margin-left: ${p => p.align === 'left' && space(2)};
+const ApdexPanelItem = styled(PanelItem)`
+ text-align: right;
+`;
+
+const SingleEmptySubText = styled(PanelItem)`
+ display: block;
+ ${emptyFieldCss}
+`;
+
+const MultipleEmptySubText = styled('div')`
+ ${emptyFieldCss}
`;
const Cell = styled('div')<{align: 'left' | 'right'}>`
@@ -396,4 +801,21 @@ const StyledAlert = styled(Alert)`
margin-bottom: 0;
`;
-export default PerformanceCardTable;
+const StyledNotAvailable = styled(NotAvailable)`
+ text-align: right;
+`;
+
+const SubText = styled('div')`
+ color: ${p => p.theme.subText};
+ text-align: right;
+`;
+
+const TrendText = styled('div')<{color: string}>`
+ color: ${p => p.theme[p.color]};
+ text-align: right;
+`;
+
+const StyledIconArrow = styled(IconArrow)<{color: string}>`
+ color: ${p => p.theme[p.color]};
+ margin-left: ${space(0.5)};
+`;
diff --git a/static/app/views/performance/utils.tsx b/static/app/views/performance/utils.tsx
index 098a934d78f476..6cd2841df5ffdd 100644
--- a/static/app/views/performance/utils.tsx
+++ b/static/app/views/performance/utils.tsx
@@ -4,7 +4,13 @@ import {Location, LocationDescriptor, Query} from 'history';
import Duration from 'app/components/duration';
import {ALL_ACCESS_PROJECTS} from 'app/constants/globalSelectionHeader';
import {backend, frontend, mobile} from 'app/data/platformCategories';
-import {GlobalSelection, Organization, OrganizationSummary, Project} from 'app/types';
+import {
+ GlobalSelection,
+ Organization,
+ OrganizationSummary,
+ Project,
+ ReleaseProject,
+} from 'app/types';
import {defined} from 'app/utils';
import {trackAnalyticsEvent} from 'app/utils/analytics';
import {statsPeriodToDays} from 'app/utils/dates';
@@ -34,13 +40,15 @@ const BACKEND_PLATFORMS: string[] = [...backend];
const MOBILE_PLATFORMS: string[] = [...mobile];
export function platformToPerformanceType(
- projects: Project[],
+ projects: (Project | ReleaseProject)[],
projectIds: readonly number[]
) {
if (projectIds.length === 0 || projectIds[0] === ALL_ACCESS_PROJECTS) {
return PROJECT_PERFORMANCE_TYPE.ANY;
}
- const selectedProjects = projects.filter(p => projectIds.includes(parseInt(p.id, 10)));
+ const selectedProjects = projects.filter(p =>
+ projectIds.includes(parseInt(`${p.id}`, 10))
+ );
if (selectedProjects.length === 0 || selectedProjects.some(p => !p.platform)) {
return PROJECT_PERFORMANCE_TYPE.ANY;
}
diff --git a/static/app/views/releases/detail/overview/index.tsx b/static/app/views/releases/detail/overview/index.tsx
index 22c3e3b07b1cf6..9c39e178523670 100644
--- a/static/app/views/releases/detail/overview/index.tsx
+++ b/static/app/views/releases/detail/overview/index.tsx
@@ -29,6 +29,7 @@ import {
import {getUtcDateString} from 'app/utils/dates';
import {TableDataRow} from 'app/utils/discover/discoverQuery';
import EventView from 'app/utils/discover/eventView';
+import {MobileVital, WebVital} from 'app/utils/discover/fields';
import {formatVersion} from 'app/utils/formatters';
import {decodeScalar} from 'app/utils/queryString';
import routeTitleGen from 'app/utils/routeTitle';
@@ -39,6 +40,10 @@ import AsyncView from 'app/views/asyncView';
import {DisplayModes} from 'app/views/performance/transactionSummary/transactionOverview/charts';
import {transactionSummaryRouteWithQuery} from 'app/views/performance/transactionSummary/utils';
import {TrendChangeType, TrendView} from 'app/views/performance/trends/types';
+import {
+ platformToPerformanceType,
+ PROJECT_PERFORMANCE_TYPE,
+} from 'app/views/performance/utils';
import {getReleaseParams, isReleaseArchived, ReleaseBounds} from '../../utils';
import {ReleaseContext} from '..';
@@ -182,6 +187,107 @@ class ReleaseOverview extends AsyncView<Props> {
return trendView;
}
+ getReleasePerformanceEventView(
+ performanceType: string,
+ baseQuery: NewQuery
+ ): EventView {
+ const eventView =
+ performanceType === PROJECT_PERFORMANCE_TYPE.FRONTEND
+ ? (EventView.fromSavedQuery({
+ ...baseQuery,
+ fields: [
+ ...baseQuery.fields,
+ `p75(${WebVital.FCP})`,
+ `p75(${WebVital.FID})`,
+ `p75(${WebVital.LCP})`,
+ `p75(${WebVital.CLS})`,
+ 'p75(spans.http)',
+ 'p75(spans.browser)',
+ 'p75(spans.resource)',
+ ],
+ }) as EventView)
+ : performanceType === PROJECT_PERFORMANCE_TYPE.BACKEND
+ ? (EventView.fromSavedQuery({
+ ...baseQuery,
+ fields: [...baseQuery.fields, 'apdex()', 'p75(spans.http)', 'p75(spans.db)'],
+ }) as EventView)
+ : performanceType === PROJECT_PERFORMANCE_TYPE.MOBILE
+ ? (EventView.fromSavedQuery({
+ ...baseQuery,
+ fields: [
+ ...baseQuery.fields,
+ `p75(${MobileVital.AppStartCold})`,
+ `p75(${MobileVital.AppStartWarm})`,
+ `p75(${MobileVital.FramesSlow})`,
+ `p75(${MobileVital.FramesFrozen})`,
+ ],
+ }) as EventView)
+ : (EventView.fromSavedQuery({
+ ...baseQuery,
+ }) as EventView);
+
+ return eventView;
+ }
+
+ getAllReleasesPerformanceView(
+ projectId: number,
+ performanceType: string,
+ releaseBounds: ReleaseBounds
+ ) {
+ const {selection, location} = this.props;
+ const {environments} = selection;
+
+ const {start, end, statsPeriod} = getReleaseParams({
+ location,
+ releaseBounds,
+ });
+
+ const baseQuery: NewQuery = {
+ id: undefined,
+ version: 2,
+ name: 'All Releases',
+ query: 'event.type:transaction',
+ fields: ['user_misery()'],
+ range: statsPeriod || undefined,
+ environment: environments,
+ projects: [projectId],
+ start: start ? getUtcDateString(start) : undefined,
+ end: end ? getUtcDateString(end) : undefined,
+ };
+
+ return this.getReleasePerformanceEventView(performanceType, baseQuery);
+ }
+
+ getReleasePerformanceView(
+ version: string,
+ projectId: number,
+ performanceType: string,
+ releaseBounds: ReleaseBounds
+ ) {
+ const {selection, location} = this.props;
+ const {environments} = selection;
+
+ const {start, end, statsPeriod} = getReleaseParams({
+ location,
+ releaseBounds,
+ });
+
+ const baseQuery: NewQuery = {
+ id: undefined,
+ version: 2,
+ name: `Release:${version}`,
+ query: `event.type:transaction release:${version}`,
+ fields: ['user_misery()'],
+ range: statsPeriod || undefined,
+ environment: environments,
+ projects: [projectId],
+ start: start ? getUtcDateString(start) : undefined,
+ end: end ? getUtcDateString(end) : undefined,
+ };
+
+ return this.getReleasePerformanceEventView(performanceType, baseQuery);
+ }
+
get pageDateTime(): DateTimeObject {
const query = this.props.location.query;
@@ -268,7 +374,7 @@ class ReleaseOverview extends AsyncView<Props> {
'release-comparison-performance'
);
const {environments} = selection;
-
+ const performanceType = platformToPerformanceType([project], [project.id]);
const {selectedSort, sortOptions} = getTransactionsListSort(location);
const releaseEventView = this.getReleaseEventView(
version,
@@ -286,6 +392,17 @@ class ReleaseOverview extends AsyncView<Props> {
releaseMeta.released,
releaseBounds
);
+ const allReleasesPerformanceView = this.getAllReleasesPerformanceView(
+ project.id,
+ performanceType,
+ releaseBounds
+ );
+ const releasePerformanceView = this.getReleasePerformanceView(
+ version,
+ project.id,
+ performanceType,
+ releaseBounds
+ );
const generateLink = {
transaction: generateTransactionLink(
@@ -397,9 +514,10 @@ class ReleaseOverview extends AsyncView<Props> {
<PerformanceCardTable
organization={organization}
project={project}
- isLoading={loading}
- // TODO(kelly): hardcoding this until I have data
- isEmpty={false}
+ location={location}
+ allReleasesEventView={allReleasesPerformanceView}
+ releaseEventView={releasePerformanceView}
+ performanceType={performanceType}
/>
) : (
<TransactionsList
|
a2816ad98814c57044fd6767ca4628ea23ddb468
|
2024-04-22 20:30:36
|
Yagiz Nizipli
|
perf: remove snuba orjson experiment (#69411)
| false
|
remove snuba orjson experiment (#69411)
|
perf
|
diff --git a/src/sentry/snuba/tasks.py b/src/sentry/snuba/tasks.py
index 359cfd3de0a854..9cbd11c6f62929 100644
--- a/src/sentry/snuba/tasks.py
+++ b/src/sentry/snuba/tasks.py
@@ -9,7 +9,6 @@
from django.utils import timezone
from sentry import features
-from sentry.features.rollout import in_random_rollout
from sentry.models.environment import Environment
from sentry.search.events.types import ParamsType
from sentry.snuba.dataset import Dataset, EntityKey
@@ -23,7 +22,7 @@
)
from sentry.snuba.models import QuerySubscription, SnubaQuery
from sentry.tasks.base import instrumented_task
-from sentry.utils import json, metrics
+from sentry.utils import metrics
from sentry.utils.snuba import SNUBA_INFO, SnubaError, _snuba_pool
if TYPE_CHECKING:
@@ -253,10 +252,7 @@ def _create_snql_in_snuba(subscription, snuba_query, snql_query, entity_subscrip
entity_key = get_entity_key_from_request(snql_query)
- if in_random_rollout("snuba.snql.enable-orjson"):
- post_body: str | bytes = orjson.dumps(body)
- else:
- post_body = json.dumps(body)
+ post_body: str | bytes = orjson.dumps(body)
response = _snuba_pool.urlopen(
"POST",
f"/{snuba_query.dataset}/{entity_key.value}/subscriptions",
@@ -266,10 +262,8 @@ def _create_snql_in_snuba(subscription, snuba_query, snql_query, entity_subscrip
metrics.incr("snuba.snql.subscription.http.error", tags={"dataset": snuba_query.dataset})
raise SnubaError("HTTP %s response from Snuba!" % response.status)
- if in_random_rollout("snuba.snql.enable-orjson"):
- with sentry_sdk.start_span(op="sentry.utils.json.loads"):
- return orjson.loads(response.data)["subscription_id"]
- return json.loads(response.data)["subscription_id"]
+ with sentry_sdk.start_span(op="sentry.utils.json.loads"):
+ return orjson.loads(response.data)["subscription_id"]
def _delete_from_snuba(dataset: Dataset, subscription_id: str, entity_key: EntityKey) -> None:
|
5a1bad3fd9ecd2a70e00ae41f833006ea39e4bda
|
2024-04-23 00:54:22
|
Gabe Villalobos
|
fix(hybrid-cloud): User deletion outboxes always fan out to all regions (#69363)
| false
|
User deletion outboxes always fan out to all regions (#69363)
|
fix
|
diff --git a/src/sentry/models/user.py b/src/sentry/models/user.py
index 2349e86649aedf..29521694ca5e2d 100644
--- a/src/sentry/models/user.py
+++ b/src/sentry/models/user.py
@@ -42,7 +42,7 @@
from sentry.services.hybrid_cloud.organization import RpcRegionUser, organization_service
from sentry.services.hybrid_cloud.user import RpcUser
from sentry.types.integrations import EXTERNAL_PROVIDERS, ExternalProviders
-from sentry.types.region import find_regions_for_user
+from sentry.types.region import find_all_region_names, find_regions_for_user
from sentry.utils.http import absolute_uri
from sentry.utils.retries import TimedRetryPolicy
@@ -202,7 +202,7 @@ def delete(self):
avatar = self.avatar.first()
if avatar:
avatar.delete()
- for outbox in self.outboxes_for_update():
+ for outbox in self.outboxes_for_update(is_user_delete=True):
outbox.save()
return super().delete()
@@ -305,13 +305,23 @@ def send_confirm_emails(self, is_new_user=False):
for email in email_list:
self.send_confirm_email_singular(email, is_new_user)
- def outboxes_for_update(self) -> list[ControlOutboxBase]:
- return User.outboxes_for_user_update(self.id)
+ def outboxes_for_update(self, is_user_delete: bool = False) -> list[ControlOutboxBase]:
+ return User.outboxes_for_user_update(self.id, is_user_delete=is_user_delete)
@staticmethod
- def outboxes_for_user_update(identifier: int) -> list[ControlOutboxBase]:
+ def outboxes_for_user_update(
+ identifier: int, is_user_delete: bool = False
+ ) -> list[ControlOutboxBase]:
+ # User deletions must fan out to all regions to ensure cascade behavior
+ # of anything with a HybridCloudForeignKey, even if the user is no longer
+ # a member of any organizations in that region.
+ if is_user_delete:
+ user_regions = set(find_all_region_names())
+ else:
+ user_regions = find_regions_for_user(identifier)
+
return OutboxCategory.USER_UPDATE.as_control_outboxes(
- region_names=find_regions_for_user(identifier),
+ region_names=user_regions,
object_identifier=identifier,
shard_identifier=identifier,
)
diff --git a/tests/sentry/models/test_user.py b/tests/sentry/models/test_user.py
index 768717fff0837d..16a6ba033eb2b3 100644
--- a/tests/sentry/models/test_user.py
+++ b/tests/sentry/models/test_user.py
@@ -9,8 +9,8 @@
from sentry.testutils.cases import TestCase
from sentry.testutils.hybrid_cloud import HybridCloudTestMixin
from sentry.testutils.outbox import outbox_runner
-from sentry.testutils.silo import assume_test_silo_mode, control_silo_test
-from sentry.types.region import Region, RegionCategory
+from sentry.testutils.silo import assume_test_silo_mode, assume_test_silo_mode_of, control_silo_test
+from sentry.types.region import Region, RegionCategory, find_regions_for_user
_TEST_REGIONS = (
Region("na", 1, "http://eu.testserver", RegionCategory.MULTI_TENANT),
@@ -34,9 +34,9 @@ def setUp(self):
)
@assume_test_silo_mode(SiloMode.REGION)
- def user_tombstone_exists(self) -> bool:
+ def user_tombstone_exists(self, user_id: int) -> bool:
return RegionTombstone.objects.filter(
- table_name="auth_user", object_identifier=self.user_id
+ table_name="auth_user", object_identifier=user_id
).exists()
@assume_test_silo_mode(SiloMode.REGION)
@@ -44,11 +44,11 @@ def get_user_saved_search_count(self) -> int:
return SavedSearch.objects.filter(owner_id=self.user_id).count()
def test_simple(self):
- assert not self.user_tombstone_exists()
+ assert not self.user_tombstone_exists(user_id=self.user_id)
with outbox_runner():
self.user.delete()
assert not User.objects.filter(id=self.user_id).exists()
- assert self.user_tombstone_exists()
+ assert self.user_tombstone_exists(user_id=self.user_id)
# cascade is asynchronous, ensure there is still related search,
assert self.get_user_saved_search_count() == 1
@@ -87,6 +87,35 @@ def test_cascades_to_multiple_regions(self):
schedule_hybrid_cloud_foreign_key_jobs()
assert self.get_user_saved_search_count() == 0
+ def test_deletions_create_tombstones_in_regions_for_user_with_no_orgs(self):
+ # Create a user with no org memberships
+ user_to_delete = self.create_user("[email protected]")
+ user_id = user_to_delete.id
+ with outbox_runner():
+ user_to_delete.delete()
+
+ assert self.user_tombstone_exists(user_id=user_id)
+
+ def test_cascades_to_regions_even_if_user_ownership_revoked(self):
+ eu_org = self.create_organization(region=_TEST_REGIONS[1])
+ self.create_member(user=self.user, organization=eu_org)
+ self.create_saved_search(name="eu-search", owner=self.user, organization=eu_org)
+ assert self.get_user_saved_search_count() == 2
+
+ with outbox_runner(), assume_test_silo_mode_of(OrganizationMember):
+ for member in OrganizationMember.objects.filter(user_id=self.user.id):
+ member.delete()
+
+ assert find_regions_for_user(self.user.id) == set()
+
+ with outbox_runner():
+ self.user.delete()
+
+ assert self.get_user_saved_search_count() == 2
+ with assume_test_silo_mode(SiloMode.REGION), self.tasks():
+ schedule_hybrid_cloud_foreign_key_jobs()
+ assert self.get_user_saved_search_count() == 0
+
@control_silo_test
class UserDetailsTest(TestCase):
|
ae1688d7fb810ae9d9afbafd03abf5208609dd4a
|
2023-09-14 23:06:00
|
Lyn Nagara
|
test: Opt in more tests to snuba-ci (#56266)
| false
|
Opt in more tests to snuba-ci (#56266)
|
test
|
diff --git a/tests/sentry/snuba/metrics/test_metrics_layer/test_metrics_enhanced_performance.py b/tests/sentry/snuba/metrics/test_metrics_layer/test_metrics_enhanced_performance.py
index 7d1b66de833c5c..0e5caad9eeff5a 100644
--- a/tests/sentry/snuba/metrics/test_metrics_layer/test_metrics_enhanced_performance.py
+++ b/tests/sentry/snuba/metrics/test_metrics_layer/test_metrics_enhanced_performance.py
@@ -47,6 +47,7 @@
pytestmark = pytest.mark.sentry_metrics
[email protected]_ci
@freeze_time(BaseMetricsLayerTestCase.MOCK_DATETIME)
class PerformanceMetricsLayerTestCase(BaseMetricsLayerTestCase, TestCase):
@property
diff --git a/tests/sentry/snuba/metrics/test_metrics_layer/test_release_health.py b/tests/sentry/snuba/metrics/test_metrics_layer/test_release_health.py
index 591cdf147d19b4..7020d9ddb4c417 100644
--- a/tests/sentry/snuba/metrics/test_metrics_layer/test_release_health.py
+++ b/tests/sentry/snuba/metrics/test_metrics_layer/test_release_health.py
@@ -18,6 +18,7 @@
pytestmark = pytest.mark.sentry_metrics
[email protected]_ci
@freeze_time(BaseMetricsLayerTestCase.MOCK_DATETIME)
class ReleaseHealthMetricsLayerTestCase(BaseMetricsLayerTestCase, TestCase):
@property
diff --git a/tests/sentry/snuba/test_entity_subscriptions.py b/tests/sentry/snuba/test_entity_subscriptions.py
index 2aeb232f5b5cb0..b1136285910c68 100644
--- a/tests/sentry/snuba/test_entity_subscriptions.py
+++ b/tests/sentry/snuba/test_entity_subscriptions.py
@@ -33,6 +33,7 @@
pytestmark = pytest.mark.sentry_metrics
[email protected]_ci
class EntitySubscriptionTestCase(TestCase):
def setUp(self) -> None:
super().setUp()
|
14bc9cea1078825ee5d209718d36cb7aa2eca7eb
|
2020-11-11 09:29:46
|
Evan Purkhiser
|
fix(py3): Fix byte requirement in collectstatic (#21925)
| false
|
Fix byte requirement in collectstatic (#21925)
|
fix
|
diff --git a/src/sentry/management/commands/collectstatic.py b/src/sentry/management/commands/collectstatic.py
index 59482a022d7672..2cb8799bae339d 100644
--- a/src/sentry/management/commands/collectstatic.py
+++ b/src/sentry/management/commands/collectstatic.py
@@ -47,5 +47,5 @@ def collect(self):
echo("-----------------")
echo(version)
with open(self.storage.path(VERSION_PATH), "wb") as fp:
- fp.write(version)
+ fp.write(version.encode("utf-8"))
return collected
|
08dbd81fbad3e44c92a073f67a20e7e9c9bca36d
|
2022-07-06 10:05:28
|
Snigdha Sharma
|
fix(release-notification): Add custom email referrer
| false
|
Add custom email referrer
|
fix
|
diff --git a/src/sentry/notifications/notifications/rules.py b/src/sentry/notifications/notifications/rules.py
index 7b585a0a4ed40c..db6fdb6494a417 100644
--- a/src/sentry/notifications/notifications/rules.py
+++ b/src/sentry/notifications/notifications/rules.py
@@ -22,7 +22,7 @@
from sentry.plugins.base.structs import Notification
from sentry.types.integrations import ExternalProviders
from sentry.utils import metrics
-from sentry.utils.http import absolute_uri
+from sentry.utils.http import absolute_uri, urlencode
logger = logging.getLogger(__name__)
@@ -210,7 +210,9 @@ def get_context(self) -> MutableMapping[str, Any]:
"project_label": self.project.get_full_name(),
"group": self.group,
"event": self.event,
- "link": get_group_settings_link(self.group, environment, rule_details),
+ "link": get_group_settings_link(
+ self.group, environment, rule_details, referrer="alert_email_release"
+ ),
"rules": rule_details,
"has_integrations": has_integrations(self.organization, self.project),
"enhanced_privacy": enhanced_privacy,
@@ -251,8 +253,11 @@ def get_release_commits(self, release: Release) -> Sequence[CommitData]:
]
def release_url(self, release: Release) -> str:
- return str(
- absolute_uri(
- f"/organizations/{release.organization.slug}/releases/{release.version}/?project={release.project_id}"
- )
+ params = {"project": release.project_id, "referrer": "alert_email_release"}
+ url = "/organizations/{org}/releases/{version}/{params}".format(
+ org=release.organization.slug,
+ version=release.version,
+ params="?" + urlencode(params),
)
+
+ return str(absolute_uri(url))
diff --git a/src/sentry/notifications/utils/__init__.py b/src/sentry/notifications/utils/__init__.py
index 09a02406b8816d..f7c1ff4e22bd18 100644
--- a/src/sentry/notifications/utils/__init__.py
+++ b/src/sentry/notifications/utils/__init__.py
@@ -156,6 +156,7 @@ def get_group_settings_link(
environment: str | None,
rule_details: Sequence[NotificationRuleDetails] | None = None,
alert_timestamp: int | None = None,
+ referrer: str = "alert_email",
) -> str:
alert_rule_id: int | None = rule_details[0].id if rule_details and rule_details[0].id else None
return str(
@@ -163,9 +164,9 @@ def get_group_settings_link(
+ (
""
if not alert_rule_id
- else get_email_link_extra_params(
- "alert_email", environment, rule_details, alert_timestamp
- )[alert_rule_id]
+ else get_email_link_extra_params(referrer, environment, rule_details, alert_timestamp)[
+ alert_rule_id
+ ]
)
)
|
192258d7316b402e60a091d72939693feaea469f
|
2020-04-15 23:33:30
|
Chris Fuller
|
fix(workflow): New migration to drop dangling alertrule constraint (#18268)
| false
|
New migration to drop dangling alertrule constraint (#18268)
|
fix
|
diff --git a/src/sentry/migrations/0063_drop_alertrule_constraint.py b/src/sentry/migrations/0063_drop_alertrule_constraint.py
new file mode 100644
index 00000000000000..62d2aa1e6f31bc
--- /dev/null
+++ b/src/sentry/migrations/0063_drop_alertrule_constraint.py
@@ -0,0 +1,52 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.27 on 2020-04-08 01:07
+from __future__ import unicode_literals
+
+from django.db import migrations
+import django.db.models.deletion
+import sentry.db.models.fields.foreignkey
+
+class Migration(migrations.Migration):
+ # This flag is used to mark that a migration shouldn't be automatically run in
+ # production. We set this to True for operations that we think are risky and want
+ # someone from ops to run manually and monitor.
+ # General advice is that if in doubt, mark your migration as `is_dangerous`.
+ # Some things you should always mark as dangerous:
+ # - Large data migrations. Typically we want these to be run manually by ops so that
+ # they can be monitored. Since data migrations will now hold a transaction open
+ # this is even more important.
+ # - Adding columns to highly active tables, even ones that are NULL.
+ is_dangerous = False
+
+ # This flag is used to decide whether to run this migration in a transaction or not.
+ # By default we prefer to run in a transaction, but for migrations where you want
+ # to `CREATE INDEX CONCURRENTLY` this needs to be set to False. Typically you'll
+ # want to create an index concurrently when adding one to an existing table.
+ atomic = False
+
+
+ dependencies = [
+ ('sentry', '0062_key_transactions_unique_with_owner'),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ database_operations=[
+ migrations.RunSQL("""
+ ALTER TABLE sentry_alertrule DROP CONSTRAINT IF EXISTS sentry_alertrule_organization_id_382634eccd5f9371_uniq;
+ """,
+ reverse_sql="""DO $$
+ BEGIN
+ BEGIN
+ ALTER TABLE sentry_alertrule ADD CONSTRAINT sentry_alertrule_organization_id_382634eccd5f9371_uniq UNIQUE (organization_id, name);
+ EXCEPTION
+ WHEN duplicate_table THEN
+ END;
+ END $$;
+ """
+ ),
+ ],
+ state_operations=[
+ ],
+ ),
+ ]
|
74e506b93959f645b29cf33ec0ff31311fd3df73
|
2024-12-20 01:23:40
|
Malachi Willey
|
fix(query-builder): Prevent error when filter sections don't match filter keys (#82392)
| false
|
Prevent error when filter sections don't match filter keys (#82392)
|
fix
|
diff --git a/static/app/components/searchQueryBuilder/tokens/filterKeyListBox/utils.tsx b/static/app/components/searchQueryBuilder/tokens/filterKeyListBox/utils.tsx
index 6e65f2d675cad2..6545cb84fe462a 100644
--- a/static/app/components/searchQueryBuilder/tokens/filterKeyListBox/utils.tsx
+++ b/static/app/components/searchQueryBuilder/tokens/filterKeyListBox/utils.tsx
@@ -16,6 +16,7 @@ import type {
} from 'sentry/components/searchQueryBuilder/types';
import {t} from 'sentry/locale';
import type {RecentSearch, Tag, TagCollection} from 'sentry/types/group';
+import {defined} from 'sentry/utils';
import {type FieldDefinition, FieldKind} from 'sentry/utils/fields';
import {escapeFilterValue} from 'sentry/utils/tokenizeSearch';
@@ -70,9 +71,14 @@ export function createSection(
key: section.value,
value: section.value,
label: section.label,
- options: section.children.map(key =>
- createItem(keys[key], getFieldDefinition(key), section)
- ),
+ options: section.children
+ .map(key => {
+ if (!keys[key]) {
+ return null;
+ }
+ return createItem(keys[key], getFieldDefinition(key), section);
+ })
+ .filter(defined),
type: 'section',
};
}
diff --git a/static/app/views/discover/homepage.spec.tsx b/static/app/views/discover/homepage.spec.tsx
index d7a1c15ef01b50..f41dcca26acc5a 100644
--- a/static/app/views/discover/homepage.spec.tsx
+++ b/static/app/views/discover/homepage.spec.tsx
@@ -9,6 +9,7 @@ import {
screen,
userEvent,
waitFor,
+ within,
} from 'sentry-test/reactTestingLibrary';
import * as pageFilterUtils from 'sentry/components/organizations/pageFilters/persistence';
@@ -91,6 +92,10 @@ describe('Discover > Homepage', () => {
method: 'GET',
body: {},
});
+ MockApiClient.addMockResponse({
+ url: '/organizations/org-slug/recent-searches/',
+ body: [],
+ });
});
it('renders the Discover banner', async () => {
@@ -180,9 +185,11 @@ describe('Discover > Homepage', () => {
await userEvent.click(await screen.findByText('Columns'));
- await userEvent.click(screen.getByTestId('label'));
- await userEvent.click(screen.getByText('event.type'));
- await userEvent.click(screen.getByText('Apply'));
+ const modal = await screen.findByRole('dialog');
+
+ await userEvent.click(within(modal).getByTestId('label'));
+ await userEvent.click(within(modal).getByText('event.type'));
+ await userEvent.click(within(modal).getByText('Apply'));
expect(browserHistory.push).toHaveBeenCalledWith(
expect.objectContaining({
|
16648d38db73091b6bbb3688266f22324862cc80
|
2024-07-26 02:48:56
|
anthony sottile
|
ref: upgrade mypy to 1.11.0 (#75020)
| false
|
upgrade mypy to 1.11.0 (#75020)
|
ref
|
diff --git a/requirements-dev-frozen.txt b/requirements-dev-frozen.txt
index 718cba50616e2c..6e0b1640b3d457 100644
--- a/requirements-dev-frozen.txt
+++ b/requirements-dev-frozen.txt
@@ -101,7 +101,7 @@ mmh3==4.0.0
more-itertools==8.13.0
msgpack==1.0.7
msgpack-types==0.2.0
-mypy==1.10.0
+mypy==1.11.0
mypy-extensions==1.0.0
nodeenv==1.8.0
oauthlib==3.1.0
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 63abb28fa5b73e..2d434ae8ae7694 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -39,7 +39,7 @@ sentry-forked-django-stubs>=5.0.2.post6
sentry-forked-djangorestframework-stubs>=3.15.0.post1
lxml-stubs
msgpack-types>=0.2.0
-mypy>=1.10
+mypy>=1.11
types-beautifulsoup4
types-cachetools
types-croniter
diff --git a/src/sentry/models/authenticator.py b/src/sentry/models/authenticator.py
index df0f03ff4cbcc8..15c95e6dbbe81c 100644
--- a/src/sentry/models/authenticator.py
+++ b/src/sentry/models/authenticator.py
@@ -191,7 +191,7 @@ def reset_fields(self, save=True):
if save:
self.save()
- def __repr__(self):
+ def __repr__(self) -> str: # type: ignore[override] # python/mypy#17562
return f"<Authenticator user={self.user.email!r} interface={self.interface.interface_id!r}>"
@classmethod
diff --git a/src/sentry/rules/conditions/event_frequency.py b/src/sentry/rules/conditions/event_frequency.py
index 0ec068db0fa249..3aaa5215170707 100644
--- a/src/sentry/rules/conditions/event_frequency.py
+++ b/src/sentry/rules/conditions/event_frequency.py
@@ -177,7 +177,7 @@ def passes(self, event: GroupEvent, state: EventState) -> bool:
comparison_interval = COMPARISON_INTERVALS[comparison_interval_option][1]
_, duration = self.intervals[interval]
try:
- current_value = self.get_rate(duration=duration, comparison_interval=comparison_interval, event=event, environment_id=self.rule.environment_id, comparison_type=comparison_type) # type: ignore[arg-type, union-attr]
+ current_value = self.get_rate(duration=duration, comparison_interval=comparison_interval, event=event, environment_id=self.rule.environment_id, comparison_type=comparison_type) # type: ignore[union-attr]
# XXX(CEO): once inc-666 work is concluded, rm try/except
except RateLimitExceeded:
metrics.incr("rule.event_frequency.snuba_query_limit")
diff --git a/tests/tools/mypy_helpers/test_plugin.py b/tests/tools/mypy_helpers/test_plugin.py
index 42af5e0fb740a2..f7eaa93e045d93 100644
--- a/tests/tools/mypy_helpers/test_plugin.py
+++ b/tests/tools/mypy_helpers/test_plugin.py
@@ -234,78 +234,3 @@ def _mypy() -> tuple[int, str]:
cfg.write_text('[tool.mypy]\nplugins = ["tools.mypy_helpers.plugin"]\n')
ret, out = _mypy()
assert ret == 0
-
-
-def test_resolution_of_objects_across_typevar(tmp_path: pathlib.Path) -> None:
- src = """\
-from typing import assert_type, TypeVar
-
-from sentry.db.models.base import Model
-
-M = TypeVar("M", bound=Model, covariant=True)
-
-def f(m: type[M]) -> M:
- return m.objects.get()
-
-class C(Model): pass
-
-assert_type(f(C), C)
-"""
- expected = """\
-<string>:8: error: Incompatible return value type (got "Model", expected "M") [return-value]
-Found 1 error in 1 file (checked 1 source file)
-"""
-
- # tools tests aren't allowed to import from `sentry` so we fixture
- # the particular source file we are testing
- models_dir = tmp_path.joinpath("sentry/db/models")
- models_dir.mkdir(parents=True)
-
- models_base_src = """\
-from typing import ClassVar, Self
-
-from .manager.base import BaseManager
-
-class Model:
- objects: ClassVar[BaseManager[Self]]
-"""
- models_dir.joinpath("base.pyi").write_text(models_base_src)
-
- manager_dir = models_dir.joinpath("manager")
- manager_dir.mkdir(parents=True)
-
- manager_base_src = """\
-from typing import Generic, TypeVar
-
-M = TypeVar("M")
-
-class BaseManager(Generic[M]):
- def get(self) -> M: ...
- """
- manager_dir.joinpath("base.pyi").write_text(manager_base_src)
-
- cfg = tmp_path.joinpath("mypy.toml")
- cfg.write_text("[tool.mypy]\nplugins = []\n")
-
- # can't use our helper above because we're fixturing sentry src, so mimic it here
- def _mypy() -> tuple[int, str]:
- ret = subprocess.run(
- (
- *(sys.executable, "-m", "mypy"),
- *("--config", cfg),
- *("-c", src),
- ),
- env={**os.environ, "MYPYPATH": str(tmp_path)},
- capture_output=True,
- encoding="UTF-8",
- )
- assert not ret.stderr
- return ret.returncode, ret.stdout
-
- ret, out = _mypy()
- assert ret
- assert out == expected
-
- cfg.write_text('[tool.mypy]\nplugins = ["tools.mypy_helpers.plugin"]\n')
- ret, out = _mypy()
- assert ret == 0
diff --git a/tools/mypy_helpers/plugin.py b/tools/mypy_helpers/plugin.py
index 8bd4214e3ce82e..9ee797a4541770 100644
--- a/tools/mypy_helpers/plugin.py
+++ b/tools/mypy_helpers/plugin.py
@@ -17,8 +17,6 @@
NoneType,
Type,
TypeOfAny,
- TypeType,
- TypeVarType,
UnionType,
)
@@ -116,23 +114,6 @@ def _lazy_service_wrapper_attribute(ctx: AttributeContext, *, attr: str) -> Type
return member
-def _resolve_objects_for_typevars(ctx: AttributeContext) -> Type:
- # XXX: hack around python/mypy#17395
-
- # self: type[<TypeVar>]
- # default_attr_type: BaseManager[ConcreteTypeVarBound]
- if (
- isinstance(ctx.type, TypeType)
- and isinstance(ctx.type.item, TypeVarType)
- and isinstance(ctx.default_attr_type, Instance)
- and ctx.default_attr_type.type.fullname == "sentry.db.models.manager.base.BaseManager"
- ):
- tvar = ctx.type.item
- return ctx.default_attr_type.copy_modified(args=(tvar,))
- else:
- return ctx.default_attr_type
-
-
class SentryMypyPlugin(Plugin):
def get_function_signature_hook(
self, fullname: str
@@ -146,12 +127,6 @@ def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None
else:
return None
- def get_class_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:
- if fullname.startswith("sentry.") and fullname.endswith(".objects"):
- return _resolve_objects_for_typevars
- else:
- return None
-
def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:
if fullname.startswith("sentry.utils.lazy_service_wrapper.LazyServiceWrapper."):
_, attr = fullname.rsplit(".", 1)
|
24807859b5ffbda04a364711a7eeca84d1446d06
|
2023-10-04 23:45:35
|
volokluev
|
ref(ci): remove tests that don't query snuba from the snuba test file (#57420)
| false
|
remove tests that don't query snuba from the snuba test file (#57420)
|
ref
|
diff --git a/tests/sentry/api/test_organization_events.py b/tests/sentry/api/test_organization_events.py
new file mode 100644
index 00000000000000..682e19094627e2
--- /dev/null
+++ b/tests/sentry/api/test_organization_events.py
@@ -0,0 +1,158 @@
+from unittest import mock
+
+from django.urls import reverse
+
+from sentry.search.events import constants
+from sentry.testutils.cases import APITestCase
+from sentry.testutils.helpers.datetime import before_now, iso_format
+from sentry.testutils.silo import region_silo_test
+from sentry.utils.snuba import QueryExecutionError, QueryIllegalTypeOfArgument, RateLimitExceeded
+
+MAX_QUERYABLE_TRANSACTION_THRESHOLDS = 1
+
+
+@region_silo_test(stable=True)
+class OrganizationEventsEndpointTest(APITestCase):
+ viewname = "sentry-api-0-organization-events"
+ referrer = "api.organization-events"
+
+ def setUp(self):
+ super().setUp()
+ self.ten_mins_ago = before_now(minutes=10)
+ self.ten_mins_ago_iso = iso_format(self.ten_mins_ago)
+ self.features = {}
+
+ def client_get(self, *args, **kwargs):
+ return self.client.get(*args, **kwargs)
+
+ def reverse_url(self):
+ return reverse(
+ self.viewname,
+ kwargs={"organization_slug": self.organization.slug},
+ )
+
+ def do_request(self, query, features=None, **kwargs):
+ if features is None:
+ features = {"organizations:discover-basic": True}
+ features.update(self.features)
+ self.login_as(user=self.user)
+ with self.feature(features):
+ return self.client_get(self.reverse_url(), query, format="json", **kwargs)
+
+ def test_api_key_request(self):
+ self.store_event(
+ data={
+ "event_id": "a" * 32,
+ "environment": "staging",
+ "timestamp": self.ten_mins_ago_iso,
+ },
+ project_id=self.project.id,
+ )
+
+ # Project ID cannot be inferred when using an org API key, so that must
+ # be passed in the parameters
+ api_key = self.create_api_key(organization=self.organization, scope_list=["org:read"])
+ query = {"field": ["project.name", "environment"], "project": [self.project.id]}
+
+ url = self.reverse_url()
+ response = self.client_get(
+ url,
+ query,
+ format="json",
+ HTTP_AUTHORIZATION=self.create_basic_auth_header(api_key.key),
+ )
+
+ assert response.status_code == 200, response.content
+ assert len(response.data["data"]) == 1
+ assert response.data["data"][0]["project.name"] == self.project.slug
+
+ @mock.patch("sentry.snuba.discover.query")
+ def test_api_token_referrer(self, mock):
+ mock.return_value = {}
+ # Project ID cannot be inferred when using an org API key, so that must
+ # be passed in the parameters
+ api_key = self.create_api_key(organization=self.organization, scope_list=["org:read"])
+
+ query = {
+ "field": ["project.name", "environment"],
+ "project": [self.project.id],
+ }
+
+ features = {"organizations:discover-basic": True}
+ features.update(self.features)
+ url = self.reverse_url()
+
+ with self.feature(features):
+ self.client_get(
+ url,
+ query,
+ format="json",
+ HTTP_AUTHORIZATION=self.create_basic_auth_header(api_key.key),
+ )
+
+ _, kwargs = mock.call_args
+ self.assertEqual(kwargs["referrer"], "api.auth-token.events")
+
+ @mock.patch("sentry.snuba.discover.query")
+ def test_invalid_referrer(self, mock):
+ mock.return_value = {}
+
+ query = {
+ "field": ["user"],
+ "referrer": "api.performance.invalid",
+ "project": [self.project.id],
+ }
+ self.do_request(query)
+ _, kwargs = mock.call_args
+ self.assertEqual(kwargs["referrer"], self.referrer)
+
+ @mock.patch("sentry.snuba.discover.query")
+ def test_empty_referrer(self, mock):
+ mock.return_value = {}
+
+ query = {
+ "field": ["user"],
+ "project": [self.project.id],
+ }
+ self.do_request(query)
+ _, kwargs = mock.call_args
+ self.assertEqual(kwargs["referrer"], self.referrer)
+
+ @mock.patch("sentry.search.events.builder.discover.raw_snql_query")
+ def test_handling_snuba_errors(self, mock_snql_query):
+ self.create_project()
+
+ mock_snql_query.side_effect = RateLimitExceeded("test")
+
+ query = {"field": ["id", "timestamp"], "orderby": ["-timestamp", "-id"]}
+ response = self.do_request(query)
+ assert response.status_code == 400, response.content
+ assert response.data["detail"] == constants.TIMEOUT_ERROR_MESSAGE
+
+ mock_snql_query.side_effect = QueryExecutionError("test")
+
+ query = {"field": ["id", "timestamp"], "orderby": ["-timestamp", "-id"]}
+ response = self.do_request(query)
+ assert response.status_code == 500, response.content
+ assert response.data["detail"] == "Internal error. Your query failed to run."
+
+ mock_snql_query.side_effect = QueryIllegalTypeOfArgument("test")
+
+ query = {"field": ["id", "timestamp"], "orderby": ["-timestamp", "-id"]}
+ response = self.do_request(query)
+
+ assert response.status_code == 400, response.content
+ assert response.data["detail"] == "Invalid query. Argument to function is wrong type."
+
+ @mock.patch("sentry.snuba.discover.query")
+ def test_valid_referrer(self, mock):
+ mock.return_value = {}
+
+ query = {
+ "field": ["user"],
+ "referrer": "api.performance.transaction-summary",
+ "project": [self.project.id],
+ }
+ self.do_request(query)
+ _, kwargs = mock.call_args
+ self.assertEqual(kwargs["referrer"], "api.performance.transaction-summary")
diff --git a/tests/snuba/api/endpoints/test_organization_events.py b/tests/snuba/api/endpoints/test_organization_events.py
index 736a4ae2f77818..99254c5c5dcc9f 100644
--- a/tests/snuba/api/endpoints/test_organization_events.py
+++ b/tests/snuba/api/endpoints/test_organization_events.py
@@ -26,7 +26,6 @@
from sentry.testutils.skips import requires_not_arm64
from sentry.utils import json
from sentry.utils.samples import load_data
-from sentry.utils.snuba import QueryExecutionError, QueryIllegalTypeOfArgument, RateLimitExceeded
from tests.sentry.issues.test_utils import SearchIssueTestMixin
MAX_QUERYABLE_TRANSACTION_THRESHOLDS = 1
@@ -97,33 +96,6 @@ def test_no_projects(self):
"tips": {"query": "Need at least one valid project to query."}
}
- def test_api_key_request(self):
- self.store_event(
- data={
- "event_id": "a" * 32,
- "environment": "staging",
- "timestamp": self.ten_mins_ago_iso,
- },
- project_id=self.project.id,
- )
-
- # Project ID cannot be inferred when using an org API key, so that must
- # be passed in the parameters
- api_key = self.create_api_key(organization=self.organization, scope_list=["org:read"])
- query = {"field": ["project.name", "environment"], "project": [self.project.id]}
-
- url = self.reverse_url()
- response = self.client_get(
- url,
- query,
- format="json",
- HTTP_AUTHORIZATION=self.create_basic_auth_header(api_key.key),
- )
-
- assert response.status_code == 200, response.content
- assert len(response.data["data"]) == 1
- assert response.data["data"][0]["project.name"] == self.project.slug
-
def test_environment_filter(self):
self.create_environment(self.project, name="production")
self.store_event(
@@ -310,32 +282,6 @@ def test_parent_span_id_in_context(self):
assert len(response.data["data"]) == 1
assert response.data["data"][0]["id"] == "a" * 32
- @mock.patch("sentry.search.events.builder.discover.raw_snql_query")
- def test_handling_snuba_errors(self, mock_snql_query):
- self.create_project()
-
- mock_snql_query.side_effect = RateLimitExceeded("test")
-
- query = {"field": ["id", "timestamp"], "orderby": ["-timestamp", "-id"]}
- response = self.do_request(query)
- assert response.status_code == 400, response.content
- assert response.data["detail"] == constants.TIMEOUT_ERROR_MESSAGE
-
- mock_snql_query.side_effect = QueryExecutionError("test")
-
- query = {"field": ["id", "timestamp"], "orderby": ["-timestamp", "-id"]}
- response = self.do_request(query)
- assert response.status_code == 500, response.content
- assert response.data["detail"] == "Internal error. Your query failed to run."
-
- mock_snql_query.side_effect = QueryIllegalTypeOfArgument("test")
-
- query = {"field": ["id", "timestamp"], "orderby": ["-timestamp", "-id"]}
- response = self.do_request(query)
-
- assert response.status_code == 400, response.content
- assert response.data["detail"] == "Invalid query. Argument to function is wrong type."
-
def test_out_of_retention(self):
self.create_project()
with self.options({"system.event-retention-days": 10}):
@@ -4152,71 +4098,6 @@ def test_quantize_dates(self, mock_quantize):
self.do_request(query)
assert len(mock_quantize.mock_calls) == 2
- @mock.patch("sentry.snuba.discover.query")
- def test_valid_referrer(self, mock):
- mock.return_value = {}
-
- query = {
- "field": ["user"],
- "referrer": "api.performance.transaction-summary",
- "project": [self.project.id],
- }
- self.do_request(query)
- _, kwargs = mock.call_args
- self.assertEqual(kwargs["referrer"], "api.performance.transaction-summary")
-
- @mock.patch("sentry.snuba.discover.query")
- def test_invalid_referrer(self, mock):
- mock.return_value = {}
-
- query = {
- "field": ["user"],
- "referrer": "api.performance.invalid",
- "project": [self.project.id],
- }
- self.do_request(query)
- _, kwargs = mock.call_args
- self.assertEqual(kwargs["referrer"], self.referrer)
-
- @mock.patch("sentry.snuba.discover.query")
- def test_empty_referrer(self, mock):
- mock.return_value = {}
-
- query = {
- "field": ["user"],
- "project": [self.project.id],
- }
- self.do_request(query)
- _, kwargs = mock.call_args
- self.assertEqual(kwargs["referrer"], self.referrer)
-
- @mock.patch("sentry.snuba.discover.query")
- def test_api_token_referrer(self, mock):
- mock.return_value = {}
- # Project ID cannot be inferred when using an org API key, so that must
- # be passed in the parameters
- api_key = self.create_api_key(organization=self.organization, scope_list=["org:read"])
-
- query = {
- "field": ["project.name", "environment"],
- "project": [self.project.id],
- }
-
- features = {"organizations:discover-basic": True}
- features.update(self.features)
- url = self.reverse_url()
-
- with self.feature(features):
- self.client_get(
- url,
- query,
- format="json",
- HTTP_AUTHORIZATION=self.create_basic_auth_header(api_key.key),
- )
-
- _, kwargs = mock.call_args
- self.assertEqual(kwargs["referrer"], "api.auth-token.events")
-
def test_limit_number_of_fields(self):
self.create_project()
for i in range(1, 25):
|
e88f8ba72b7f768b9dd5d0f3f7075b0bc40e1d85
|
2021-05-20 22:49:33
|
Tony Xiao
|
feat(performance): Add team key transaction button to transaction summary (#26142)
| false
|
Add team key transaction button to transaction summary (#26142)
|
feat
|
diff --git a/static/app/actionCreators/performance.tsx b/static/app/actionCreators/performance.tsx
index c2ea89eae17ae6..c10fe35019bf8f 100644
--- a/static/app/actionCreators/performance.tsx
+++ b/static/app/actionCreators/performance.tsx
@@ -1,4 +1,8 @@
-import {addErrorMessage} from 'app/actionCreators/indicator';
+import {
+ addErrorMessage,
+ addLoadingMessage,
+ clearIndicators,
+} from 'app/actionCreators/indicator';
import {Client} from 'app/api';
import {t} from 'app/locale';
@@ -6,9 +10,12 @@ export function toggleKeyTransaction(
api: Client,
isKeyTransaction: boolean,
orgId: string,
- projects: number[],
- transactionName: string
+ projects: Readonly<number[]>,
+ transactionName: string,
+ teamIds?: string[] // TODO(txiao): make this required
): Promise<undefined> {
+ addLoadingMessage(t('Saving changes\u2026'));
+
const promise: Promise<undefined> = api.requestPromise(
`/organizations/${orgId}/key-transactions/`,
{
@@ -16,10 +23,15 @@ export function toggleKeyTransaction(
query: {
project: projects.map(id => String(id)),
},
- data: {transaction: transactionName},
+ data: {
+ transaction: transactionName,
+ team: teamIds,
+ },
}
);
+ promise.then(clearIndicators);
+
promise.catch(response => {
const non_field_errors = response?.responseJSON?.non_field_errors;
diff --git a/static/app/components/performance/teamKeyTransaction.tsx b/static/app/components/performance/teamKeyTransaction.tsx
new file mode 100644
index 00000000000000..15647ed819e08d
--- /dev/null
+++ b/static/app/components/performance/teamKeyTransaction.tsx
@@ -0,0 +1,235 @@
+import {Component, ReactElement} from 'react';
+import styled from '@emotion/styled';
+
+import {toggleKeyTransaction} from 'app/actionCreators/performance';
+import {Client} from 'app/api';
+import CheckboxFancy from 'app/components/checkboxFancy/checkboxFancy';
+import DropdownLink from 'app/components/dropdownLink';
+import {t} from 'app/locale';
+import space from 'app/styles/space';
+import {Organization, Team} from 'app/types';
+import withApi from 'app/utils/withApi';
+
+export type TitleProps = {
+ keyedTeamsCount: number;
+ disabled?: boolean;
+};
+
+type Props = {
+ api: Client;
+ project: number;
+ organization: Organization;
+ teams: Team[];
+ transactionName: string;
+ title: (props: TitleProps) => ReactElement;
+};
+
+type State = {
+ isLoading: boolean;
+ keyFetchID: symbol | undefined;
+ error: null | string;
+ keyedTeams: Set<string>;
+};
+
+type SelectionAction = {action: 'key' | 'unkey'};
+type MyTeamSelection = SelectionAction & {type: 'my teams'};
+type TeamIdSelection = SelectionAction & {type: 'id'; teamId: string};
+type TeamSelection = MyTeamSelection | TeamIdSelection;
+
+function isMyTeamSelection(selection: TeamSelection): selection is MyTeamSelection {
+ return selection.type === 'my teams';
+}
+
+class TeamKeyTransaction extends Component<Props, State> {
+ state: State = {
+ isLoading: true,
+ keyFetchID: undefined,
+ error: null,
+ keyedTeams: new Set(),
+ };
+
+ componentDidMount() {
+ this.fetchData();
+ }
+
+ componentDidUpdate(prevProps: Props) {
+ const orgSlugChanged = prevProps.organization.slug !== this.props.organization.slug;
+ const projectsChanged = prevProps.project !== this.props.project;
+ const transactionChanged = prevProps.transactionName !== this.props.transactionName;
+ if (orgSlugChanged || projectsChanged || transactionChanged) {
+ this.fetchData();
+ }
+ }
+
+ async fetchData() {
+ const {api, organization, project, transactionName} = this.props;
+
+ const url = `/organizations/${organization.slug}/key-transactions/`;
+ const keyFetchID = Symbol('keyFetchID');
+
+ this.setState({isLoading: true, keyFetchID});
+
+ try {
+ const [data] = await api.requestPromise(url, {
+ method: 'GET',
+ includeAllArgs: true,
+ query: {
+ project: String(project),
+ transaction: transactionName,
+ },
+ });
+ this.setState({
+ isLoading: false,
+ keyFetchID: undefined,
+ error: null,
+ keyedTeams: new Set(data.map(({team}) => team)),
+ });
+ } catch (err) {
+ this.setState({
+ isLoading: false,
+ keyFetchID: undefined,
+ error: err.responseJSON?.detail ?? null,
+ });
+ }
+ }
+
+ handleToggleKeyTransaction = async (selection: TeamSelection) => {
+ // TODO: handle the max 100 limit
+ const {api, organization, project, teams, transactionName} = this.props;
+ const markAsKeyTransaction = selection.action === 'key';
+
+ let teamIds;
+ let keyedTeams;
+ if (isMyTeamSelection(selection)) {
+ teamIds = teams.map(({id}) => id);
+ if (markAsKeyTransaction) {
+ keyedTeams = new Set(teamIds);
+ } else {
+ keyedTeams = new Set();
+ }
+ } else {
+ teamIds = [selection.teamId];
+ keyedTeams = new Set(this.state.keyedTeams);
+ if (markAsKeyTransaction) {
+ keyedTeams.add(selection.teamId);
+ } else {
+ keyedTeams.delete(selection.teamId);
+ }
+ }
+
+ try {
+ await toggleKeyTransaction(
+ api,
+ !markAsKeyTransaction,
+ organization.slug,
+ [project],
+ transactionName,
+ teamIds
+ );
+ this.setState({
+ isLoading: false,
+ keyFetchID: undefined,
+ error: null,
+ keyedTeams,
+ });
+ } catch (err) {
+ this.setState({
+ isLoading: false,
+ keyFetchID: undefined,
+ error: err.responseJSON?.detail ?? null,
+ });
+ }
+ };
+
+ render() {
+ const {teams, title: Title} = this.props;
+ const {keyedTeams, isLoading} = this.state;
+
+ if (isLoading) {
+ return <Title disabled keyedTeamsCount={keyedTeams.size} />;
+ }
+
+ return (
+ <TeamKeyTransactionSelector
+ title={<Title keyedTeamsCount={keyedTeams.size} />}
+ handleToggleKeyTransaction={this.handleToggleKeyTransaction}
+ teams={teams}
+ keyedTeams={keyedTeams}
+ />
+ );
+ }
+}
+
+type SelectorProps = {
+ title: React.ReactNode;
+ handleToggleKeyTransaction: (selection: TeamSelection) => void;
+ teams: Team[];
+ keyedTeams: Set<string>;
+};
+
+function TeamKeyTransactionSelector({
+ title,
+ handleToggleKeyTransaction,
+ teams,
+ keyedTeams,
+}: SelectorProps) {
+ const toggleTeam = (team: TeamSelection) => e => {
+ e.stopPropagation();
+ handleToggleKeyTransaction(team);
+ };
+
+ return (
+ <DropdownLink caret={false} title={title} anchorMiddle>
+ <DropdownMenuHeader
+ first
+ onClick={toggleTeam({
+ type: 'my teams',
+ action: teams.length === keyedTeams.size ? 'unkey' : 'key',
+ })}
+ >
+ {t('My Teams')}
+ <StyledCheckbox
+ isChecked={teams.length === keyedTeams.size}
+ isIndeterminate={teams.length > keyedTeams.size && keyedTeams.size > 0}
+ />
+ </DropdownMenuHeader>
+ {teams.map(team => (
+ <DropdownMenuItem
+ key={team.slug}
+ onClick={toggleTeam({
+ type: 'id',
+ action: keyedTeams.has(team.id) ? 'unkey' : 'key',
+ teamId: team.id,
+ })}
+ >
+ {team.name}
+ <StyledCheckbox isChecked={keyedTeams.has(team.id)} />
+ </DropdownMenuItem>
+ ))}
+ </DropdownLink>
+ );
+}
+
+const DropdownMenuItemBase = styled('li')`
+ display: flex;
+ flex-direction: row;
+ justify-content: space-between;
+ align-items: center;
+ padding: ${space(1)} ${space(1.5)};
+`;
+
+const DropdownMenuHeader = styled(DropdownMenuItemBase)<{first?: boolean}>`
+ background: ${p => p.theme.backgroundSecondary};
+ ${p => p.first && 'border-radius: 2px'};
+`;
+
+const DropdownMenuItem = styled(DropdownMenuItemBase)`
+ border-top: 1px solid ${p => p.theme.border};
+`;
+
+const StyledCheckbox = styled(CheckboxFancy)`
+ min-width: ${space(2)};
+ margin-left: ${space(1)};
+`;
+
+export default withApi(TeamKeyTransaction);
diff --git a/static/app/views/performance/transactionSummary/header.tsx b/static/app/views/performance/transactionSummary/header.tsx
index a3b23e2eaa698f..f8d25f9ea72eef 100644
--- a/static/app/views/performance/transactionSummary/header.tsx
+++ b/static/app/views/performance/transactionSummary/header.tsx
@@ -20,6 +20,7 @@ import Breadcrumb from 'app/views/performance/breadcrumb';
import {tagsRouteWithQuery} from './transactionTags/utils';
import {vitalsRouteWithQuery} from './transactionVitals/utils';
import KeyTransactionButton from './keyTransactionButton';
+import TeamKeyTransactionButton from './teamKeyTransactionButton';
import {transactionSummaryRouteWithQuery} from './utils';
export enum Tab {
@@ -97,11 +98,23 @@ class TransactionHeader extends React.Component<Props> {
const {eventView, organization, transactionName} = this.props;
return (
- <KeyTransactionButton
- transactionName={transactionName}
- eventView={eventView}
- organization={organization}
- />
+ <Feature organization={organization} features={['team-key-transactions']}>
+ {({hasFeature}) =>
+ hasFeature ? (
+ <TeamKeyTransactionButton
+ transactionName={transactionName}
+ eventView={eventView}
+ organization={organization}
+ />
+ ) : (
+ <KeyTransactionButton
+ transactionName={transactionName}
+ eventView={eventView}
+ organization={organization}
+ />
+ )
+ }
+ </Feature>
);
}
diff --git a/static/app/views/performance/transactionSummary/teamKeyTransactionButton.tsx b/static/app/views/performance/transactionSummary/teamKeyTransactionButton.tsx
new file mode 100644
index 00000000000000..4c37324186aa12
--- /dev/null
+++ b/static/app/views/performance/transactionSummary/teamKeyTransactionButton.tsx
@@ -0,0 +1,53 @@
+import styled from '@emotion/styled';
+
+import Button from 'app/components/button';
+import TeamKeyTransaction, {
+ TitleProps,
+} from 'app/components/performance/teamKeyTransaction';
+import {IconStar} from 'app/icons';
+import {t, tn} from 'app/locale';
+import {Organization, Team} from 'app/types';
+import EventView from 'app/utils/discover/eventView';
+import withTeams from 'app/utils/withTeams';
+
+type Props = {
+ eventView: EventView;
+ organization: Organization;
+ teams: Team[];
+ transactionName: string;
+};
+
+function TeamKeyTransactionButton({eventView, teams, ...props}: Props) {
+ if (eventView.project.length !== 1) {
+ return <TitleButton disabled keyedTeamsCount={0} />;
+ }
+
+ const userTeams = teams.filter(({isMember}) => isMember);
+ return (
+ <TeamKeyTransaction
+ teams={userTeams}
+ project={eventView.project[0]}
+ title={TitleButton}
+ {...props}
+ />
+ );
+}
+
+function TitleButton({disabled, keyedTeamsCount}: TitleProps) {
+ return (
+ <StyledButton
+ disabled={disabled}
+ icon={keyedTeamsCount ? <IconStar color="yellow300" isSolid /> : <IconStar />}
+ >
+ {keyedTeamsCount
+ ? tn('Starred for Team', 'Starred for Teams', keyedTeamsCount)
+ : t('Star for Team')}
+ </StyledButton>
+ );
+}
+
+const StyledButton = styled(Button)`
+ width: 180px;
+`;
+
+export default withTeams(TeamKeyTransactionButton);
diff --git a/tests/js/spec/components/performance/teamKeyTransaction.spec.jsx b/tests/js/spec/components/performance/teamKeyTransaction.spec.jsx
new file mode 100644
index 00000000000000..c382269cb8dae5
--- /dev/null
+++ b/tests/js/spec/components/performance/teamKeyTransaction.spec.jsx
@@ -0,0 +1,336 @@
+import {mountWithTheme} from 'sentry-test/enzyme';
+
+import TeamKeyTransaction from 'app/components/performance/teamKeyTransaction';
+
+function TestTitle({disabled, keyedTeamsCount}) {
+ return <p>{disabled ? 'disabled' : `count: ${keyedTeamsCount}`}</p>;
+}
+
+describe('TeamKeyTransaction', function () {
+ const organization = TestStubs.Organization({features: ['performance-view']});
+ const project = TestStubs.Project();
+ const teams = [
+ TestStubs.Team({id: '1', slug: 'team1', name: 'Team 1'}),
+ TestStubs.Team({id: '2', slug: 'team2', name: 'Team 2'}),
+ ];
+
+ beforeEach(function () {
+ jest.clearAllMocks();
+ MockApiClient.clearMockResponses();
+ });
+
+ it('renders with all teams checked', async function () {
+ const getTeamKeyTransactionsMock = MockApiClient.addMockResponse({
+ method: 'GET',
+ url: '/organizations/org-slug/key-transactions/',
+ body: teams.map(({id}) => ({team: id})),
+ });
+
+ const wrapper = mountWithTheme(
+ <TeamKeyTransaction
+ project={project.id}
+ organization={organization}
+ teams={teams}
+ transactionName="transaction"
+ title={TestTitle}
+ />
+ );
+
+ await tick();
+ wrapper.update();
+
+ // header should show the checked state
+ expect(getTeamKeyTransactionsMock).toHaveBeenCalledTimes(1);
+ expect(wrapper.find('TestTitle').exists()).toBeTruthy();
+ const header = wrapper.find('DropdownMenuHeader');
+ expect(header.exists()).toBeTruthy();
+ expect(header.find('StyledCheckbox').props().isChecked).toBeTruthy();
+ expect(header.find('StyledCheckbox').props().isIndeterminate).toBeFalsy();
+
+ // all teams should be checked
+ const entries = wrapper.find('DropdownMenuItem');
+ expect(entries.length).toBe(2);
+ entries.forEach((entry, i) => {
+ expect(entry.text()).toEqual(teams[i].name);
+ expect(entry.find('StyledCheckbox').props().isChecked).toBeTruthy();
+ });
+ });
+
+ it('renders with some teams checked', async function () {
+ MockApiClient.addMockResponse({
+ method: 'GET',
+ url: '/organizations/org-slug/key-transactions/',
+ body: [{team: teams[0].id}],
+ });
+
+ const wrapper = mountWithTheme(
+ <TeamKeyTransaction
+ project={project.id}
+ organization={organization}
+ teams={teams}
+ transactionName="transaction"
+ title={TestTitle}
+ />
+ );
+
+ await tick();
+ wrapper.update();
+
+ // header should show the indeterminate state
+ const header = wrapper.find('DropdownMenuHeader');
+ expect(header.exists()).toBeTruthy();
+ expect(header.find('StyledCheckbox').props().isChecked).toBeFalsy();
+ expect(header.find('StyledCheckbox').props().isIndeterminate).toBeTruthy();
+
+ // only team 1 should be checked
+ const entries = wrapper.find('DropdownMenuItem');
+ expect(entries.length).toBe(2);
+ entries.forEach((entry, i) => {
+ expect(entry.text()).toEqual(teams[i].name);
+ });
+ expect(entries.at(0).find('StyledCheckbox').props().isChecked).toBeTruthy();
+ expect(entries.at(1).find('StyledCheckbox').props().isChecked).toBeFalsy();
+ });
+
+ it('renders with no teams checked', async function () {
+ MockApiClient.addMockResponse({
+ method: 'GET',
+ url: '/organizations/org-slug/key-transactions/',
+ body: [],
+ });
+
+ const wrapper = mountWithTheme(
+ <TeamKeyTransaction
+ project={project.id}
+ organization={organization}
+ teams={teams}
+ transactionName="transaction"
+ title={TestTitle}
+ />
+ );
+
+ await tick();
+ wrapper.update();
+
+ // header should show the unchecked state
+ const header = wrapper.find('DropdownMenuHeader');
+ expect(header.exists()).toBeTruthy();
+ expect(header.find('StyledCheckbox').props().isChecked).toBeFalsy();
+ expect(header.find('StyledCheckbox').props().isIndeterminate).toBeFalsy();
+
+ // all teams should be unchecked
+ const entries = wrapper.find('DropdownMenuItem');
+ expect(entries.length).toBe(2);
+ entries.forEach((entry, i) => {
+ expect(entry.text()).toEqual(teams[i].name);
+ expect(entry.find('StyledCheckbox').props().isChecked).toBeFalsy();
+ });
+ });
+
+ it('should be able to check one team', async function () {
+ MockApiClient.addMockResponse({
+ method: 'GET',
+ url: '/organizations/org-slug/key-transactions/',
+ body: [],
+ });
+
+ const postTeamKeyTransactionsMock = MockApiClient.addMockResponse(
+ {
+ method: 'POST',
+ url: '/organizations/org-slug/key-transactions/',
+ body: [],
+ },
+ {
+ predicate: (_, options) =>
+ options.method === 'POST' &&
+ options.query.project.length === 1 &&
+ options.query.project[0] === project.id &&
+ options.data.team.length === 1 &&
+ options.data.team[0] === teams[0].id &&
+ options.data.transaction === 'transaction',
+ }
+ );
+
+ const wrapper = mountWithTheme(
+ <TeamKeyTransaction
+ project={project.id}
+ organization={organization}
+ teams={teams}
+ transactionName="transaction"
+ title={TestTitle}
+ />
+ );
+
+ await tick();
+ wrapper.update();
+
+ wrapper.find('DropdownMenuItem').first().simulate('click');
+
+ await tick();
+ wrapper.update();
+
+ const entries = wrapper.find('DropdownMenuItem');
+ expect(entries.at(0).find('StyledCheckbox').props().isChecked).toBeTruthy();
+ expect(postTeamKeyTransactionsMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('should be able to uncheck one team', async function () {
+ MockApiClient.addMockResponse({
+ method: 'GET',
+ url: '/organizations/org-slug/key-transactions/',
+ body: teams.map(({id}) => ({team: id})),
+ });
+
+ const deleteTeamKeyTransactionsMock = MockApiClient.addMockResponse(
+ {
+ method: 'DELETE',
+ url: '/organizations/org-slug/key-transactions/',
+ body: [],
+ },
+ {
+ predicate: (_, options) =>
+ options.method === 'DELETE' &&
+ options.query.project.length === 1 &&
+ options.query.project[0] === project.id &&
+ options.data.team.length === 1 &&
+ options.data.team[0] === teams[0].id &&
+ options.data.transaction === 'transaction',
+ }
+ );
+
+ const wrapper = mountWithTheme(
+ <TeamKeyTransaction
+ project={project.id}
+ organization={organization}
+ teams={teams}
+ transactionName="transaction"
+ title={TestTitle}
+ />
+ );
+
+ await tick();
+ wrapper.update();
+
+ wrapper.find('DropdownMenuItem').first().simulate('click');
+
+ await tick();
+ wrapper.update();
+
+ const entries = wrapper.find('DropdownMenuItem');
+ expect(entries.at(0).find('StyledCheckbox').props().isChecked).toBeFalsy();
+ expect(deleteTeamKeyTransactionsMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('should be able to check all with my teams', async function () {
+ MockApiClient.addMockResponse({
+ method: 'GET',
+ url: '/organizations/org-slug/key-transactions/',
+ body: [],
+ });
+
+ const postTeamKeyTransactionsMock = MockApiClient.addMockResponse(
+ {
+ method: 'POST',
+ url: '/organizations/org-slug/key-transactions/',
+ body: [],
+ },
+ {
+ predicate: (_, options) =>
+ options.method === 'POST' &&
+ options.query.project.length === 1 &&
+ options.query.project[0] === project.id &&
+ options.data.team.length === 2 &&
+ options.data.team[0] === teams[0].id &&
+ options.data.team[1] === teams[1].id &&
+ options.data.transaction === 'transaction',
+ }
+ );
+
+ const wrapper = mountWithTheme(
+ <TeamKeyTransaction
+ project={project.id}
+ organization={organization}
+ teams={teams}
+ transactionName="transaction"
+ title={TestTitle}
+ />
+ );
+
+ await tick();
+ wrapper.update();
+
+ wrapper.find('DropdownMenuHeader').simulate('click');
+
+ await tick();
+ wrapper.update();
+
+ // header should be checked now
+ const header = wrapper.find('DropdownMenuHeader');
+ expect(header.find('StyledCheckbox').props().isChecked).toBeTruthy();
+ expect(header.find('StyledCheckbox').props().isIndeterminate).toBeFalsy();
+
+ // all teams should be checked now
+ const entries = wrapper.find('DropdownMenuItem');
+ entries.forEach(entry => {
+ expect(entry.find('StyledCheckbox').props().isChecked).toBeTruthy();
+ });
+ expect(postTeamKeyTransactionsMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('should be able to uncheck all with my teams', async function () {
+ MockApiClient.addMockResponse({
+ method: 'GET',
+ url: '/organizations/org-slug/key-transactions/',
+ body: teams.map(({id}) => ({team: id})),
+ });
+
+ const deleteTeamKeyTransactionsMock = MockApiClient.addMockResponse(
+ {
+ method: 'DELETE',
+ url: '/organizations/org-slug/key-transactions/',
+ body: [],
+ },
+ {
+ predicate: (_, options) =>
+ options.method === 'DELETE' &&
+ options.query.project.length === 1 &&
+ options.query.project[0] === project.id &&
+ options.data.team.length === 2 &&
+ options.data.team[0] === teams[0].id &&
+ options.data.team[1] === teams[1].id &&
+ options.data.transaction === 'transaction',
+ }
+ );
+
+ const wrapper = mountWithTheme(
+ <TeamKeyTransaction
+ project={project.id}
+ organization={organization}
+ teams={teams}
+ transactionName="transaction"
+ title={TestTitle}
+ />
+ );
+
+ await tick();
+ wrapper.update();
+
+ wrapper.find('DropdownMenuHeader').simulate('click');
+
+ await tick();
+ wrapper.update();
+
+ // header should be unchecked now
+ const header = wrapper.find('DropdownMenuHeader');
+ expect(header.find('StyledCheckbox').props().isChecked).toBeFalsy();
+ expect(header.find('StyledCheckbox').props().isIndeterminate).toBeFalsy();
+
+ // all teams should be unchecked now
+ const entries = wrapper.find('DropdownMenuItem');
+ entries.forEach(entry => {
+ expect(entry.find('StyledCheckbox').props().isChecked).toBeFalsy();
+ });
+
+ expect(deleteTeamKeyTransactionsMock).toHaveBeenCalledTimes(1);
+ });
+});
|
387272d0e7189597d6525500805f6b66ee90cc9f
|
2021-07-24 00:05:29
|
NisanthanNanthakumar
|
feat(codeowners): Async update Code Owners on association updates (#27565)
| false
|
Async update Code Owners on association updates (#27565)
|
feat
|
diff --git a/src/sentry/api/endpoints/project_codeowners.py b/src/sentry/api/endpoints/project_codeowners.py
index 5f63358b61f09e..2d7d80329239de 100644
--- a/src/sentry/api/endpoints/project_codeowners.py
+++ b/src/sentry/api/endpoints/project_codeowners.py
@@ -2,13 +2,13 @@
from typing import Any, Mapping, MutableMapping, Sequence, Union
from rest_framework import serializers, status
-from rest_framework.exceptions import PermissionDenied
+from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
from sentry import analytics, features
from sentry.api.bases.project import ProjectEndpoint
-from sentry.api.endpoints.project_ownership import ProjectOwnershipMixin, ProjectOwnershipSerializer
+from sentry.api.endpoints.project_ownership import ProjectOwnershipMixin
from sentry.api.serializers import serialize
from sentry.api.serializers.models import projectcodeowners as projectcodeowners_serializers
from sentry.api.serializers.rest_framework.base import CamelSnakeModelSerializer
@@ -19,7 +19,7 @@
RepositoryProjectPathConfig,
UserEmail,
)
-from sentry.ownership.grammar import convert_codeowners_syntax
+from sentry.ownership.grammar import convert_codeowners_syntax, create_schema_from_issue_owners
from sentry.utils import metrics
logger = logging.getLogger(__name__)
@@ -64,7 +64,7 @@ def validate(self, attrs: Mapping[str, Any]) -> Mapping[str, Any]:
# Ignore association errors and continue parsing CODEOWNERS for valid lines.
# Allow users to incrementally fix association errors; for CODEOWNERS with many external mappings.
associations, _ = ProjectCodeOwners.validate_codeowners_associations(
- attrs, self.context["project"]
+ attrs["raw"], self.context["project"]
)
issue_owner_rules = convert_codeowners_syntax(
@@ -72,11 +72,16 @@ def validate(self, attrs: Mapping[str, Any]) -> Mapping[str, Any]:
)
# Convert IssueOwner syntax into schema syntax
- validated_data = ProjectOwnershipSerializer(context=self.context).validate(
- {"raw": issue_owner_rules}
- )
-
- return {**validated_data, **attrs}
+ try:
+ validated_data = create_schema_from_issue_owners(
+ issue_owners=issue_owner_rules, project_id=self.context["project"].id
+ )
+ return {
+ **attrs,
+ "schema": validated_data,
+ }
+ except ValidationError as e:
+ raise serializers.ValidationError(e)
def validate_code_mapping_id(self, code_mapping_id: int) -> RepositoryProjectPathConfig:
if ProjectCodeOwners.objects.filter(
diff --git a/src/sentry/api/endpoints/project_ownership.py b/src/sentry/api/endpoints/project_ownership.py
index 83e3a2ae0c1741..4f911f44f2fba0 100644
--- a/src/sentry/api/endpoints/project_ownership.py
+++ b/src/sentry/api/endpoints/project_ownership.py
@@ -1,13 +1,11 @@
-from typing import List
-
from django.utils import timezone
from rest_framework import serializers
from rest_framework.response import Response
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.serializers import serialize
-from sentry.models import ProjectOwnership, resolve_actors
-from sentry.ownership.grammar import CODEOWNERS, ParseError, Rule, dump_schema, parse_rules
+from sentry.models import ProjectOwnership
+from sentry.ownership.grammar import CODEOWNERS, create_schema_from_issue_owners
from sentry.signals import ownership_rule_created
@@ -17,13 +15,13 @@ class ProjectOwnershipSerializer(serializers.Serializer):
autoAssignment = serializers.BooleanField()
@staticmethod
- def _validate_no_codeowners(rules: List[Rule]):
+ def _validate_no_codeowners(rules):
"""
codeowner matcher types cannot be added via ProjectOwnership, only through codeowner
specific serializers
"""
for rule in rules:
- if rule.matcher.type == CODEOWNERS:
+ if rule["matcher"]["type"] == CODEOWNERS:
raise serializers.ValidationError(
{"raw": "Codeowner type paths can only be added by importing CODEOWNER files"}
)
@@ -31,36 +29,10 @@ def _validate_no_codeowners(rules: List[Rule]):
def validate(self, attrs):
if "raw" not in attrs:
return attrs
- try:
- rules = parse_rules(attrs["raw"])
- except ParseError as e:
- raise serializers.ValidationError(
- {
- "raw": "Parse error: %r (line %d, column %d)"
- % (e.expr.name, e.line(), e.column())
- }
- )
-
- schema = dump_schema(rules)
- self._validate_no_codeowners(rules)
+ schema = create_schema_from_issue_owners(attrs["raw"], self.context["ownership"].project_id)
- owners = {o for rule in rules for o in rule.owners}
- actors = resolve_actors(owners, self.context["ownership"].project_id)
-
- bad_actors = []
- for owner, actor in actors.items():
- if actor is None:
- if owner.type == "user":
- bad_actors.append(owner.identifier)
- elif owner.type == "team":
- bad_actors.append(f"#{owner.identifier}")
-
- if bad_actors:
- bad_actors.sort()
- raise serializers.ValidationError(
- {"raw": "Invalid rule owners: {}".format(", ".join(bad_actors))}
- )
+ self._validate_no_codeowners(schema["rules"])
attrs["schema"] = schema
return attrs
diff --git a/src/sentry/api/serializers/models/projectcodeowners.py b/src/sentry/api/serializers/models/projectcodeowners.py
index 9e8431d539a1a5..07714847ca49b1 100644
--- a/src/sentry/api/serializers/models/projectcodeowners.py
+++ b/src/sentry/api/serializers/models/projectcodeowners.py
@@ -53,7 +53,7 @@ def serialize(self, obj, attrs, user):
data["ownershipSyntax"] = convert_schema_to_rules_text(obj.schema)
if "errors" in self.expand:
- _, errors = ProjectCodeOwners.validate_codeowners_associations(data, obj.project)
+ _, errors = ProjectCodeOwners.validate_codeowners_associations(obj.raw, obj.project)
data["errors"] = errors
return data
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index f26dd18398e775..a94990f1b707c8 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -575,6 +575,7 @@ def SOCIAL_AUTH_DEFAULT_USERNAME():
Queue("auth", routing_key="auth"),
Queue("buffers.process_pending", routing_key="buffers.process_pending"),
Queue("cleanup", routing_key="cleanup"),
+ Queue("code_owners", routing_key="code_owners"),
Queue("commits", routing_key="commits"),
Queue("data_export", routing_key="data_export"),
Queue("default", routing_key="default"),
diff --git a/src/sentry/models/externalactor.py b/src/sentry/models/externalactor.py
index 69e0e6649a910b..32b9438e694270 100644
--- a/src/sentry/models/externalactor.py
+++ b/src/sentry/models/externalactor.py
@@ -1,8 +1,10 @@
import logging
from django.db import models
+from django.db.models.signals import post_delete, post_save
from sentry.db.models import BoundedPositiveIntegerField, DefaultFieldsModel, FlexibleForeignKey
+from sentry.tasks.code_owners import update_code_owners_schema
from sentry.types.integrations import ExternalProviders
logger = logging.getLogger(__name__)
@@ -35,3 +37,19 @@ class Meta:
app_label = "sentry"
db_table = "sentry_externalactor"
unique_together = (("organization", "provider", "external_name", "actor"),)
+
+
+post_save.connect(
+ lambda instance, **kwargs: update_code_owners_schema.apply_async(
+ kwargs={"organization": instance.organization, "integration": instance.integration}
+ ),
+ sender=ExternalActor,
+ weak=False,
+)
+post_delete.connect(
+ lambda instance, **kwargs: update_code_owners_schema.apply_async(
+ kwargs={"organization": instance.organization, "integration": instance.integration}
+ ),
+ sender=ExternalActor,
+ weak=False,
+)
diff --git a/src/sentry/models/project.py b/src/sentry/models/project.py
index f6c784d63ac4c1..18394b8ce59488 100644
--- a/src/sentry/models/project.py
+++ b/src/sentry/models/project.py
@@ -8,7 +8,7 @@
from django.conf import settings
from django.db import IntegrityError, models, transaction
from django.db.models import QuerySet
-from django.db.models.signals import pre_delete
+from django.db.models.signals import post_delete, post_save, pre_delete
from django.utils import timezone
from django.utils.http import urlencode
from django.utils.translation import ugettext_lazy as _
@@ -26,6 +26,7 @@
sane_repr,
)
from sentry.db.models.utils import slugify_instance
+from sentry.tasks.code_owners import update_code_owners_schema
from sentry.utils import metrics
from sentry.utils.colors import get_hashed_color
from sentry.utils.http import absolute_uri
@@ -435,3 +436,23 @@ def delete(self, **kwargs):
pre_delete.connect(delete_pending_deletion_option, sender=Project, weak=False)
+post_save.connect(
+ lambda instance, **kwargs: update_code_owners_schema.apply_async(
+ kwargs={
+ "organization": instance.project.organization,
+ "projects": [instance.project],
+ }
+ ),
+ sender=ProjectTeam,
+ weak=False,
+)
+post_delete.connect(
+ lambda instance, **kwargs: update_code_owners_schema.apply_async(
+ kwargs={
+ "organization": instance.project.organization,
+ "projects": [instance.project],
+ }
+ ),
+ sender=ProjectTeam,
+ weak=False,
+)
diff --git a/src/sentry/models/projectcodeowners.py b/src/sentry/models/projectcodeowners.py
index db61f84394a74c..74b87e87ed240b 100644
--- a/src/sentry/models/projectcodeowners.py
+++ b/src/sentry/models/projectcodeowners.py
@@ -2,8 +2,10 @@
from django.db import models
from django.utils import timezone
+from rest_framework.exceptions import ValidationError
from sentry.db.models import DefaultFieldsModel, FlexibleForeignKey, JSONField, sane_repr
+from sentry.ownership.grammar import convert_codeowners_syntax, create_schema_from_issue_owners
from sentry.utils.cache import cache
logger = logging.getLogger(__name__)
@@ -55,13 +57,13 @@ def get_codeowners_cached(self, project_id):
return codeowners or None
@classmethod
- def validate_codeowners_associations(self, attrs, project):
+ def validate_codeowners_associations(self, codeowners, project):
from sentry.api.endpoints.project_codeowners import validate_association
from sentry.models import ExternalActor, UserEmail, actor_type_to_string
from sentry.ownership.grammar import parse_code_owners
# Get list of team/user names from CODEOWNERS file
- team_names, usernames, emails = parse_code_owners(attrs["raw"])
+ team_names, usernames, emails = parse_code_owners(codeowners)
# Check if there exists Sentry users with the emails listed in CODEOWNERS
user_emails = UserEmail.objects.filter(
@@ -105,3 +107,30 @@ def validate_codeowners_associations(self, attrs, project):
"teams_without_access": teams_without_access,
}
return associations, errors
+
+ def update_schema(self):
+ """
+ Updating the schema goes through the following steps:
+ 1. parsing the original codeowner file to get the associations
+ 2. convert the codeowner file to the ownership syntax
+ 3. convert the ownership syntax to the schema
+ """
+ associations, _ = self.validate_codeowners_associations(self.raw, self.project)
+
+ issue_owner_rules = convert_codeowners_syntax(
+ codeowners=self.raw,
+ associations=associations,
+ code_mapping=self.repository_project_path_config,
+ )
+
+ # Convert IssueOwner syntax into schema syntax
+ try:
+ schema = create_schema_from_issue_owners(
+ issue_owners=issue_owner_rules, project_id=self.project.id
+ )
+ # Convert IssueOwner syntax into schema syntax
+ if schema:
+ self.schema = schema
+ self.save()
+ except ValidationError:
+ return
diff --git a/src/sentry/models/projectownership.py b/src/sentry/models/projectownership.py
index 52798402eeb97c..119014b254620a 100644
--- a/src/sentry/models/projectownership.py
+++ b/src/sentry/models/projectownership.py
@@ -1,14 +1,10 @@
-import operator
-from functools import reduce
-
from django.db import models
-from django.db.models import Q
from django.db.models.signals import post_delete, post_save
from django.utils import timezone
from sentry.db.models import Model, sane_repr
from sentry.db.models.fields import FlexibleForeignKey, JSONField
-from sentry.ownership.grammar import load_schema
+from sentry.ownership.grammar import load_schema, resolve_actors
from sentry.utils import metrics
from sentry.utils.cache import cache
@@ -194,58 +190,6 @@ def _matching_ownership_rules(cls, ownership, project_id, data):
return rules
-def resolve_actors(owners, project_id):
- """Convert a list of Owner objects into a dictionary
- of {Owner: Actor} pairs. Actors not identified are returned
- as None."""
- from sentry.models import ActorTuple, Team, User
-
- if not owners:
- return {}
-
- users, teams = [], []
- owners_lookup = {}
-
- for owner in owners:
- # teams aren't technical case insensitive, but teams also
- # aren't allowed to have non-lowercase in slugs, so
- # this kinda works itself out correctly since they won't match
- owners_lookup[(owner.type, owner.identifier.lower())] = owner
- if owner.type == "user":
- users.append(owner)
- elif owner.type == "team":
- teams.append(owner)
-
- actors = {}
- if users:
- actors.update(
- {
- ("user", email.lower()): ActorTuple(u_id, User)
- for u_id, email in User.objects.filter(
- reduce(operator.or_, [Q(emails__email__iexact=o.identifier) for o in users]),
- # We don't require verified emails
- # emails__is_verified=True,
- is_active=True,
- sentry_orgmember_set__organizationmemberteam__team__projectteam__project_id=project_id,
- )
- .distinct()
- .values_list("id", "emails__email")
- }
- )
-
- if teams:
- actors.update(
- {
- ("team", slug): ActorTuple(t_id, Team)
- for t_id, slug in Team.objects.filter(
- slug__in=[o.identifier for o in teams], projectteam__project_id=project_id
- ).values_list("id", "slug")
- }
- )
-
- return {o: actors.get((o.type, o.identifier.lower())) for o in owners}
-
-
# Signals update the cached reads used in post_processing
post_save.connect(
lambda instance, **kwargs: cache.set(
diff --git a/src/sentry/models/team.py b/src/sentry/models/team.py
index 447e63cbe497f2..0f369ff3223fa1 100644
--- a/src/sentry/models/team.py
+++ b/src/sentry/models/team.py
@@ -15,6 +15,7 @@
sane_repr,
)
from sentry.db.models.utils import slugify_instance
+from sentry.tasks.code_owners import update_code_owners_schema
from sentry.utils.retries import TimedRetryPolicy
@@ -85,6 +86,22 @@ def get_for_user(self, organization, user, scope=None, with_projects=False):
return results
+ def post_save(self, instance, **kwargs):
+ update_code_owners_schema.apply_async(
+ kwargs={
+ "organization": instance.organization,
+ "projects": instance.get_projects(),
+ }
+ ),
+
+ def post_delete(self, instance, **kwargs):
+ update_code_owners_schema.apply_async(
+ kwargs={
+ "organization": instance.organization,
+ "projects": instance.get_projects(),
+ }
+ ),
+
# TODO(dcramer): pull in enum library
class TeamStatus:
@@ -250,3 +267,10 @@ def get_projects(self):
from sentry.models import Project
return Project.objects.get_for_team_ids({self.id})
+
+ def delete(self, **kwargs):
+ from sentry.models import ExternalActor
+
+ # There is no foreign key relationship so we have to manually delete the ExternalActors
+ ExternalActor.objects.filter(actor_id=self.actor_id).delete()
+ return super().delete(**kwargs)
diff --git a/src/sentry/ownership/grammar.py b/src/sentry/ownership/grammar.py
index 70c1ca8a47dcd1..d13bc4fae0ca7e 100644
--- a/src/sentry/ownership/grammar.py
+++ b/src/sentry/ownership/grammar.py
@@ -1,9 +1,13 @@
+import operator
import re
from collections import namedtuple
+from functools import reduce
from typing import List, Pattern, Tuple
+from django.db.models import Q
from parsimonious.exceptions import ParseError # noqa
from parsimonious.grammar import Grammar, NodeVisitor
+from rest_framework.serializers import ValidationError
from sentry.utils.glob import glob_match
from sentry.utils.safe import get_path
@@ -391,25 +395,25 @@ def parse_code_owners(data: str) -> Tuple[List[str], List[str], List[str]]:
return teams, usernames, emails
-def convert_codeowners_syntax(data, associations, code_mapping):
+def convert_codeowners_syntax(codeowners, associations, code_mapping):
"""Converts CODEOWNERS text into IssueOwner syntax
- data: CODEOWNERS text
+ codeowners: CODEOWNERS text
associations: dict of {externalName: sentryName}
code_mapping: RepositoryProjectPathConfig object
"""
result = ""
- for rule in data.splitlines():
+ for rule in codeowners.splitlines():
if rule.startswith("#") or not len(rule):
# We want to preserve comments from CODEOWNERS
result += f"{rule}\n"
continue
- path, *codeowners = rule.split()
+ path, *code_owners = rule.split()
sentry_assignees = []
- for owner in codeowners:
+ for owner in code_owners:
try:
sentry_assignees.append(associations[owner])
except KeyError:
@@ -427,3 +431,83 @@ def convert_codeowners_syntax(data, associations, code_mapping):
result += f'path:{formatted_path} {" ".join(sentry_assignees)}\n'
return result
+
+
+def resolve_actors(owners, project_id):
+ """Convert a list of Owner objects into a dictionary
+ of {Owner: Actor} pairs. Actors not identified are returned
+ as None."""
+ from sentry.models import ActorTuple, Team, User
+
+ if not owners:
+ return {}
+
+ users, teams = [], []
+ owners_lookup = {}
+
+ for owner in owners:
+ # teams aren't technical case insensitive, but teams also
+ # aren't allowed to have non-lowercase in slugs, so
+ # this kinda works itself out correctly since they won't match
+ owners_lookup[(owner.type, owner.identifier.lower())] = owner
+ if owner.type == "user":
+ users.append(owner)
+ elif owner.type == "team":
+ teams.append(owner)
+
+ actors = {}
+ if users:
+ actors.update(
+ {
+ ("user", email.lower()): ActorTuple(u_id, User)
+ for u_id, email in User.objects.filter(
+ reduce(operator.or_, [Q(emails__email__iexact=o.identifier) for o in users]),
+ # We don't require verified emails
+ # emails__is_verified=True,
+ is_active=True,
+ sentry_orgmember_set__organizationmemberteam__team__projectteam__project_id=project_id,
+ )
+ .distinct()
+ .values_list("id", "emails__email")
+ }
+ )
+
+ if teams:
+ actors.update(
+ {
+ ("team", slug): ActorTuple(t_id, Team)
+ for t_id, slug in Team.objects.filter(
+ slug__in=[o.identifier for o in teams], projectteam__project_id=project_id
+ ).values_list("id", "slug")
+ }
+ )
+
+ return {o: actors.get((o.type, o.identifier.lower())) for o in owners}
+
+
+def create_schema_from_issue_owners(issue_owners, project_id):
+ try:
+ rules = parse_rules(issue_owners)
+ except ParseError as e:
+ raise ValidationError(
+ {"raw": f"Parse error: {e.expr.name} (line {e.line()}, column {e.column()})"}
+ )
+
+ schema = dump_schema(rules)
+
+ owners = {o for rule in rules for o in rule.owners}
+ actors = resolve_actors(owners, project_id)
+
+ bad_actors = []
+ for owner, actor in actors.items():
+ if actor is None:
+ if owner.type == "user":
+ bad_actors.append(owner.identifier)
+ elif owner.type == "team":
+ bad_actors.append(f"#{owner.identifier}")
+
+ if bad_actors:
+ bad_actors.sort()
+ raise ValidationError({"raw": "Invalid rule owners: {}".format(", ".join(bad_actors))})
+
+ return schema
diff --git a/src/sentry/tasks/code_owners.py b/src/sentry/tasks/code_owners.py
new file mode 100644
index 00000000000000..82ea76a173ddce
--- /dev/null
+++ b/src/sentry/tasks/code_owners.py
@@ -0,0 +1,41 @@
+import logging
+
+from sentry import features
+from sentry.tasks.base import instrumented_task
+
+logger = logging.getLogger("sentry.tasks.code_owners")
+
+
+@instrumented_task(
+ name="sentry.tasks.update_code_owners_schema",
+ queue="code_owners",
+ default_retry_delay=5,
+ max_retries=5,
+)
+def update_code_owners_schema(organization, integration=None, projects=None, **kwargs):
+ from sentry.models import ProjectCodeOwners, RepositoryProjectPathConfig
+
+ if not features.has("organizations:integrations-codeowners", organization):
+ return
+ try:
+ code_owners = []
+
+ if projects:
+ code_owners = ProjectCodeOwners.objects.filter(project__in=projects)
+
+ if integration:
+ code_mapping_ids = RepositoryProjectPathConfig.objects.filter(
+ organization_integration__organization=organization,
+ organization_integration__integration=integration,
+ ).values_list("id", flat=True)
+
+ code_owners = ProjectCodeOwners.objects.filter(
+ repository_project_path_config__in=code_mapping_ids
+ )
+
+ for code_owner in code_owners:
+ code_owner.update_schema()
+
+ # TODO(nisanthan): May need to add logging for the cases where we might want to have more information if something fails
+ except (RepositoryProjectPathConfig.DoesNotExist, ProjectCodeOwners.DoesNotExist):
+ return
diff --git a/tests/sentry/models/test_projectownership.py b/tests/sentry/models/test_projectownership.py
index 7f776c99301060..d496aed2e4382c 100644
--- a/tests/sentry/models/test_projectownership.py
+++ b/tests/sentry/models/test_projectownership.py
@@ -1,6 +1,5 @@
from sentry.models import ActorTuple, ProjectOwnership, Team, User
-from sentry.models.projectownership import resolve_actors
-from sentry.ownership.grammar import Matcher, Owner, Rule, dump_schema
+from sentry.ownership.grammar import Matcher, Owner, Rule, dump_schema, resolve_actors
from sentry.testutils import TestCase
from sentry.utils.cache import cache
diff --git a/tests/sentry/tasks/test_code_owners.py b/tests/sentry/tasks/test_code_owners.py
new file mode 100644
index 00000000000000..a6b712679299f4
--- /dev/null
+++ b/tests/sentry/tasks/test_code_owners.py
@@ -0,0 +1,62 @@
+from sentry.models import ExternalActor, Integration
+from sentry.models.projectcodeowners import ProjectCodeOwners
+from sentry.tasks.code_owners import update_code_owners_schema
+from sentry.testutils import TestCase
+
+
+class CodeOwnersTest(TestCase):
+ def setUp(self):
+ self.login_as(user=self.user)
+ self.integration = Integration.objects.create(
+ provider="github", name="GitHub", external_id="github:1"
+ )
+ self.oi = self.integration.add_organization(self.organization, self.user)
+
+ self.team = self.create_team(
+ organization=self.organization, slug="tiger-team", members=[self.user]
+ )
+
+ self.project = self.project = self.create_project(
+ organization=self.organization, teams=[self.team], slug="bengal"
+ )
+ self.code_mapping = self.create_code_mapping(
+ project=self.project,
+ organization_integration=self.oi,
+ )
+
+ self.data = {
+ "raw": "docs/* @NisanthanNanthakumar @getsentry/ecosystem\n",
+ }
+
+ self.code_owners = self.create_codeowners(
+ self.project, self.code_mapping, raw=self.data["raw"]
+ )
+
+ def test_simple(self):
+ with self.tasks() and self.feature({"organizations:integrations-codeowners": True}):
+ # new external team mapping
+ self.external_team = self.create_external_team(integration=self.integration)
+ update_code_owners_schema(organization=self.organization, integration=self.integration)
+
+ code_owners = ProjectCodeOwners.objects.get(id=self.code_owners.id)
+
+ assert code_owners.schema == {
+ "$version": 1,
+ "rules": [
+ {
+ "matcher": {"type": "path", "pattern": "docs/*"},
+ "owners": [
+ {"type": "team", "identifier": "tiger-team"},
+ ],
+ }
+ ],
+ }
+
+ with self.tasks() and self.feature({"organizations:integrations-codeowners": True}):
+ # delete external team mapping
+ ExternalActor.objects.get(id=self.external_team.id).delete()
+ update_code_owners_schema(organization=self.organization, integration=self.integration)
+
+ code_owners = ProjectCodeOwners.objects.get(id=self.code_owners.id)
+
+ assert code_owners.schema == {"$version": 1, "rules": []}
|
b5dce30fa7fca5728eaa809fd51286e17256a082
|
2019-01-03 00:36:06
|
Evan Purkhiser
|
fix(webpack): Correct eslint errors (#11305)
| false
|
Correct eslint errors (#11305)
|
fix
|
diff --git a/src/sentry/static/sentry/app/index.js b/src/sentry/static/sentry/app/index.js
index f8f00052c37c0f..93a48686c6f819 100644
--- a/src/sentry/static/sentry/app/index.js
+++ b/src/sentry/static/sentry/app/index.js
@@ -40,6 +40,7 @@ Sentry.configureScope(scope => {
function __raven_deprecated() {
const message = '[DEPRECATED]: Please no longer use Raven, use Sentry instead';
+ // eslint-disable-next-line no-console
console.error(message);
Sentry.captureMessage(message);
}
|
68a21b4bd89c3a0da82b65b395988614452f5f1a
|
2022-06-02 04:25:45
|
Scott Cooper
|
fix(workflow): Add back slack incident message color (#35207)
| false
|
Add back slack incident message color (#35207)
|
fix
|
diff --git a/src/sentry/integrations/slack/utils/notifications.py b/src/sentry/integrations/slack/utils/notifications.py
index c4f2f31c33a98d..313f9386799a6e 100644
--- a/src/sentry/integrations/slack/utils/notifications.py
+++ b/src/sentry/integrations/slack/utils/notifications.py
@@ -50,7 +50,7 @@ def send_incident_alert_notification(
incident, new_status, metric_value, chart_url
).build()
text = attachment["text"]
- blocks = {"blocks": attachment["blocks"]}
+ blocks = {"blocks": attachment["blocks"], "color": attachment["color"]}
payload = {
"token": integration.metadata["access_token"],
diff --git a/tests/sentry/incidents/action_handlers/test_slack.py b/tests/sentry/incidents/action_handlers/test_slack.py
index b5de6efd8247ff..9624ea2b469b03 100644
--- a/tests/sentry/incidents/action_handlers/test_slack.py
+++ b/tests/sentry/incidents/action_handlers/test_slack.py
@@ -60,7 +60,9 @@ def run_test(self, incident, method, chart_url=None):
slack_body = SlackIncidentsMessageBuilder(
incident, IncidentStatus(incident.status), metric_value, chart_url
).build()
- assert json.loads(data["attachments"][0])[0]["blocks"] == slack_body["blocks"]
+ attachments = json.loads(data["attachments"][0])
+ assert attachments[0]["color"] == slack_body["color"]
+ assert attachments[0]["blocks"] == slack_body["blocks"]
assert data["text"][0] == slack_body["text"]
def test_fire_metric_alert(self):
@@ -121,7 +123,9 @@ def run_test(self, incident, method):
slack_body = SlackIncidentsMessageBuilder(
incident, IncidentStatus(incident.status), metric_value
).build()
- assert json.loads(data["attachments"][0])[0]["blocks"] == slack_body["blocks"]
+ attachments = json.loads(data["attachments"][0])
+ assert attachments[0]["color"] == slack_body["color"]
+ assert attachments[0]["blocks"] == slack_body["blocks"]
assert data["text"][0] == slack_body["text"]
def test_fire_metric_alert(self):
|
d31841ed8d90b712e8f6d7da7d41ebe098dbd714
|
2022-08-17 23:59:36
|
Evan Purkhiser
|
ref(ts): Add types to groupStore showAlert (#37879)
| false
|
Add types to groupStore showAlert (#37879)
|
ref
|
diff --git a/static/app/stores/groupStore.tsx b/static/app/stores/groupStore.tsx
index ea11dc6422de68..5dfedb22b68484 100644
--- a/static/app/stores/groupStore.tsx
+++ b/static/app/stores/groupStore.tsx
@@ -1,6 +1,7 @@
import isArray from 'lodash/isArray';
import {createStore, StoreDefinition} from 'reflux';
+import {Indicator} from 'sentry/actionCreators/indicator';
import GroupActions from 'sentry/actions/groupActions';
import {t} from 'sentry/locale';
import IndicatorStore from 'sentry/stores/indicatorStore';
@@ -14,7 +15,7 @@ import {
} from 'sentry/types';
import {makeSafeRefluxStore} from 'sentry/utils/makeSafeRefluxStore';
-function showAlert(msg, type) {
+function showAlert(msg: string, type: Indicator['type']) {
IndicatorStore.addMessage(msg, type, {duration: 4000});
}
|
ca59242c563d2e006686a8b56e372d7f7ab0ae7e
|
2024-09-06 03:29:06
|
Michelle Fu
|
chore(anomaly detection): replace placeholder get_historical_data with seer call (#76977)
| false
|
replace placeholder get_historical_data with seer call (#76977)
|
chore
|
diff --git a/src/sentry/seer/anomaly_detection/get_historical_anomalies.py b/src/sentry/seer/anomaly_detection/get_historical_anomalies.py
index 9cf8539a02cbe6..5306e26ed21198 100644
--- a/src/sentry/seer/anomaly_detection/get_historical_anomalies.py
+++ b/src/sentry/seer/anomaly_detection/get_historical_anomalies.py
@@ -1,24 +1,154 @@
+import logging
+from datetime import datetime
+
+from django.conf import settings
+from urllib3.exceptions import MaxRetryError, TimeoutError
+
+from sentry.conf.server import SEER_ANOMALY_DETECTION_ENDPOINT_URL
from sentry.incidents.models.alert_rule import AlertRule, AlertRuleStatus
from sentry.models.project import Project
-from sentry.seer.anomaly_detection.types import AnomalyType
+from sentry.net.http import connection_from_url
+from sentry.seer.anomaly_detection.types import AnomalyDetectionConfig, DetectAnomaliesRequest
+from sentry.seer.anomaly_detection.utils import (
+ fetch_historical_data,
+ format_historical_data,
+ translate_direction,
+)
+from sentry.seer.signed_seer_api import make_signed_seer_api_request
+from sentry.snuba.models import SnubaQuery
+from sentry.snuba.utils import get_dataset
+from sentry.utils import json
+from sentry.utils.json import JSONDecodeError
+
+logger = logging.getLogger(__name__)
+
+seer_anomaly_detection_connection_pool = connection_from_url(
+ settings.SEER_ANOMALY_DETECTION_URL,
+ timeout=settings.SEER_ANOMALY_DETECTION_TIMEOUT,
+)
def get_historical_anomaly_data_from_seer(
alert_rule: AlertRule, project: Project, start_string: str, end_string: str
) -> list | None:
"""
- Send time series data to Seer and return anomaly detection response (PLACEHOLDER).
+ Send time series data to Seer and return anomaly detection response.
"""
if alert_rule.status == AlertRuleStatus.NOT_ENOUGH_DATA.value:
return []
+ # don't think this can happen but mypy is yelling
+ if not alert_rule.snuba_query:
+ logger.error(
+ "No snuba query associated with alert rule",
+ extra={
+ "alert_rule_id": alert_rule.id,
+ },
+ )
+ return None
+ subscription = alert_rule.snuba_query.subscriptions.first()
+ # same deal as above
+ if not subscription:
+ logger.error(
+ "No subscription associated with alert rule",
+ extra={"alert_rule_id": alert_rule.id, "snuba_query_id": alert_rule.snuba_query_id},
+ )
+ return None
+ snuba_query = SnubaQuery.objects.get(id=alert_rule.snuba_query_id)
+ dataset = get_dataset(snuba_query.dataset)
+ window_min = int(snuba_query.time_window / 60)
+ start = datetime.fromisoformat(start_string)
+ end = datetime.fromisoformat(end_string)
+ historical_data = fetch_historical_data(
+ alert_rule=alert_rule, snuba_query=snuba_query, project=project, start=start, end=end
+ )
+
+ if not historical_data:
+ logger.error(
+ "No historical data available",
+ extra={
+ "alert_rule_id": alert_rule.id,
+ "snuba_query_id": alert_rule.snuba_query_id,
+ "project_id": project.id,
+ "start": start,
+ "end": end,
+ },
+ )
+ return None
+ formatted_data = format_historical_data(historical_data, dataset)
+ if (
+ not alert_rule.sensitivity
+ or not alert_rule.seasonality
+ or alert_rule.threshold_type is None
+ or alert_rule.organization is None
+ ):
+ # this won't happen because we've already gone through the serializer, but mypy insists
+ logger.error("Missing required configuration for an anomaly detection alert")
+ return None
+
+ anomaly_detection_config = AnomalyDetectionConfig(
+ time_period=window_min,
+ sensitivity=alert_rule.sensitivity,
+ direction=translate_direction(alert_rule.threshold_type),
+ expected_seasonality=alert_rule.seasonality,
+ )
+ body = DetectAnomaliesRequest(
+ organization_id=alert_rule.organization.id,
+ project_id=project.id,
+ config=anomaly_detection_config,
+ context=formatted_data,
+ )
+ try:
+ response = make_signed_seer_api_request(
+ seer_anomaly_detection_connection_pool,
+ SEER_ANOMALY_DETECTION_ENDPOINT_URL,
+ json.dumps(body).encode("utf-8"),
+ )
+ except (TimeoutError, MaxRetryError):
+ logger.exception(
+ "Timeout error when hitting anomaly detection endpoint",
+ extra={
+ "subscription_id": subscription.id,
+ "dataset": alert_rule.snuba_query.dataset,
+ "organization_id": alert_rule.organization.id,
+ "project_id": project.id,
+ "alert_rule_id": alert_rule.id,
+ },
+ )
+ return None
+
+ if response.status != 200:
+ logger.error(
+ f"Received {response.status} when calling Seer endpoint {SEER_ANOMALY_DETECTION_ENDPOINT_URL}.", # noqa
+ extra={"response_data": response.data},
+ )
+ return None
- return [
- {
- "timestamp": 0.1,
- "value": 100.0,
- "anomaly": {
- "anomaly_type": AnomalyType.HIGH_CONFIDENCE.value,
- "anomaly_value": 100,
+ try:
+ results = json.loads(response.data.decode("utf-8")).get("timeseries")
+ if not results:
+ logger.warning(
+ "Seer anomaly detection response returned no potential anomalies",
+ extra={
+ "ad_config": anomaly_detection_config,
+ "context": formatted_data,
+ "response_data": response.data,
+ "reponse_code": response.status,
+ },
+ )
+ return None
+ return results
+ except (
+ AttributeError,
+ UnicodeError,
+ JSONDecodeError,
+ ):
+ logger.exception(
+ "Failed to parse Seer anomaly detection response",
+ extra={
+ "ad_config": anomaly_detection_config,
+ "context": formatted_data,
+ "response_data": response.data,
+ "reponse_code": response.status,
},
- }
- ]
+ )
+ return None
diff --git a/src/sentry/seer/anomaly_detection/store_data.py b/src/sentry/seer/anomaly_detection/store_data.py
index a5d1c0b7c4b643..840891b62babb8 100644
--- a/src/sentry/seer/anomaly_detection/store_data.py
+++ b/src/sentry/seer/anomaly_detection/store_data.py
@@ -3,28 +3,24 @@
from django.conf import settings
from django.core.exceptions import ValidationError
-from django.utils import timezone
from urllib3.exceptions import MaxRetryError, TimeoutError
from sentry.conf.server import SEER_ANOMALY_DETECTION_STORE_DATA_URL
from sentry.incidents.models.alert_rule import AlertRule, AlertRuleStatus
from sentry.models.project import Project
from sentry.net.http import connection_from_url
-from sentry.search.events.types import SnubaParams
from sentry.seer.anomaly_detection.types import (
AlertInSeer,
AnomalyDetectionConfig,
StoreDataRequest,
)
from sentry.seer.anomaly_detection.utils import (
+ fetch_historical_data,
format_historical_data,
- get_crash_free_historical_data,
translate_direction,
)
from sentry.seer.signed_seer_api import make_signed_seer_api_request
-from sentry.snuba import metrics_performance
from sentry.snuba.models import SnubaQuery
-from sentry.snuba.referrer import Referrer
from sentry.snuba.utils import get_dataset
from sentry.utils import json
from sentry.utils.snuba import SnubaTSResult
@@ -122,46 +118,3 @@ def send_historical_data_to_seer(alert_rule: AlertRule, project: Project) -> Ale
if data_end_time - data_start_time < timedelta(days=MIN_DAYS):
return AlertRuleStatus.NOT_ENOUGH_DATA
return AlertRuleStatus.PENDING
-
-
-def fetch_historical_data(
- alert_rule: AlertRule, snuba_query: SnubaQuery, project: Project
-) -> SnubaTSResult | None:
- """
- Fetch 28 days of historical data from Snuba to pass to Seer to build the anomaly detection model
- """
- # TODO: if we can pass the existing timeseries data we have on the front end along here, we can shorten
- # the time period we query and combine the data
- end = timezone.now()
- start = end - timedelta(days=NUM_DAYS)
- granularity = snuba_query.time_window
-
- dataset_label = snuba_query.dataset
- if dataset_label == "events":
- # DATSET_OPTIONS expects the name 'errors'
- dataset_label = "errors"
- dataset = get_dataset(dataset_label)
-
- if not project or not dataset or not alert_rule.organization:
- return None
-
- if dataset == metrics_performance:
- return get_crash_free_historical_data(
- start, end, project, alert_rule.organization, granularity
- )
-
- else:
- historical_data = dataset.timeseries_query(
- selected_columns=[snuba_query.aggregate],
- query=snuba_query.query,
- snuba_params=SnubaParams(
- organization=alert_rule.organization,
- projects=[project],
- start=start,
- end=end,
- ),
- rollup=granularity,
- referrer=Referrer.ANOMALY_DETECTION_HISTORICAL_DATA_QUERY.value,
- zerofill_results=True,
- )
- return historical_data
diff --git a/src/sentry/seer/anomaly_detection/utils.py b/src/sentry/seer/anomaly_detection/utils.py
index a6f225c6fdf8b7..5e207090aea57a 100644
--- a/src/sentry/seer/anomaly_detection/utils.py
+++ b/src/sentry/seer/anomaly_detection/utils.py
@@ -1,15 +1,20 @@
-from datetime import datetime
+from datetime import datetime, timedelta
from typing import Any
+from django.utils import timezone
from django.utils.datastructures import MultiValueDict
from sentry import release_health
-from sentry.incidents.models.alert_rule import AlertRuleThresholdType
+from sentry.incidents.models.alert_rule import AlertRule, AlertRuleThresholdType
from sentry.models.organization import Organization
from sentry.models.project import Project
+from sentry.search.events.types import SnubaParams
from sentry.seer.anomaly_detection.types import TimeSeriesPoint
from sentry.snuba import metrics_performance
+from sentry.snuba.models import SnubaQuery
+from sentry.snuba.referrer import Referrer
from sentry.snuba.sessions_v2 import QueryDefinition
+from sentry.snuba.utils import get_dataset
from sentry.utils.snuba import SnubaTSResult
@@ -101,3 +106,59 @@ def format_historical_data(data: SnubaTSResult, dataset: Any) -> list[TimeSeries
ts_point = TimeSeriesPoint(timestamp=datum.get("time"), value=datum.get("count", 0))
formatted_data.append(ts_point)
return formatted_data
+
+
+def fetch_historical_data(
+ alert_rule: AlertRule,
+ snuba_query: SnubaQuery,
+ project: Project,
+ start: datetime | None = None,
+ end: datetime | None = None,
+) -> SnubaTSResult | None:
+ """
+ Fetch 28 days of historical data from Snuba to pass to Seer to build the anomaly detection model
+ """
+ # TODO: if we can pass the existing timeseries data we have on the front end along here, we can shorten
+ # the time period we query and combine the data
+ is_store_data_request = False
+ if end is None:
+ is_store_data_request = True
+ end = timezone.now()
+ # doing it this way to suppress typing errors
+ if start is None:
+ start = end - timedelta(days=NUM_DAYS)
+ granularity = snuba_query.time_window
+
+ dataset_label = snuba_query.dataset
+ if dataset_label == "events":
+ # DATSET_OPTIONS expects the name 'errors'
+ dataset_label = "errors"
+ dataset = get_dataset(dataset_label)
+
+ if not project or not dataset or not alert_rule.organization:
+ return None
+
+ if dataset == metrics_performance:
+ return get_crash_free_historical_data(
+ start, end, project, alert_rule.organization, granularity
+ )
+
+ else:
+ historical_data = dataset.timeseries_query(
+ selected_columns=[snuba_query.aggregate],
+ query=snuba_query.query,
+ snuba_params=SnubaParams(
+ organization=alert_rule.organization,
+ projects=[project],
+ start=start,
+ end=end,
+ ),
+ rollup=granularity,
+ referrer=(
+ Referrer.ANOMALY_DETECTION_HISTORICAL_DATA_QUERY.value
+ if is_store_data_request
+ else Referrer.ANOMALY_DETECTION_RETURN_HISTORICAL_ANOMALIES.value
+ ),
+ zerofill_results=True,
+ )
+ return historical_data
diff --git a/src/sentry/snuba/referrer.py b/src/sentry/snuba/referrer.py
index cdbcfef67384bd..145be18468daf5 100644
--- a/src/sentry/snuba/referrer.py
+++ b/src/sentry/snuba/referrer.py
@@ -13,6 +13,9 @@ class Referrer(Enum):
ALERTRULESERIALIZER_TEST_QUERY_PRIMARY = "alertruleserializer.test_query.primary"
ALERTRULESERIALIZER_TEST_QUERY = "alertruleserializer.test_query"
ANOMALY_DETECTION_HISTORICAL_DATA_QUERY = "anomaly_detection_historical_data_query"
+ ANOMALY_DETECTION_RETURN_HISTORICAL_ANOMALIES = (
+ "anomaly_detection_get_historical_anomalies_query"
+ )
API_ALERTS_ALERT_RULE_CHART_METRICS_ENHANCED = "api.alerts.alert-rule-chart.metrics-enhanced"
API_ALERTS_ALERT_RULE_CHART = "api.alerts.alert-rule-chart"
API_ALERTS_CHARTCUTERIE = "api.alerts.chartcuterie"
diff --git a/tests/sentry/incidents/endpoints/test_organization_alert_rule_anomalies.py b/tests/sentry/incidents/endpoints/test_organization_alert_rule_anomalies.py
index 953e23609cef40..80da88a172f952 100644
--- a/tests/sentry/incidents/endpoints/test_organization_alert_rule_anomalies.py
+++ b/tests/sentry/incidents/endpoints/test_organization_alert_rule_anomalies.py
@@ -1,9 +1,12 @@
from datetime import timedelta
from unittest.mock import patch
+import orjson
import pytest
+from urllib3.exceptions import TimeoutError
from urllib3.response import HTTPResponse
+from sentry.conf.server import SEER_ANOMALY_DETECTION_ENDPOINT_URL
from sentry.incidents.models.alert_rule import (
AlertRuleDetectionType,
AlertRuleSeasonality,
@@ -32,7 +35,10 @@ class AlertRuleAnomalyEndpointTest(AlertRuleBase, SnubaTestCase):
@patch(
"sentry.seer.anomaly_detection.store_data.seer_anomaly_detection_connection_pool.urlopen"
)
- def test_simple(self, mock_seer_store_request):
+ @patch(
+ "sentry.seer.anomaly_detection.get_historical_anomalies.seer_anomaly_detection_connection_pool.urlopen"
+ )
+ def test_simple(self, mock_seer_request, mock_seer_store_request):
self.create_team(organization=self.organization, members=[self.user])
two_weeks_ago = before_now(days=14).replace(hour=10, minute=0, second=0, microsecond=0)
with self.options({"issues.group_attributes.send_kafka": True}):
@@ -68,7 +74,28 @@ def test_simple(self, mock_seer_store_request):
self.login_as(self.user)
+ seer_return_value = {
+ "timeseries": [
+ {
+ "anomaly": {
+ "anomaly_score": 0.0,
+ "anomaly_type": AnomalyType.NONE.value,
+ },
+ "timestamp": 1,
+ "value": 1,
+ },
+ {
+ "anomaly": {
+ "anomaly_score": 0.0,
+ "anomaly_type": AnomalyType.NONE.value,
+ },
+ "timestamp": 2,
+ "value": 1,
+ },
+ ]
+ }
mock_seer_store_request.return_value = HTTPResponse(status=200)
+ mock_seer_request.return_value = HTTPResponse(orjson.dumps(seer_return_value), status=200)
with outbox_runner():
resp = self.get_success_response(
self.organization.slug,
@@ -81,16 +108,10 @@ def test_simple(self, mock_seer_store_request):
)
assert mock_seer_store_request.call_count == 1
- assert resp.data == [
- {
- "timestamp": 0.1,
- "value": 100.0,
- "anomaly": {
- "anomaly_type": AnomalyType.HIGH_CONFIDENCE.value,
- "anomaly_value": 100,
- },
- }
- ]
+ assert mock_seer_request.call_count == 1
+ assert mock_seer_request.call_args.args[0] == "POST"
+ assert mock_seer_request.call_args.args[1] == SEER_ANOMALY_DETECTION_ENDPOINT_URL
+ assert resp.data == seer_return_value["timeseries"]
@with_feature("organizations:anomaly-detection-alerts")
@with_feature("organizations:incidents")
@@ -121,3 +142,135 @@ def test_alert_not_enough_data(self, mock_seer_store_request):
)
assert resp.data == []
+
+ @with_feature("organizations:anomaly-detection-alerts")
+ @with_feature("organizations:incidents")
+ @patch(
+ "sentry.seer.anomaly_detection.store_data.seer_anomaly_detection_connection_pool.urlopen"
+ )
+ @patch(
+ "sentry.seer.anomaly_detection.get_historical_anomalies.seer_anomaly_detection_connection_pool.urlopen"
+ )
+ @patch("sentry.seer.anomaly_detection.get_historical_anomalies.logger")
+ def test_timeout(self, mock_logger, mock_seer_request, mock_seer_store_request):
+ self.create_team(organization=self.organization, members=[self.user])
+ two_weeks_ago = before_now(days=14).replace(hour=10, minute=0, second=0, microsecond=0)
+ with self.options({"issues.group_attributes.send_kafka": True}):
+ self.store_event(
+ data={
+ "event_id": "a" * 32,
+ "message": "super duper bad",
+ "timestamp": iso_format(two_weeks_ago + timedelta(minutes=1)),
+ "fingerprint": ["group1"],
+ "tags": {"sentry:user": self.user.email},
+ },
+ event_type=EventType.ERROR,
+ project_id=self.project.id,
+ )
+ self.store_event(
+ data={
+ "event_id": "b" * 32,
+ "message": "super bad",
+ "timestamp": iso_format(two_weeks_ago + timedelta(days=10)),
+ "fingerprint": ["group2"],
+ "tags": {"sentry:user": self.user.email},
+ },
+ event_type=EventType.ERROR,
+ project_id=self.project.id,
+ )
+
+ alert_rule = self.create_alert_rule(
+ time_window=15,
+ sensitivity=AlertRuleSensitivity.MEDIUM,
+ seasonality=AlertRuleSeasonality.AUTO,
+ detection_type=AlertRuleDetectionType.DYNAMIC,
+ )
+
+ self.login_as(self.user)
+ mock_seer_store_request.return_value = HTTPResponse(status=200)
+ mock_seer_request.side_effect = TimeoutError
+ with outbox_runner():
+ resp = self.get_error_response(
+ self.organization.slug,
+ alert_rule.id,
+ qs_params={
+ "start": str(two_weeks_ago),
+ "end": str(two_weeks_ago + timedelta(days=12)),
+ },
+ status_code=400,
+ )
+ assert mock_seer_request.call_count == 1
+ mock_logger.exception.assert_called_with(
+ "Timeout error when hitting anomaly detection endpoint",
+ extra={
+ "subscription_id": alert_rule.snuba_query.subscriptions.first().id,
+ "dataset": alert_rule.snuba_query.dataset,
+ "organization_id": alert_rule.organization.id,
+ "project_id": self.project.id,
+ "alert_rule_id": alert_rule.id,
+ },
+ )
+ assert resp.data == "Unable to get historical anomaly data"
+
+ @with_feature("organizations:anomaly-detection-alerts")
+ @with_feature("organizations:incidents")
+ @patch(
+ "sentry.seer.anomaly_detection.store_data.seer_anomaly_detection_connection_pool.urlopen"
+ )
+ @patch(
+ "sentry.seer.anomaly_detection.get_historical_anomalies.seer_anomaly_detection_connection_pool.urlopen"
+ )
+ @patch("sentry.seer.anomaly_detection.get_historical_anomalies.logger")
+ def test_seer_error(self, mock_logger, mock_seer_request, mock_seer_store_request):
+ self.create_team(organization=self.organization, members=[self.user])
+ two_weeks_ago = before_now(days=14).replace(hour=10, minute=0, second=0, microsecond=0)
+ with self.options({"issues.group_attributes.send_kafka": True}):
+ self.store_event(
+ data={
+ "event_id": "a" * 32,
+ "message": "super duper bad",
+ "timestamp": iso_format(two_weeks_ago + timedelta(minutes=1)),
+ "fingerprint": ["group1"],
+ "tags": {"sentry:user": self.user.email},
+ },
+ event_type=EventType.ERROR,
+ project_id=self.project.id,
+ )
+ self.store_event(
+ data={
+ "event_id": "b" * 32,
+ "message": "super bad",
+ "timestamp": iso_format(two_weeks_ago + timedelta(days=10)),
+ "fingerprint": ["group2"],
+ "tags": {"sentry:user": self.user.email},
+ },
+ event_type=EventType.ERROR,
+ project_id=self.project.id,
+ )
+
+ alert_rule = self.create_alert_rule(
+ time_window=15,
+ sensitivity=AlertRuleSensitivity.MEDIUM,
+ seasonality=AlertRuleSeasonality.AUTO,
+ detection_type=AlertRuleDetectionType.DYNAMIC,
+ )
+
+ self.login_as(self.user)
+ mock_seer_store_request.return_value = HTTPResponse(status=200)
+ mock_seer_request.return_value = HTTPResponse("Bad stuff", status=500)
+ with outbox_runner():
+ resp = self.get_error_response(
+ self.organization.slug,
+ alert_rule.id,
+ qs_params={
+ "start": str(two_weeks_ago),
+ "end": str(two_weeks_ago + timedelta(days=12)),
+ },
+ status_code=400,
+ )
+ assert mock_seer_request.call_count == 1
+ mock_logger.error.assert_called_with(
+ f"Received 500 when calling Seer endpoint {SEER_ANOMALY_DETECTION_ENDPOINT_URL}.",
+ extra={"response_data": "Bad stuff"},
+ )
+ assert resp.data == "Unable to get historical anomaly data"
diff --git a/tests/sentry/seer/anomaly_detection/test_store_data.py b/tests/sentry/seer/anomaly_detection/test_store_data.py
index 4b4e599eb5e13b..df78a22f4fc3b3 100644
--- a/tests/sentry/seer/anomaly_detection/test_store_data.py
+++ b/tests/sentry/seer/anomaly_detection/test_store_data.py
@@ -5,8 +5,7 @@
import pytest
from sentry.incidents.models.alert_rule import AlertRuleThresholdType
-from sentry.seer.anomaly_detection.store_data import fetch_historical_data
-from sentry.seer.anomaly_detection.utils import format_historical_data
+from sentry.seer.anomaly_detection.utils import fetch_historical_data, format_historical_data
from sentry.snuba import errors, metrics_performance
from sentry.snuba.dataset import Dataset
from sentry.snuba.models import SnubaQuery
|
d2876bd4dca821b80ef35bf95e561c82abc03c6c
|
2020-02-29 03:42:46
|
Evan Purkhiser
|
chore(frontend): Cleanup modal actions (#17386)
| false
|
Cleanup modal actions (#17386)
|
chore
|
diff --git a/src/sentry/static/sentry/app/actionCreators/modal.tsx b/src/sentry/static/sentry/app/actionCreators/modal.tsx
index cadaf4dd799993..d41a6e9446d63f 100644
--- a/src/sentry/static/sentry/app/actionCreators/modal.tsx
+++ b/src/sentry/static/sentry/app/actionCreators/modal.tsx
@@ -3,7 +3,13 @@ import {css} from '@emotion/core';
import {ModalHeader, ModalBody, ModalFooter} from 'react-bootstrap';
import ModalActions from 'app/actions/modalActions';
-import {Integration, IntegrationProvider, Organization, SentryApp} from 'app/types';
+import {
+ Integration,
+ IntegrationProvider,
+ Organization,
+ SentryApp,
+ Project,
+} from 'app/types';
export type ModalRenderProps = {
closeModal: () => void;
@@ -20,28 +26,6 @@ export type ModalOptions = {
type?: string;
};
-export type IntegrationDetailsModalOptions = {
- onAddIntegration: (integration: Integration) => void;
- provider: IntegrationProvider;
- organization: Organization;
- isInstalled: boolean; //used for analytics
- onCloseModal?: () => void; //used for analytics
-};
-
-export type SentryAppDetailsModalOptions = {
- sentryApp: SentryApp;
- isInstalled: boolean;
- onInstall: () => Promise<void>;
- organization: Organization;
- onCloseModal?: () => void; //used for analytics
-};
-
-export type TeamAccessRequestModalOptions = {
- memberId: string;
- teamId: string;
- orgId: string;
-};
-
/**
* Show a modal
*/
@@ -59,181 +43,182 @@ export function closeModal() {
ModalActions.closeModal();
}
-export function openSudo({
- onClose,
- ...args
-}: {
+type OpenSudoModalOptions = {
onClose?: () => void;
superuser?: boolean;
sudo?: boolean;
retryRequest?: () => Promise<any>;
-} = {}) {
- import(/* webpackChunkName: "SudoModal" */ 'app/components/modals/sudoModal')
- .then(mod => mod.default)
- .then(SudoModal =>
- openModal(deps => <SudoModal {...deps} {...args} />, {
- modalClassName: 'sudo-modal',
- onClose,
- })
- );
+};
+
+export async function openSudo({onClose, ...args}: OpenSudoModalOptions = {}) {
+ const mod = await import(
+ /* webpackChunkName: "SudoModal" */ 'app/components/modals/sudoModal'
+ );
+ const {default: Modal} = mod;
+
+ openModal(deps => <Modal {...deps} {...args} />, {
+ modalClassName: 'sudo-modal',
+ onClose,
+ });
}
-export function openDiffModal(options: ModalOptions) {
- import(/* webpackChunkName: "DiffModal" */ 'app/components/modals/diffModal')
- .then(mod => mod.default)
- .then(Modal => {
- // This is the only way to style the different Modal children
- const modalCss = css`
- .modal-dialog {
- display: flex;
- margin: 0;
- left: 10px;
- right: 10px;
- top: 10px;
- bottom: 10px;
- width: auto;
- }
- .modal-content {
- display: flex;
- flex: 1;
- }
- .modal-body {
- display: flex;
- overflow: hidden;
- flex: 1;
- }
- `;
-
- openModal(deps => <Modal {...deps} {...options} />, {
- modalCss,
- });
- });
+export async function openDiffModal(options: ModalOptions) {
+ const mod = await import(
+ /* webpackChunkName: "DiffModal" */ 'app/components/modals/diffModal'
+ );
+ const {default: Modal, modalCss} = mod;
+
+ openModal(deps => <Modal {...deps} {...options} />, {
+ modalCss,
+ });
}
-/**
- * @param Object options
- * @param Object options.organization The organization to create a team for
- * @param Object options.project (optional) An initial project to add the team to. This may be deprecated soon as
- * we may add a project selection inside of the modal flow
- */
-export function openCreateTeamModal(options: ModalOptions = {}) {
- import(
+type CreateTeamModalOptions = {
+ /**
+ * The organization to create a team for
+ */
+ organization: Organization;
+ /**
+ * An initial project to add the team to. This may be deprecated soon as we may add a project selection inside of the modal flow
+ */
+ project?: Project;
+};
+
+export async function openCreateTeamModal(options: CreateTeamModalOptions) {
+ const mod = await import(
/* webpackChunkName: "CreateTeamModal" */ 'app/components/modals/createTeamModal'
- )
- .then(mod => mod.default)
- .then(Modal => {
- openModal(deps => <Modal {...deps} {...options} />, {
- modalClassName: 'create-team-modal',
- });
- });
+ );
+ const {default: Modal} = mod;
+
+ openModal(deps => <Modal {...deps} {...options} />, {
+ modalClassName: 'create-team-modal',
+ });
}
-/**
- * @param Object options.organization The organization to create a rules for
- * @param Object options.project The project to create a rules for
- */
-export function openCreateOwnershipRule(options: ModalOptions = {}) {
- import(
+type CreateOwnershipRuleModalOptions = {
+ /**
+ * The organization to create a rules for
+ */
+ organization: Organization;
+ /**
+ * The project to create a rules for
+ */
+ project: Project;
+};
+
+export async function openCreateOwnershipRule(options: CreateOwnershipRuleModalOptions) {
+ const mod = await import(
/* webpackChunkName: "CreateOwnershipRuleModal" */ 'app/components/modals/createOwnershipRuleModal'
- )
- .then(mod => mod.default)
- .then(Modal => {
- openModal(deps => <Modal {...deps} {...options} />, {
- modalClassName: 'create-ownership-rule-modal',
- });
- });
+ );
+ const {default: Modal} = mod;
+
+ openModal(deps => <Modal {...deps} {...options} />, {
+ modalClassName: 'create-ownership-rule-modal',
+ });
}
-export function openCommandPalette(options: ModalOptions = {}) {
- import(/* webpackChunkName: "CommandPalette" */ 'app/components/modals/commandPalette')
- .then(mod => mod.default)
- .then(Modal => {
- openModal(deps => <Modal {...deps} {...options} />, {
- modalClassName: 'command-palette',
- });
- });
+export async function openCommandPalette(options: ModalOptions = {}) {
+ const mod = await import(
+ /* webpackChunkName: "CommandPalette" */ 'app/components/modals/commandPalette'
+ );
+ const {default: Modal} = mod;
+
+ openModal(deps => <Modal {...deps} {...options} />, {
+ modalClassName: 'command-palette',
+ });
}
-export function openRecoveryOptions(options: ModalOptions = {}) {
- import(
+export async function openRecoveryOptions(options: ModalOptions = {}) {
+ const mod = await import(
/* webpackChunkName: "RecoveryOptionsModal" */ 'app/components/modals/recoveryOptionsModal'
- )
- .then(mod => mod.default)
- .then(Modal => {
- openModal(deps => <Modal {...deps} {...options} />, {
- modalClassName: 'recovery-options',
- });
- });
+ );
+ const {default: Modal} = mod;
+
+ openModal(deps => <Modal {...deps} {...options} />, {
+ modalClassName: 'recovery-options',
+ });
}
-export function openTeamAccessRequestModal(options: TeamAccessRequestModalOptions) {
- import(
+export type TeamAccessRequestModalOptions = {
+ memberId: string;
+ teamId: string;
+ orgId: string;
+};
+
+export async function openTeamAccessRequestModal(options: TeamAccessRequestModalOptions) {
+ const mod = await import(
/* webpackChunkName: "TeamAccessRequestModal" */ 'app/components/modals/teamAccessRequestModal'
- )
- .then(mod => mod.default)
- .then(Modal => {
- openModal(deps => <Modal {...deps} {...options} />, {
- modalClassName: 'confirm-team-request',
- });
- });
+ );
+ const {default: Modal} = mod;
+
+ openModal(deps => <Modal {...deps} {...options} />, {
+ modalClassName: 'confirm-team-request',
+ });
}
-/**
- * @param Object options.provider The integration provider to show the details for
- * @param Function options.onAddIntegration Called after a new integration is added
- */
-export function openIntegrationDetails(options: IntegrationDetailsModalOptions) {
- import(
+export type IntegrationDetailsModalOptions = {
+ onAddIntegration: (integration: Integration) => void;
+ provider: IntegrationProvider;
+ organization: Organization;
+ isInstalled: boolean; //used for analytics
+ onCloseModal?: () => void; //used for analytics
+};
+
+export async function openIntegrationDetails(options: IntegrationDetailsModalOptions) {
+ const mod = await import(
/* webpackChunkName: "IntegrationDetailsModal" */ 'app/components/modals/integrationDetailsModal'
- )
- .then(mod => mod.default)
- .then(Modal => {
- openModal(deps => <Modal {...deps} {...options} />);
- });
+ );
+ const {default: Modal} = mod;
+
+ openModal(deps => <Modal {...deps} {...options} />);
}
-export function redirectToProject(newProjectSlug: string) {
- import(
+export async function redirectToProject(newProjectSlug: string) {
+ const mod = await import(
/* webpackChunkName: "RedirectToProjectModal" */ 'app/components/modals/redirectToProject'
- )
- .then(mod => mod.default)
- .then(Modal => {
- openModal(deps => <Modal {...deps} slug={newProjectSlug} />, {});
- });
+ );
+ const {default: Modal} = mod;
+
+ openModal(deps => <Modal {...deps} slug={newProjectSlug} />, {});
}
-export function openHelpSearchModal() {
- import(
+export async function openHelpSearchModal() {
+ const mod = await import(
/* webpackChunkName: "HelpSearchModal" */ 'app/components/modals/helpSearchModal'
- )
- .then(mod => mod.default)
- .then(Modal => {
- openModal(deps => <Modal {...deps} />, {
- modalClassName: 'help-search-modal',
- });
- });
+ );
+ const {default: Modal} = mod;
+
+ openModal(deps => <Modal {...deps} />, {
+ modalClassName: 'help-search-modal',
+ });
}
-export function openSentryAppDetailsModal(options: SentryAppDetailsModalOptions) {
- import(
+export type SentryAppDetailsModalOptions = {
+ sentryApp: SentryApp;
+ isInstalled: boolean;
+ onInstall: () => Promise<void>;
+ organization: Organization;
+ onCloseModal?: () => void; //used for analytics
+};
+
+export async function openSentryAppDetailsModal(options: SentryAppDetailsModalOptions) {
+ const mod = await import(
/* webpackChunkName: "SentryAppDetailsModal" */ 'app/components/modals/sentryAppDetailsModal'
- )
- .then(mod => mod.default)
- .then(Modal => {
- openModal(deps => <Modal {...deps} {...options} />);
- });
+ );
+ const {default: Modal} = mod;
+
+ openModal(deps => <Modal {...deps} {...options} />);
}
-export function openDebugFileSourceModal(options: ModalOptions = {}) {
- import(
+export async function openDebugFileSourceModal(options: ModalOptions = {}) {
+ const mod = await import(
/* webpackChunkName: "DebugFileSourceModal" */ 'app/components/modals/debugFileSourceModal'
- )
- .then(mod => mod.default)
- .then(Modal => {
- openModal(deps => <Modal {...deps} {...options} />, {
- modalClassName: 'debug-file-source',
- });
- });
+ );
+ const {default: Modal} = mod;
+
+ openModal(deps => <Modal {...deps} {...options} />, {
+ modalClassName: 'debug-file-source',
+ });
}
export async function openInviteMembersModal(options = {}) {
diff --git a/src/sentry/static/sentry/app/components/modals/diffModal.jsx b/src/sentry/static/sentry/app/components/modals/diffModal.jsx
index 9b16b7c568eba6..7be337278190fa 100644
--- a/src/sentry/static/sentry/app/components/modals/diffModal.jsx
+++ b/src/sentry/static/sentry/app/components/modals/diffModal.jsx
@@ -1,5 +1,6 @@
import PropTypes from 'prop-types';
import React from 'react';
+import {css} from '@emotion/core';
import IssueDiff from 'app/components/issueDiff';
@@ -19,4 +20,27 @@ class DiffModal extends React.Component {
}
}
+const modalCss = css`
+ .modal-dialog {
+ display: flex;
+ margin: 0;
+ left: 10px;
+ right: 10px;
+ top: 10px;
+ bottom: 10px;
+ width: auto;
+ }
+ .modal-content {
+ display: flex;
+ flex: 1;
+ }
+ .modal-body {
+ display: flex;
+ overflow: hidden;
+ flex: 1;
+ }
+`;
+
+export {modalCss};
+
export default DiffModal;
|
f91600a851d631a50d7bbcc1c524ce7fe2f535f6
|
2023-04-27 05:42:15
|
Evan Purkhiser
|
ref(js): Do not pass organization object to Access (#48037)
| false
|
Do not pass organization object to Access (#48037)
|
ref
|
diff --git a/static/app/components/createAlertButton.spec.jsx b/static/app/components/createAlertButton.spec.jsx
index cf30d04df4d248..8c63eb33024130 100644
--- a/static/app/components/createAlertButton.spec.jsx
+++ b/static/app/components/createAlertButton.spec.jsx
@@ -9,29 +9,9 @@ import EventView from 'sentry/utils/discover/eventView';
import {DEFAULT_EVENT_VIEW} from 'sentry/views/discover/data';
const onClickMock = jest.fn();
-const context = TestStubs.routerContext();
jest.mock('sentry/actionCreators/navigation');
-function renderComponent(organization, eventView) {
- return render(
- <CreateAlertFromViewButton
- location={location}
- organization={organization}
- eventView={eventView}
- projects={[TestStubs.Project()]}
- onClick={onClickMock}
- />,
- {context}
- );
-}
-
-function renderSimpleComponent(organization, extraProps) {
- return render(<CreateAlertButton organization={organization} {...extraProps} />, {
- context: TestStubs.routerContext(),
- });
-}
-
describe('CreateAlertFromViewButton', () => {
const organization = TestStubs.Organization();
@@ -40,12 +20,23 @@ describe('CreateAlertFromViewButton', () => {
});
it('should trigger onClick callback', async () => {
+ const context = TestStubs.routerContext();
+
const eventView = EventView.fromSavedQuery({
...DEFAULT_EVENT_VIEW,
query: 'event.type:error',
projects: [2],
});
- renderComponent(organization, eventView);
+ render(
+ <CreateAlertFromViewButton
+ location={location}
+ organization={organization}
+ eventView={eventView}
+ projects={[TestStubs.Project()]}
+ onClick={onClickMock}
+ />,
+ {context}
+ );
await userEvent.click(screen.getByRole('button', {name: 'Create Alert'}));
expect(onClickMock).toHaveBeenCalledTimes(1);
});
@@ -59,7 +50,20 @@ describe('CreateAlertFromViewButton', () => {
access: [],
};
- renderComponent(noAccessOrg, eventView);
+ render(
+ <CreateAlertFromViewButton
+ location={location}
+ organization={organization}
+ eventView={eventView}
+ projects={[TestStubs.Project()]}
+ onClick={onClickMock}
+ />,
+ {
+ context: TestStubs.routerContext([{organization: noAccessOrg}]),
+ organization: noAccessOrg,
+ }
+ );
+
expect(screen.getByRole('button', {name: 'Create Alert'})).toBeDisabled();
});
@@ -69,8 +73,8 @@ describe('CreateAlertFromViewButton', () => {
access: [],
};
- renderSimpleComponent(noAccessOrg, {
- showPermissionGuide: true,
+ render(<CreateAlertButton organization={noAccessOrg} showPermissionGuide />, {
+ organization: noAccessOrg,
});
expect(GuideStore.state.anchors).toEqual(new Set(['alerts_write_member']));
@@ -82,15 +86,17 @@ describe('CreateAlertFromViewButton', () => {
access: ['org:write'],
};
- renderSimpleComponent(adminAccessOrg, {
- showPermissionGuide: true,
+ render(<CreateAlertButton organization={adminAccessOrg} showPermissionGuide />, {
+ organization: adminAccessOrg,
});
expect(GuideStore.state.anchors).toEqual(new Set(['alerts_write_owner']));
});
it('redirects to alert wizard with no project', async () => {
- renderSimpleComponent(organization);
+ render(<CreateAlertButton organization={organization} />, {
+ organization,
+ });
await userEvent.click(screen.getByRole('button'));
expect(navigateTo).toHaveBeenCalledWith(
`/organizations/org-slug/alerts/wizard/?`,
@@ -103,8 +109,8 @@ describe('CreateAlertFromViewButton', () => {
});
it('redirects to alert wizard with a project', () => {
- renderSimpleComponent(organization, {
- projectSlug: 'proj-slug',
+ render(<CreateAlertButton organization={organization} projectSlug="proj-slug" />, {
+ organization,
});
expect(screen.getByRole('button')).toHaveAttribute(
@@ -114,12 +120,23 @@ describe('CreateAlertFromViewButton', () => {
});
it('removes a duplicate project filter', async () => {
+ const context = TestStubs.routerContext();
+
const eventView = EventView.fromSavedQuery({
...DEFAULT_EVENT_VIEW,
query: 'event.type:error project:project-slug',
projects: [2],
});
- renderComponent(organization, eventView);
+ render(
+ <CreateAlertFromViewButton
+ location={location}
+ organization={organization}
+ eventView={eventView}
+ projects={[TestStubs.Project()]}
+ onClick={onClickMock}
+ />,
+ {context}
+ );
await userEvent.click(screen.getByRole('button'));
expect(context.context.router.push).toHaveBeenCalledWith({
pathname: `/organizations/org-slug/alerts/new/metric/`,
diff --git a/static/app/components/createAlertButton.tsx b/static/app/components/createAlertButton.tsx
index 8f7a6510c52bff..f796b2a072f9ba 100644
--- a/static/app/components/createAlertButton.tsx
+++ b/static/app/components/createAlertButton.tsx
@@ -193,10 +193,10 @@ function CreateAlertButton({
const showGuide = !organization.alertsMemberWrite && !!showPermissionGuide;
return (
- <Access organization={organization} access={['alerts:write']}>
+ <Access access={['alerts:write']}>
{({hasAccess}) =>
showGuide ? (
- <Access organization={organization} access={['org:write']}>
+ <Access access={['org:write']}>
{({hasAccess: isOrgAdmin}) => (
<GuideAnchor
target={isOrgAdmin ? 'alerts_write_owner' : 'alerts_write_member'}
diff --git a/static/app/components/events/interfaces/debugMeta/debugImageDetails/candidate/actions.tsx b/static/app/components/events/interfaces/debugMeta/debugImageDetails/candidate/actions.tsx
index 25ad4510b1f6eb..fc26376e3205bb 100644
--- a/static/app/components/events/interfaces/debugMeta/debugImageDetails/candidate/actions.tsx
+++ b/static/app/components/events/interfaces/debugMeta/debugImageDetails/candidate/actions.tsx
@@ -55,7 +55,7 @@ function Actions({
const actions = (
<Role role={organization.debugFilesRole} organization={organization}>
{({hasRole}) => (
- <Access access={['project:write']} organization={organization}>
+ <Access access={['project:write']}>
{({hasAccess}) => (
<Fragment>
<StyledDropdownLink
diff --git a/static/app/components/modals/sentryAppDetailsModal.spec.tsx b/static/app/components/modals/sentryAppDetailsModal.spec.tsx
index 2c8b433499d8b6..59ececbfc79b3c 100644
--- a/static/app/components/modals/sentryAppDetailsModal.spec.tsx
+++ b/static/app/components/modals/sentryAppDetailsModal.spec.tsx
@@ -121,14 +121,17 @@ describe('SentryAppDetailsModal', function () {
it('does not display the Install button, when the User does not have permission to install Integrations', function () {
renderMockRequests({sentryAppSlug: sentryApp.slug});
+ const noAccessOrg = TestStubs.Organization({access: []});
+
render(
<SentryAppDetailsModal
closeModal={jest.fn()}
isInstalled={false}
onInstall={jest.fn()}
- organization={TestStubs.Organization({access: []})}
+ organization={noAccessOrg}
sentryApp={sentryApp}
- />
+ />,
+ {organization: noAccessOrg}
);
expect(
diff --git a/static/app/components/modals/sentryAppDetailsModal.tsx b/static/app/components/modals/sentryAppDetailsModal.tsx
index 44a3d20ac3cb31..e12c677101cc52 100644
--- a/static/app/components/modals/sentryAppDetailsModal.tsx
+++ b/static/app/components/modals/sentryAppDetailsModal.tsx
@@ -177,7 +177,7 @@ export default class SentryAppDetailsModal extends AsyncComponent<Props, State>
{t('Cancel')}
</Button>
- <Access organization={organization} access={['org:integrations']}>
+ <Access access={['org:integrations']}>
{({hasAccess}) =>
hasAccess && (
<Button
diff --git a/static/app/components/modals/suggestProjectModal.tsx b/static/app/components/modals/suggestProjectModal.tsx
index 6b976492a25455..9f2f2b0a26cfb3 100644
--- a/static/app/components/modals/suggestProjectModal.tsx
+++ b/static/app/components/modals/suggestProjectModal.tsx
@@ -162,7 +162,7 @@ class SuggestProjectModal extends Component<Props, State> {
</ModalContainer>
</Body>
<Footer>
- <Access organization={organization} access={['project:write']}>
+ <Access access={['project:write']}>
{({hasAccess}) => (
<ButtonBar gap={1}>
<Button
diff --git a/static/app/components/repositoryRow.spec.tsx b/static/app/components/repositoryRow.spec.tsx
index 220a09f6946699..0bf77928b8d758 100644
--- a/static/app/components/repositoryRow.spec.tsx
+++ b/static/app/components/repositoryRow.spec.tsx
@@ -34,7 +34,6 @@ describe('RepositoryRow', function () {
const organization = TestStubs.Organization({
access: ['org:integrations'],
});
- const routerContext = TestStubs.routerContext([{organization}]);
it('displays provider information', function () {
render(
@@ -44,7 +43,7 @@ describe('RepositoryRow', function () {
orgId={organization.slug}
organization={organization}
/>,
- {context: routerContext}
+ {organization}
);
expect(screen.getByText(repository.name)).toBeInTheDocument();
expect(screen.getByText('github.com/example/repo-name')).toBeInTheDocument();
@@ -64,7 +63,7 @@ describe('RepositoryRow', function () {
orgId={organization.slug}
organization={organization}
/>,
- {context: routerContext}
+ {organization}
);
// Trash button should be disabled
@@ -80,7 +79,6 @@ describe('RepositoryRow', function () {
const organization = TestStubs.Organization({
access: ['org:write'],
});
- const routerContext = TestStubs.routerContext([{organization}]);
it('displays disabled trash', function () {
render(
@@ -90,7 +88,7 @@ describe('RepositoryRow', function () {
orgId={organization.slug}
organization={organization}
/>,
- {context: routerContext}
+ {organization}
);
// Trash button should be disabled
@@ -105,7 +103,7 @@ describe('RepositoryRow', function () {
orgId={organization.slug}
organization={organization}
/>,
- {context: routerContext}
+ {organization}
);
// Cancel should be disabled
@@ -117,7 +115,6 @@ describe('RepositoryRow', function () {
const organization = TestStubs.Organization({
access: ['org:integrations'],
});
- const routerContext = TestStubs.routerContext([{organization}]);
it('sends api request on delete', async function () {
const deleteRepo = MockApiClient.addMockResponse({
@@ -134,7 +131,7 @@ describe('RepositoryRow', function () {
orgId={organization.slug}
organization={organization}
/>,
- {context: routerContext}
+ {organization}
);
renderGlobalModal();
await userEvent.click(screen.getByRole('button', {name: 'delete'}));
@@ -150,7 +147,6 @@ describe('RepositoryRow', function () {
const organization = TestStubs.Organization({
access: ['org:integrations'],
});
- const routerContext = TestStubs.routerContext([{organization}]);
it('sends api request to cancel', async function () {
const cancel = MockApiClient.addMockResponse({
@@ -167,7 +163,7 @@ describe('RepositoryRow', function () {
orgId={organization.slug}
organization={organization}
/>,
- {context: routerContext}
+ {organization}
);
await userEvent.click(screen.getByRole('button', {name: 'Cancel'}));
@@ -180,7 +176,6 @@ describe('RepositoryRow', function () {
access: ['org:integrations'],
features: ['integrations-custom-scm'],
});
- const routerContext = TestStubs.routerContext([{organization}]);
it('displays edit button', function () {
render(
@@ -190,7 +185,7 @@ describe('RepositoryRow', function () {
orgId={organization.slug}
organization={organization}
/>,
- {context: routerContext}
+ {organization}
);
// Trash button should display enabled
@@ -210,7 +205,7 @@ describe('RepositoryRow', function () {
orgId={organization.slug}
organization={organization}
/>,
- {context: routerContext}
+ {organization}
);
// Trash button should be disabled
diff --git a/static/app/views/alerts/list/rules/index.spec.jsx b/static/app/views/alerts/list/rules/index.spec.jsx
index 3e240aab390269..3997a68625db11 100644
--- a/static/app/views/alerts/list/rules/index.spec.jsx
+++ b/static/app/views/alerts/list/rules/index.spec.jsx
@@ -231,13 +231,12 @@ describe('AlertRulesList', () => {
access: [],
};
- const {rerender} = createWrapper({organization: noAccessOrg});
+ render(getComponent({organization: noAccessOrg}), {
+ context: TestStubs.routerContext([{organization: noAccessOrg}]),
+ organization: noAccessOrg,
+ });
expect(await screen.findByLabelText('Create Alert')).toBeDisabled();
-
- // Enabled with access
- rerender(getComponent());
- expect(await screen.findByLabelText('Create Alert')).toBeEnabled();
});
it('searches by name', async () => {
diff --git a/static/app/views/settings/organization/permissionAlert.tsx b/static/app/views/settings/organization/permissionAlert.tsx
index 66e3804b31cb11..4eb7e83d4a1d37 100644
--- a/static/app/views/settings/organization/permissionAlert.tsx
+++ b/static/app/views/settings/organization/permissionAlert.tsx
@@ -3,12 +3,11 @@ import {ReactNode} from 'react';
import Access from 'sentry/components/acl/access';
import {Alert} from 'sentry/components/alert';
import {t} from 'sentry/locale';
-import {Organization, Scope} from 'sentry/types';
+import {Scope} from 'sentry/types';
type Props = React.ComponentPropsWithoutRef<typeof Alert> & {
access?: Scope[];
message?: ReactNode;
- organization?: Organization;
};
function PermissionAlert({
@@ -16,11 +15,10 @@ function PermissionAlert({
message = t(
'These settings can only be edited by users with the organization owner or manager role.'
),
- organization,
...props
}: Props) {
return (
- <Access access={access} organization={organization}>
+ <Access access={access}>
{({hasAccess}) =>
!hasAccess && (
<Alert data-test-id="org-permission-alert" type="warning" showIcon {...props}>
diff --git a/static/app/views/settings/organizationDeveloperSettings/index.spec.jsx b/static/app/views/settings/organizationDeveloperSettings/index.spec.jsx
index 36b6e8aa669dfc..18a7c9667c8e2c 100644
--- a/static/app/views/settings/organizationDeveloperSettings/index.spec.jsx
+++ b/static/app/views/settings/organizationDeveloperSettings/index.spec.jsx
@@ -235,7 +235,8 @@ describe('Organization Developer Settings', function () {
<OrganizationDeveloperSettings
organization={newOrg}
location={{query: {type: 'public'}}}
- />
+ />,
+ {organization: newOrg}
);
const deleteButton = await screen.findByRole('button', {name: 'Delete'});
expect(deleteButton).toHaveAttribute('aria-disabled', 'true');
@@ -246,7 +247,8 @@ describe('Organization Developer Settings', function () {
<OrganizationDeveloperSettings
organization={newOrg}
location={{query: {type: 'public'}}}
- />
+ />,
+ {organization: newOrg}
);
const publishButton = await screen.findByRole('button', {name: 'Publish'});
expect(publishButton).toHaveAttribute('aria-disabled', 'true');
diff --git a/static/app/views/settings/organizationDeveloperSettings/sentryApplicationRow/sentryApplicationRowButtons.tsx b/static/app/views/settings/organizationDeveloperSettings/sentryApplicationRow/sentryApplicationRowButtons.tsx
index 876666a27031b9..78d9977e1ce026 100644
--- a/static/app/views/settings/organizationDeveloperSettings/sentryApplicationRow/sentryApplicationRowButtons.tsx
+++ b/static/app/views/settings/organizationDeveloperSettings/sentryApplicationRow/sentryApplicationRowButtons.tsx
@@ -21,7 +21,7 @@ function SentryApplicationRowButtons({
const isInternal = app.status === 'internal';
return (
- <Access access={['org:admin']} organization={organization}>
+ <Access access={['org:admin']}>
{({hasAccess}) => {
let disablePublishReason = '';
let disableDeleteReason = '';
diff --git a/static/app/views/settings/organizationGeneralSettings/index.spec.tsx b/static/app/views/settings/organizationGeneralSettings/index.spec.tsx
index ca69a0228afec4..a8d79af87e3fe6 100644
--- a/static/app/views/settings/organizationGeneralSettings/index.spec.tsx
+++ b/static/app/views/settings/organizationGeneralSettings/index.spec.tsx
@@ -141,12 +141,11 @@ describe('OrganizationGeneralSettings', function () {
});
it('disables the entire form if user does not have write access', function () {
- render(
- <OrganizationGeneralSettings
- {...defaultProps}
- organization={TestStubs.Organization({access: ['org:read']})}
- />
- );
+ const readOnlyOrg = TestStubs.Organization({access: ['org:read']});
+
+ render(<OrganizationGeneralSettings {...defaultProps} organization={readOnlyOrg} />, {
+ organization: readOnlyOrg,
+ });
const formElements = [
...screen.getAllByRole('textbox'),
diff --git a/static/app/views/settings/organizationIntegrations/abstractIntegrationDetailedView.tsx b/static/app/views/settings/organizationIntegrations/abstractIntegrationDetailedView.tsx
index 1f4e7bf99192af..11d40d3fcab6c0 100644
--- a/static/app/views/settings/organizationIntegrations/abstractIntegrationDetailedView.tsx
+++ b/static/app/views/settings/organizationIntegrations/abstractIntegrationDetailedView.tsx
@@ -258,14 +258,13 @@ class AbstractIntegrationDetailedView<
}
renderAddInstallButton(hideButtonIfDisabled = false) {
- const {organization} = this.props;
const {IntegrationFeatures} = getIntegrationFeatureGate();
return (
<IntegrationFeatures {...this.featureProps}>
{({disabled, disabledReason}) => (
<DisableWrapper>
- <Access organization={organization} access={['org:integrations']}>
+ <Access access={['org:integrations']}>
{({hasAccess}) => (
<Tooltip
title={t(
diff --git a/static/app/views/settings/organizationIntegrations/createIntegrationButton.tsx b/static/app/views/settings/organizationIntegrations/createIntegrationButton.tsx
index f3b5c19f42fcac..d9236c295367f8 100644
--- a/static/app/views/settings/organizationIntegrations/createIntegrationButton.tsx
+++ b/static/app/views/settings/organizationIntegrations/createIntegrationButton.tsx
@@ -25,7 +25,7 @@ function CreateIntegrationButton({
);
return (
- <Access organization={organization} access={['org:write']}>
+ <Access access={['org:write']}>
{({hasAccess}) => (
<Button
size="sm"
diff --git a/static/app/views/settings/organizationIntegrations/installedIntegration.tsx b/static/app/views/settings/organizationIntegrations/installedIntegration.tsx
index caa0cfcec8afae..9a4fad93b73c3d 100644
--- a/static/app/views/settings/organizationIntegrations/installedIntegration.tsx
+++ b/static/app/views/settings/organizationIntegrations/installedIntegration.tsx
@@ -109,7 +109,7 @@ export default class InstalledIntegration extends Component<Props> {
);
return (
- <Access organization={organization} access={['org:integrations']}>
+ <Access access={['org:integrations']}>
{({hasAccess}) => {
const disableAction = !(hasAccess && this.integrationStatus === 'active');
return (
diff --git a/static/app/views/settings/organizationIntegrations/integrationDetailedView.spec.jsx b/static/app/views/settings/organizationIntegrations/integrationDetailedView.spec.jsx
index 4f633996ad7097..03806f09ad2a64 100644
--- a/static/app/views/settings/organizationIntegrations/integrationDetailedView.spec.jsx
+++ b/static/app/views/settings/organizationIntegrations/integrationDetailedView.spec.jsx
@@ -113,8 +113,8 @@ describe('IntegrationDetailedView', function () {
<IntegrationDetailedView
params={{integrationSlug: 'bitbucket', orgId: org.slug}}
location={{query: {tab: 'configurations'}}}
- organization={TestStubs.Organization({access: ['org:read']})}
- />
+ />,
+ {organization: TestStubs.Organization({access: ['org:read']})}
);
expect(screen.getByRole('button', {name: 'Configure'})).toBeDisabled();
@@ -156,8 +156,8 @@ describe('IntegrationDetailedView', function () {
<IntegrationDetailedView
params={{integrationSlug: 'github', orgId: org.slug}}
location={{query: {tab: 'configurations'}}}
- organization={TestStubs.Organization({access: ['org:read']})}
- />
+ />,
+ {organization: TestStubs.Organization({access: ['org:read']})}
);
expect(screen.getByRole('button', {name: 'Configure'})).toBeEnabled();
diff --git a/static/app/views/settings/project/projectFilters/index.spec.jsx b/static/app/views/settings/project/projectFilters/index.spec.jsx
index f80dc9385b98c3..f0c38337efe0eb 100644
--- a/static/app/views/settings/project/projectFilters/index.spec.jsx
+++ b/static/app/views/settings/project/projectFilters/index.spec.jsx
@@ -251,10 +251,6 @@ describe('ProjectFilters', function () {
});
it('disables configuration for non project:write users', function () {
- const context = TestStubs.routerContext([
- {organization: TestStubs.Organization({access: []})},
- ]);
-
render(
<ProjectFilters
organization={org}
@@ -262,7 +258,7 @@ describe('ProjectFilters', function () {
params={{projectId: project.slug, orgId: org.slug}}
project={project}
/>,
- {context}
+ {organization: TestStubs.Organization({access: []})}
);
screen.getAllByRole('checkbox').forEach(checkbox => {
@@ -298,7 +294,6 @@ describe('ProjectFilters', function () {
features: ['discard-groups'],
});
const discardOrg = TestStubs.Organization({access: [], features: ['discard-groups']});
- const context = TestStubs.routerContext([{organization: discardOrg}]);
render(
<ProjectFilters
@@ -311,7 +306,7 @@ describe('ProjectFilters', function () {
location={{}}
project={discardProject}
/>,
- {context}
+ {organization: discardOrg}
);
expect(await screen.findByRole('button', {name: 'Undiscard'})).toBeDisabled();
diff --git a/static/app/views/settings/project/projectOwnership/index.spec.jsx b/static/app/views/settings/project/projectOwnership/index.spec.jsx
index e80ffb005b604c..8cda2a775bedf2 100644
--- a/static/app/views/settings/project/projectOwnership/index.spec.jsx
+++ b/static/app/views/settings/project/projectOwnership/index.spec.jsx
@@ -60,16 +60,13 @@ describe('Project Ownership', () => {
});
it('renders allows users to edit ownership rules', () => {
- org = TestStubs.Organization({
- access: ['project:read'],
- });
render(
<ProjectOwnership
params={{projectId: project.slug}}
organization={org}
project={project}
/>,
- {context: TestStubs.routerContext([{organization: org}])}
+ {organization: TestStubs.Organization({access: ['project:read']})}
);
expect(screen.queryByRole('button', {name: 'Edit'})).toBeEnabled();
diff --git a/static/app/views/settings/projectAlerts/index.tsx b/static/app/views/settings/projectAlerts/index.tsx
index add36c3ac69b17..eb4f2b3d27b9a1 100644
--- a/static/app/views/settings/projectAlerts/index.tsx
+++ b/static/app/views/settings/projectAlerts/index.tsx
@@ -12,7 +12,7 @@ interface Props
function ProjectAlerts({children, organization}: Props) {
return (
- <Access organization={organization} access={['project:write']}>
+ <Access access={['project:write']}>
{({hasAccess}) => (
<Fragment>
{isValidElement(children) &&
diff --git a/static/app/views/settings/projectGeneralSettings/index.spec.jsx b/static/app/views/settings/projectGeneralSettings/index.spec.jsx
index 677934beb2904b..04415b0aefd3a5 100644
--- a/static/app/views/settings/projectGeneralSettings/index.spec.jsx
+++ b/static/app/views/settings/projectGeneralSettings/index.spec.jsx
@@ -201,9 +201,12 @@ describe('projectGeneralSettings', function () {
});
it('disables the form for users without write permissions', function () {
- routerContext.context.organization.access = ['org:read'];
+ const readOnlyOrg = TestStubs.Organization({access: ['org:read']});
+ routerContext.context.organization = readOnlyOrg;
+
render(<ProjectGeneralSettings params={{projectId: project.slug}} />, {
context: routerContext,
+ organization: readOnlyOrg,
});
// no textboxes are enabled
diff --git a/static/app/views/settings/projectPlugins/projectPluginRow.spec.jsx b/static/app/views/settings/projectPlugins/projectPluginRow.spec.jsx
index e5f04a7d29e2ce..c93a73992db334 100644
--- a/static/app/views/settings/projectPlugins/projectPluginRow.spec.jsx
+++ b/static/app/views/settings/projectPlugins/projectPluginRow.spec.jsx
@@ -39,9 +39,7 @@ describe('ProjectPluginRow', function () {
render(
<ProjectPluginRow {...params} {...plugin} onChange={onChange} project={project} />,
{
- context: TestStubs.routerContext([
- {organization: TestStubs.Organization({access: []})},
- ]),
+ organization: TestStubs.Organization({access: []}),
}
);
diff --git a/static/app/views/settings/projectTags/index.spec.jsx b/static/app/views/settings/projectTags/index.spec.jsx
index abbd69ddf98053..1207c32e88c50f 100644
--- a/static/app/views/settings/projectTags/index.spec.jsx
+++ b/static/app/views/settings/projectTags/index.spec.jsx
@@ -48,12 +48,8 @@ describe('ProjectTags', function () {
});
it('disables delete button for users without access', function () {
- const context = {
- organization: TestStubs.Organization({access: []}),
- };
-
render(<ProjectTags organization={org} params={{projectId: project.slug}} />, {
- context: TestStubs.routerContext([context]),
+ organization: TestStubs.Organization({access: []}),
});
screen
|
923b3b4d267ae7577c7d10a6eaf7a0344620c767
|
2023-02-11 01:51:26
|
Scott Cooper
|
fix(ecosystem): Remove unique metrics tags from plugins (#44437)
| false
|
Remove unique metrics tags from plugins (#44437)
|
fix
|
diff --git a/src/sentry_plugins/amazon_sqs/plugin.py b/src/sentry_plugins/amazon_sqs/plugin.py
index 1acdb03a708e1c..fd62744298a6f1 100644
--- a/src/sentry_plugins/amazon_sqs/plugin.py
+++ b/src/sentry_plugins/amazon_sqs/plugin.py
@@ -117,14 +117,12 @@ def forward_event(self, event, payload):
region = self.get_option("region", event.project)
message_group_id = self.get_option("message_group_id", event.project)
- # the metrics tags are a subset of logging params
- metric_tags = {
+ logging_params = {
"project_id": event.project_id,
"organization_id": event.project.organization_id,
+ "event_id": event.event_id,
+ "issue_id": event.group_id,
}
- logging_params = metric_tags.copy()
- logging_params["event_id"] = event.event_id
- logging_params["issue_id"] = event.group_id
if not all((queue_url, access_key, secret_key, region)):
logger.info("sentry_plugins.amazon_sqs.skip_unconfigured", extra=logging_params)
@@ -141,10 +139,7 @@ def log_and_increment(metrics_name):
metrics_name,
extra=logging_params,
)
- metrics.incr(
- metrics_name,
- tags=metric_tags,
- )
+ metrics.incr(metrics_name)
def s3_put_object(*args, **kwargs):
s3_client = boto3.client(
diff --git a/src/sentry_plugins/splunk/plugin.py b/src/sentry_plugins/splunk/plugin.py
index 66700b70973bd4..5a3504567e16d7 100644
--- a/src/sentry_plugins/splunk/plugin.py
+++ b/src/sentry_plugins/splunk/plugin.py
@@ -175,11 +175,7 @@ def is_ratelimited(self, event):
if super().is_ratelimited(event):
metrics.incr(
"integrations.splunk.forward-event.rate-limited",
- tags={
- "project_id": event.project_id,
- "organization_id": event.project.organization_id,
- "event_type": event.get_event_type(),
- },
+ tags={"event_type": event.get_event_type()},
)
return True
return False
@@ -197,11 +193,7 @@ def forward_event(self, event: Event, payload: MutableMapping[str, Any]) -> bool
if not (self.project_token and self.project_index and self.project_instance):
metrics.incr(
"integrations.splunk.forward-event.unconfigured",
- tags={
- "project_id": event.project_id,
- "organization_id": event.project.organization_id,
- "event_type": event.get_event_type(),
- },
+ tags={"event_type": event.get_event_type()},
)
return False
@@ -215,14 +207,7 @@ def forward_event(self, event: Event, payload: MutableMapping[str, Any]) -> bool
client.request(payload)
except Exception as exc:
metric = "integrations.splunk.forward-event.error"
- metrics.incr(
- metric,
- tags={
- "project_id": event.project_id,
- "organization_id": event.project.organization_id,
- "event_type": event.get_event_type(),
- },
- )
+ metrics.incr(metric, tags={"event_type": event.get_event_type()})
logger.info(
metric,
extra={
@@ -245,11 +230,6 @@ def forward_event(self, event: Event, payload: MutableMapping[str, Any]) -> bool
raise exc
metrics.incr(
- "integrations.splunk.forward-event.success",
- tags={
- "project_id": event.project_id,
- "organization_id": event.project.organization_id,
- "event_type": event.get_event_type(),
- },
+ "integrations.splunk.forward-event.success", tags={"event_type": event.get_event_type()}
)
return True
|
500967fff35f1fc484492f56e3a4d0e9f47c8758
|
2023-03-30 12:02:58
|
Matej Minar
|
fix(ai): Change error status code from 401 to 403 (#46576)
| false
|
Change error status code from 401 to 403 (#46576)
|
fix
|
diff --git a/src/sentry/api/endpoints/event_ai_suggested_fix.py b/src/sentry/api/endpoints/event_ai_suggested_fix.py
index e43d7f44a1e2cc..c04363bea4081c 100644
--- a/src/sentry/api/endpoints/event_ai_suggested_fix.py
+++ b/src/sentry/api/endpoints/event_ai_suggested_fix.py
@@ -223,7 +223,7 @@ def get(self, request: Request, project, event_id) -> Response:
return HttpResponse(
json.dumps({"restriction": policy_failure}),
content_type="application/json",
- status=401,
+ status=403,
)
# Cache the suggestion for a certain amount by primary hash, so even when new events
diff --git a/tests/sentry/api/endpoints/test_event_ai_suggested_fix.py b/tests/sentry/api/endpoints/test_event_ai_suggested_fix.py
index 70e41a37b1635d..07521e688e1c40 100644
--- a/tests/sentry/api/endpoints/test_event_ai_suggested_fix.py
+++ b/tests/sentry/api/endpoints/test_event_ai_suggested_fix.py
@@ -69,7 +69,7 @@ def test_consent(client, default_project, test_event, openai_policy):
openai_policy["result"] = "individual_consent"
response = client.get(path)
- assert response.status_code == 401
+ assert response.status_code == 403
assert response.json() == {"restriction": "individual_consent"}
response = client.get(path + "?consent=yes")
assert response.status_code == 200
@@ -77,7 +77,7 @@ def test_consent(client, default_project, test_event, openai_policy):
openai_policy["result"] = "subprocessor"
response = client.get(path)
- assert response.status_code == 401
+ assert response.status_code == 403
assert response.json() == {"restriction": "subprocessor"}
openai_policy["result"] = "allowed"
|
a4ebc44d8aa6e036e456381b1b84b2da6c6336de
|
2018-05-23 22:38:58
|
Lyn Nagara
|
fix(dashboard): Only return latest deploy for each environment (#8517)
| false
|
Only return latest deploy for each environment (#8517)
|
fix
|
diff --git a/src/sentry/api/serializers/models/project.py b/src/sentry/api/serializers/models/project.py
index a4c416a739bbf4..8b3fb7730fd95b 100644
--- a/src/sentry/api/serializers/models/project.py
+++ b/src/sentry/api/serializers/models/project.py
@@ -272,14 +272,21 @@ def get_attrs(self, item_list, user):
'id',
'date_finished'))
- deploys_by_project = defaultdict(list)
+ deploys_by_project = defaultdict(dict)
for rpe in release_project_envs:
- deploys_by_project[rpe['project__id']].append({
- 'version': rpe['release__version'],
- 'environment': rpe['environment__name'],
- 'dateFinished': deploys[rpe['last_deploy_id']],
- })
+ env_name = rpe['environment__name']
+ project_id = rpe['project__id']
+ date_finished = deploys[rpe['last_deploy_id']]
+
+ if (
+ env_name not in deploys_by_project[project_id] or
+ deploys_by_project[project_id][env_name]['dateFinished'] < date_finished
+ ):
+ deploys_by_project[project_id][env_name] = {
+ 'version': rpe['release__version'],
+ 'dateFinished': date_finished
+ }
for item in item_list:
attrs[item]['deploys'] = deploys_by_project.get(item.id)
diff --git a/tests/sentry/api/serializers/test_project.py b/tests/sentry/api/serializers/test_project.py
index 7b8751c7993cf6..edd22ece481072 100644
--- a/tests/sentry/api/serializers/test_project.py
+++ b/tests/sentry/api/serializers/test_project.py
@@ -3,11 +3,14 @@
from __future__ import absolute_import
import six
+import datetime
+from django.utils import timezone
from sentry.api.serializers import serialize
from sentry.api.serializers.models.project import (
- ProjectWithOrganizationSerializer, ProjectWithTeamSerializer
+ ProjectWithOrganizationSerializer, ProjectWithTeamSerializer, ProjectSummarySerializer
)
+from sentry.models import Deploy, Environment, Release, ReleaseProjectEnvironment
from sentry.testutils import TestCase
@@ -145,6 +148,45 @@ def test_simple(self):
'name': team.name}
+class ProjectSummarySerializerTest(TestCase):
+ def test_simple(self):
+ date = datetime.datetime(2018, 1, 12, 3, 8, 25, tzinfo=timezone.utc)
+ user = self.create_user(username='foo')
+ organization = self.create_organization(owner=user)
+ team = self.create_team(organization=organization)
+ project = self.create_project(teams=[team], organization=organization, name='foo')
+
+ release = Release.objects.create(
+ organization_id=organization.id,
+ version='1',
+ )
+
+ environment = Environment.objects.create(
+ organization_id=organization.id,
+ name='production',
+ )
+
+ deploy = Deploy.objects.create(
+ environment_id=environment.id,
+ organization_id=organization.id,
+ release=release,
+ date_finished=date
+ )
+
+ ReleaseProjectEnvironment.objects.create(
+ project_id=project.id,
+ release_id=release.id,
+ environment_id=environment.id,
+ last_deploy_id=deploy.id
+ )
+
+ result = serialize(project, user, ProjectSummarySerializer())
+
+ assert result['latestDeploys'] == {
+ 'production': {'dateFinished': date, 'version': '1'}
+ }
+
+
class ProjectWithOrganizationSerializerTest(TestCase):
def test_simple(self):
user = self.create_user(username='foo')
|
339bfd7f0dac604b24840a8c9158b72336f38c31
|
2022-02-09 03:18:53
|
Scott Cooper
|
feat(alerts): Check latest release is in alert environment (#31648)
| false
|
Check latest release is in alert environment (#31648)
|
feat
|
diff --git a/src/sentry/rules/filters/latest_release.py b/src/sentry/rules/filters/latest_release.py
index a8ca9e52b3c26b..66687f89119ccf 100644
--- a/src/sentry/rules/filters/latest_release.py
+++ b/src/sentry/rules/filters/latest_release.py
@@ -1,24 +1,38 @@
+from typing import Any, Optional
+
from django.db.models.signals import post_delete, post_save, pre_delete
from sentry import tagstore
-from sentry.api.serializers.models.project import bulk_fetch_project_latest_releases
-from sentry.models import Release, ReleaseProject
+from sentry.models import Environment, Event, Release, ReleaseEnvironment, ReleaseProject
from sentry.rules.filters.base import EventFilter
+from sentry.search.utils import get_latest_release
from sentry.utils.cache import cache
-def get_project_release_cache_key(project_id):
- return f"project:{project_id}:latest_release"
+def get_project_release_cache_key(project_id: int, environment_id: Optional[int] = None) -> str:
+ if environment_id is None:
+ return f"project:{project_id}:latest_release"
+ return f"project:{project_id}:env:{environment_id}:latest_release"
# clear the cache given a Release object
-def clear_release_cache(instance, **kwargs):
+def clear_release_cache(instance: Release, **kwargs: Any) -> None:
release_project_ids = instance.projects.values_list("id", flat=True)
cache.delete_many([get_project_release_cache_key(proj_id) for proj_id in release_project_ids])
+def clear_release_environment_project_cache(instance: ReleaseEnvironment, **kwargs: Any) -> None:
+ release_project_ids = instance.release.projects.values_list("id", flat=True)
+ cache.delete_many(
+ [
+ get_project_release_cache_key(proj_id, instance.environment_id)
+ for proj_id in release_project_ids
+ ]
+ )
+
+
# clear the cache given a ReleaseProject object
-def clear_release_project_cache(instance, **kwargs):
+def clear_release_project_cache(instance: ReleaseProject, **kwargs: Any) -> None:
proj_id = instance.project_id
cache.delete(get_project_release_cache_key(proj_id))
@@ -26,11 +40,28 @@ def clear_release_project_cache(instance, **kwargs):
class LatestReleaseFilter(EventFilter):
label = "The event is from the latest release"
- def get_latest_release(self, event):
- cache_key = get_project_release_cache_key(event.group.project_id)
+ def get_latest_release(self, event: Event) -> Optional[Release]:
+ environment_id = None if self.rule is None else self.rule.environment_id
+ cache_key = get_project_release_cache_key(event.group.project_id, environment_id)
latest_release = cache.get(cache_key)
if latest_release is None:
- latest_releases = bulk_fetch_project_latest_releases([event.group.project])
+ organization_id = event.group.project.organization_id
+ environments = None
+ if environment_id:
+ environments = [Environment.objects.get(id=environment_id)]
+ try:
+ latest_release_versions = get_latest_release(
+ [event.group.project],
+ environments,
+ organization_id,
+ )
+ except Release.DoesNotExist:
+ return None
+ latest_releases = list(
+ Release.objects.filter(
+ version=latest_release_versions[0], organization_id=organization_id
+ )
+ )
if latest_releases:
cache.set(cache_key, latest_releases[0], 600)
return latest_releases[0]
@@ -38,7 +69,7 @@ def get_latest_release(self, event):
cache.set(cache_key, False, 600)
return latest_release
- def passes(self, event, state):
+ def passes(self, event: Event, state: Any) -> bool:
latest_release = self.get_latest_release(event)
if not latest_release:
return False
@@ -61,3 +92,6 @@ def passes(self, event, state):
post_save.connect(clear_release_project_cache, sender=ReleaseProject, weak=False)
post_delete.connect(clear_release_project_cache, sender=ReleaseProject, weak=False)
+
+post_save.connect(clear_release_environment_project_cache, sender=ReleaseEnvironment, weak=False)
+post_delete.connect(clear_release_environment_project_cache, sender=ReleaseEnvironment, weak=False)
diff --git a/tests/sentry/rules/filters/test_latest_release.py b/tests/sentry/rules/filters/test_latest_release.py
index 663e8045e970f6..456c54a1b3678b 100644
--- a/tests/sentry/rules/filters/test_latest_release.py
+++ b/tests/sentry/rules/filters/test_latest_release.py
@@ -1,6 +1,6 @@
from datetime import datetime
-from sentry.models import Release
+from sentry.models import Release, Rule
from sentry.rules.filters.latest_release import LatestReleaseFilter, get_project_release_cache_key
from sentry.testutils.cases import RuleTestCase
from sentry.utils.cache import cache
@@ -81,3 +81,33 @@ def test_caching(self):
# rule should pass again because the latest release is oldRelease
self.assertPasses(rule, event)
+
+ def test_latest_release_with_environment(self):
+ event = self.get_event()
+ self.create_release(
+ project=event.group.project,
+ version="1",
+ date_added=datetime(2020, 9, 1, 3, 8, 24, 880386),
+ environments=[self.environment],
+ )
+
+ new_release = self.create_release(
+ project=event.group.project,
+ version="2",
+ date_added=datetime(2020, 9, 2, 3, 8, 24, 880386),
+ environments=[self.environment],
+ )
+
+ other_env_release = self.create_release(
+ project=event.group.project,
+ version="4",
+ date_added=datetime(2020, 9, 3, 3, 8, 24, 880386),
+ )
+
+ event.data["tags"] = (("release", new_release.version),)
+ environment_rule = self.get_rule(rule=Rule(environment_id=self.environment.id))
+ self.assertPasses(environment_rule, event)
+
+ event.data["tags"] = (("release", other_env_release.version),)
+ environment_rule = self.get_rule(rule=Rule(environment_id=self.environment.id))
+ self.assertDoesNotPass(environment_rule, event)
diff --git a/tests/sentry/rules/test_processor.py b/tests/sentry/rules/test_processor.py
index ac49ebcb3e2d8c..6185a510e3627c 100644
--- a/tests/sentry/rules/test_processor.py
+++ b/tests/sentry/rules/test_processor.py
@@ -1,4 +1,4 @@
-from datetime import timedelta
+from datetime import datetime, timedelta
from unittest import mock
from unittest.mock import patch
@@ -365,3 +365,50 @@ def test_latest_release(self):
assert len(futures) == 1
assert futures[0].rule == self.rule
assert futures[0].kwargs == {}
+
+ def test_latest_release_environment(self):
+ # setup an alert rule with 1 conditions and no filters that passes
+ release = self.create_release(
+ project=self.project,
+ version="2021-02.newRelease",
+ date_added=datetime(2020, 9, 1, 3, 8, 24, 880386),
+ environments=[self.environment],
+ )
+
+ self.event = self.store_event(
+ data={
+ "release": release.version,
+ "tags": [["environment", self.environment.name]],
+ },
+ project_id=self.project.id,
+ )
+
+ Rule.objects.filter(project=self.event.project).delete()
+ self.rule = Rule.objects.create(
+ environment_id=self.environment.id,
+ project=self.event.project,
+ data={
+ "actions": [EMAIL_ACTION_DATA],
+ "filter_match": "any",
+ "conditions": [
+ {
+ "id": "sentry.rules.filters.latest_release.LatestReleaseFilter",
+ "name": "The event is from the latest release",
+ },
+ ],
+ },
+ )
+
+ rp = RuleProcessor(
+ self.event,
+ is_new=True,
+ is_regression=False,
+ is_new_group_environment=True,
+ has_reappeared=False,
+ )
+ results = list(rp.apply())
+ assert len(results) == 1
+ callback, futures = results[0]
+ assert len(futures) == 1
+ assert futures[0].rule == self.rule
+ assert futures[0].kwargs == {}
|
e11ab6499ffa5c83d38d56ddce58562674f0c6e0
|
2022-03-29 06:33:59
|
Nar Saynorath
|
ref(dependencies): Move react-select-event to dependencies (#33035)
| false
|
Move react-select-event to dependencies (#33035)
|
ref
|
diff --git a/package.json b/package.json
index 2fe50c8a64f17f..19bd5cd2dd3294 100644
--- a/package.json
+++ b/package.json
@@ -125,6 +125,7 @@
"react-popper": "^1.3.11",
"react-router": "3.2.0",
"react-select": "^3.0.8",
+ "react-select-event": "5.3.0",
"react-sparklines": "1.7.0",
"react-virtualized": "^9.22.3",
"reflux": "0.4.1",
@@ -174,7 +175,6 @@
"postcss-jsx": "0.36.4",
"postcss-syntax": "0.36.2",
"react-refresh": "0.11.0",
- "react-select-event": "5.3.0",
"react-test-renderer": "17.0.2",
"size-limit": "^5.0.5",
"storybook-dark-mode": "^1.0.9",
|
b557c4b1e4f0f45a224df104f39dbc0fd602e8d3
|
2023-02-17 01:05:13
|
Matt Quinn
|
feat(perf-issues): Prepare MN+1 DB for release (#44664)
| false
|
Prepare MN+1 DB for release (#44664)
|
feat
|
diff --git a/bin/load-mocks b/bin/load-mocks
index 3e9941c0d62e57..c7e275e1566624 100755
--- a/bin/load-mocks
+++ b/bin/load-mocks
@@ -1160,6 +1160,58 @@ def create_mock_transactions(
},
)
+ def load_m_n_plus_one_issue():
+ trace_id = uuid4().hex
+ transaction_user = generate_user()
+
+ parent_span_id = uuid4().hex[:16]
+ duration = 200
+
+ def make_repeating_span(i):
+ nonlocal timestamp
+ nonlocal duration
+ start_timestamp = timestamp + timedelta(milliseconds=i * (duration + 1))
+ end_timestamp = start_timestamp + timedelta(milliseconds=duration)
+ op = "http" if i % 2 == 0 else "db"
+ description = "GET /" if i % 2 == 0 else "SELECT * FROM authors WHERE id = %s"
+ hash = "63f1e89e6a073441" if i % 2 == 0 else "a109ff3ef40f7fb3"
+ return {
+ "timestamp": end_timestamp.timestamp(),
+ "start_timestamp": start_timestamp.timestamp(),
+ "description": description,
+ "op": op,
+ "span_id": uuid4().hex[:16],
+ "parent_span_id": parent_span_id,
+ "hash": hash,
+ }
+
+ span_count = 10
+ repeating_spans = [make_repeating_span(i) for i in range(span_count)]
+
+ parent_span = {
+ "timestamp": (
+ timestamp + timedelta(milliseconds=span_count * (duration + 1))
+ ).timestamp(),
+ "start_timestamp": timestamp.timestamp(),
+ "description": "execute",
+ "op": "graphql.execute",
+ "parent_span_id": uuid4().hex[:16],
+ "span_id": parent_span_id,
+ "hash": "0f43fb6f6e01ca52",
+ }
+
+ create_sample_event(
+ project=backend_project,
+ platform="transaction",
+ transaction="/m_n_plus_one_db/backend/",
+ event_id=uuid4().hex,
+ user=transaction_user,
+ timestamp=timestamp + timedelta(milliseconds=span_count * (duration + 1) + 100),
+ start_timestamp=timestamp,
+ trace=trace_id,
+ spans=[parent_span] + repeating_spans,
+ )
+
def load_performance_issues():
print(f" > Loading performance issues data") # NOQA
print(f" > Loading n plus one issue") # NOQA
@@ -1170,6 +1222,8 @@ def create_mock_transactions(
load_uncompressed_asset_issue()
print(f" > Loading render blocking asset issue") # NOQA
load_render_blocking_asset_issue()
+ print(f" > Loading MN+1 issue") # NOQA
+ load_m_n_plus_one_issue()
load_performance_issues()
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index 7c256c3269be8d..f6d363bb6376d5 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -1177,6 +1177,8 @@ def SOCIAL_AUTH_DEFAULT_USERNAME():
"organizations:performance-issues-compressed-assets-detector": False,
# Enable render blocking assets performance issue type
"organizations:performance-issues-render-blocking-assets-detector": False,
+ # Enable MN+1 DB performance issue type
+ "organizations:performance-issues-m-n-plus-one-db-detector": False,
# Enable the new Related Events feature
"organizations:related-events": False,
# Enable usage of external relays, for use with Relay. See
diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py
index 7bde36bd3d8c36..1cb7f182959377 100644
--- a/src/sentry/features/__init__.py
+++ b/src/sentry/features/__init__.py
@@ -116,6 +116,7 @@
default_manager.add("organizations:performance-n-plus-one-api-calls-detector", OrganizationFeature)
default_manager.add("organizations:performance-issues-compressed-assets-detector", OrganizationFeature)
default_manager.add("organizations:performance-issues-render-blocking-assets-detector", OrganizationFeature)
+default_manager.add("organizations:performance-issues-m-n-plus-one-db-detector", OrganizationFeature)
default_manager.add("organizations:performance-issues-dev", OrganizationFeature, True)
default_manager.add("organizations:performance-issues-all-events-tab", OrganizationFeature, True)
default_manager.add("organizations:performance-issues-search", OrganizationFeature)
diff --git a/src/sentry/options/defaults.py b/src/sentry/options/defaults.py
index 31c5a8eb83b2f2..c090149e520a67 100644
--- a/src/sentry/options/defaults.py
+++ b/src/sentry/options/defaults.py
@@ -583,6 +583,10 @@
register("performance.issues.render_blocking_assets.la-rollout", default=0.0)
register("performance.issues.render_blocking_assets.ea-rollout", default=0.0)
register("performance.issues.render_blocking_assets.ga-rollout", default=0.0)
+register("performance.issues.m_n_plus_one_db.problem-creation", default=0.0)
+register("performance.issues.m_n_plus_one_db.la-rollout", default=0.0)
+register("performance.issues.m_n_plus_one_db.ea-rollout", default=0.0)
+register("performance.issues.m_n_plus_one_db.ga-rollout", default=0.0)
# System-wide options for default performance detection settings for any org opted into the performance-issues-ingest feature. Meant for rollout.
diff --git a/src/sentry/utils/performance_issues/base.py b/src/sentry/utils/performance_issues/base.py
index 3f3489acfae4bd..69a65d3c210422 100644
--- a/src/sentry/utils/performance_issues/base.py
+++ b/src/sentry/utils/performance_issues/base.py
@@ -61,6 +61,7 @@ class DetectorType(Enum):
DetectorType.UNCOMPRESSED_ASSETS: "performance.issues.compressed_assets.problem-creation",
DetectorType.SLOW_DB_QUERY: "performance.issues.slow_db_query.problem-creation",
DetectorType.RENDER_BLOCKING_ASSET_SPAN: "performance.issues.render_blocking_assets.problem-creation",
+ DetectorType.M_N_PLUS_ONE_DB: "organizations:performance-issues-m-n-plus-one-db-detector.problem-creation",
}
diff --git a/src/sentry/utils/performance_issues/performance_detection.py b/src/sentry/utils/performance_issues/performance_detection.py
index 24f7d8c3df704c..6c225103bf3bc6 100644
--- a/src/sentry/utils/performance_issues/performance_detection.py
+++ b/src/sentry/utils/performance_issues/performance_detection.py
@@ -1017,7 +1017,7 @@ def _maybe_performance_problem(self) -> Optional[PerformanceProblem]:
fingerprint=self._fingerprint(db_span["hash"], parent_span),
op="db",
desc=db_span["description"],
- type=PerformanceMNPlusOneDBQueriesGroupType,
+ type=PerformanceNPlusOneGroupType,
parent_span_ids=[parent_span["span_id"]],
cause_span_ids=[],
offender_span_ids=[span["span_id"] for span in offender_spans],
@@ -1073,6 +1073,16 @@ def init(self):
self.stored_problems = {}
self.state = SearchingForMNPlusOne(self.settings, self.event())
+ def is_creation_allowed_for_organization(self, organization: Optional[Organization]) -> bool:
+ return features.has(
+ "organizations:performance-issues-m-n-plus-one-db-detector",
+ organization,
+ actor=None,
+ )
+
+ def is_creation_allowed_for_project(self, project: Project) -> bool:
+ return True # Detection always allowed by project for now
+
def visit_span(self, span):
self.state, performance_problem = self.state.next(span)
if performance_problem:
diff --git a/tests/sentry/utils/performance_issues/test_m_n_plus_one_db_detector.py b/tests/sentry/utils/performance_issues/test_m_n_plus_one_db_detector.py
index 4563bbd1cf663f..9bb4ed712b35ac 100644
--- a/tests/sentry/utils/performance_issues/test_m_n_plus_one_db_detector.py
+++ b/tests/sentry/utils/performance_issues/test_m_n_plus_one_db_detector.py
@@ -4,7 +4,7 @@
import pytest
from sentry.eventstore.models import Event
-from sentry.issues.grouptype import PerformanceMNPlusOneDBQueriesGroupType
+from sentry.issues.grouptype import PerformanceNPlusOneGroupType
from sentry.testutils import TestCase
from sentry.testutils.performance_issues.event_generators import get_event
from sentry.testutils.silo import region_silo_test
@@ -37,7 +37,7 @@ def test_detects_parallel_m_n_plus_one(self):
PerformanceProblem(
fingerprint="1-1011-6807a9d5bedb6fdb175b006448cddf8cdf18fbd8",
op="db",
- type=PerformanceMNPlusOneDBQueriesGroupType,
+ type=PerformanceNPlusOneGroupType,
desc="SELECT id, name FROM authors INNER JOIN book_authors ON author_id = id WHERE book_id = $1",
parent_span_ids=[],
cause_span_ids=[],
@@ -69,7 +69,7 @@ def test_detects_parallel_m_n_plus_one(self):
],
)
]
- assert problems[0].title == "MN+1 Query"
+ assert problems[0].title == "N+1 Query"
def test_does_not_detect_truncated_m_n_plus_one(self):
event = get_event("m-n-plus-one-db/m-n-plus-one-graphql-truncated")
|
bc2a01482e24b1b04bfdc83b5a8d8ad935d03547
|
2020-03-26 21:40:33
|
Matej Minar
|
fix(ui): Fixed data massaging for keyValueList in richHttpContent (#17928)
| false
|
Fixed data massaging for keyValueList in richHttpContent (#17928)
|
fix
|
diff --git a/src/sentry/static/sentry/app/components/events/interfaces/richHttpContent/getTransformedData.tsx b/src/sentry/static/sentry/app/components/events/interfaces/richHttpContent/getTransformedData.tsx
index 7594e5f50dc275..45953846350d71 100644
--- a/src/sentry/static/sentry/app/components/events/interfaces/richHttpContent/getTransformedData.tsx
+++ b/src/sentry/static/sentry/app/components/events/interfaces/richHttpContent/getTransformedData.tsx
@@ -1,8 +1,18 @@
import {defined} from 'app/utils';
-function getTransformedData(data: any) {
+function getTransformedData(data: any): [string, string][] {
if (Array.isArray(data)) {
- return data.filter(dataValue => defined(dataValue));
+ return data
+ .filter(dataValue => defined(dataValue))
+ .map(dataValue => {
+ if (Array.isArray(dataValue)) {
+ return dataValue;
+ }
+ if (typeof data === 'object') {
+ return Object.keys(dataValue).flatMap(key => [key, dataValue[key]]);
+ }
+ return dataValue;
+ });
}
if (typeof data === 'object') {
|
33d1ced4d1411ee35e51ea347762ea5aaeb76e54
|
2019-02-05 04:56:55
|
Chris Clark
|
feat(visibility): no projects message (#11657)
| false
|
no projects message (#11657)
|
feat
|
diff --git a/src/sentry/static/sentry/app/views/organizationProjectsDashboard/emptyState.jsx b/src/sentry/static/sentry/app/components/noProjectMessage.jsx
similarity index 63%
rename from src/sentry/static/sentry/app/views/organizationProjectsDashboard/emptyState.jsx
rename to src/sentry/static/sentry/app/components/noProjectMessage.jsx
index 79d517d8f2613f..16e173dbee6576 100644
--- a/src/sentry/static/sentry/app/views/organizationProjectsDashboard/emptyState.jsx
+++ b/src/sentry/static/sentry/app/components/noProjectMessage.jsx
@@ -1,31 +1,44 @@
import React from 'react';
import {Flex} from 'grid-emotion';
import styled from 'react-emotion';
+import PropTypes from 'prop-types';
import {t} from 'app/locale';
import Button from 'app/components/button';
+import PageHeading from 'app/components/pageHeading';
import Tooltip from 'app/components/tooltip';
import SentryTypes from 'app/sentryTypes';
-import img from '../../../images/dashboard/hair-on-fire.svg';
+import space from 'app/styles/space';
+/* TODO: replace with I/O when finished */
+import img from '../../images/dashboard/hair-on-fire.svg';
-export default class EmptyState extends React.Component {
+export default class NoProjectMessage extends React.Component {
static propTypes = {
+ /* if the user has access to any projects, we show whatever
+ children are included. Otherwise we show the message */
+ children: PropTypes.node,
organization: SentryTypes.Organization,
+ className: PropTypes.string,
};
render() {
- const {organization} = this.props;
+ const {children, organization, className} = this.props;
const orgId = organization.slug;
const canCreateProject = organization.access.includes('project:write');
const canJoinTeam = organization.access.includes('team:read');
+ const hasProjects = organization.projects.some(p => p.isMember && p.hasAccess);
- return (
- <Flex flex="1" align="center" justify="center">
+ return hasProjects ? (
+ children
+ ) : (
+ <Flex flex="1" align="center" justify="center" className={className}>
<Wrapper>
<img src={img} height={350} alt="Nothing to see" />
<Content direction="column" justify="center">
- <h2>{t('Remain calm.')}</h2>
- <p>{t("Sentry's got you covered. To get started:")}</p>
+ <StyledPageHeading>{t('Remain Calm')}</StyledPageHeading>
+ <HelpMessage>
+ {t('You need at least one project to use this view')}
+ </HelpMessage>
<Flex align="center">
<CallToAction>
<Tooltip
@@ -63,6 +76,11 @@ export default class EmptyState extends React.Component {
}
}
+const StyledPageHeading = styled(PageHeading)`
+ font-size: 28px;
+ margin-bottom: ${space(1.5)};
+`;
+
const CallToAction = styled('div')`
margin-right: 8px;
&:last-child {
@@ -70,6 +88,10 @@ const CallToAction = styled('div')`
}
`;
+const HelpMessage = styled('div')`
+ margin-bottom: ${space(2)};
+`;
+
const Wrapper = styled(Flex)`
height: 350px;
`;
diff --git a/src/sentry/static/sentry/app/views/organizationEvents/index.jsx b/src/sentry/static/sentry/app/views/organizationEvents/index.jsx
index cef57e0a0d32ac..6041ce7bc6e813 100644
--- a/src/sentry/static/sentry/app/views/organizationEvents/index.jsx
+++ b/src/sentry/static/sentry/app/views/organizationEvents/index.jsx
@@ -8,6 +8,7 @@ import {t} from 'app/locale';
import BetaTag from 'app/components/betaTag';
import Feature from 'app/components/acl/feature';
import GlobalSelectionHeader from 'app/components/organizations/globalSelectionHeader';
+import NoProjectMessage from 'app/components/noProjectMessage';
import SentryTypes from 'app/sentryTypes';
import PageHeading from 'app/components/pageHeading';
import withGlobalSelection from 'app/utils/withGlobalSelection';
@@ -49,21 +50,22 @@ class OrganizationEventsContainer extends React.Component {
resetParamsOnChange={['cursor']}
/>
<PageContent>
- <Body>
- <PageHeader>
- <HeaderTitle>
- {t('Events')} <BetaTag />
- </HeaderTitle>
- <StyledSearchBar
- organization={organization}
- query={(location.query && location.query.query) || ''}
- placeholder={t('Search for events, users, tags, and everything else.')}
- onSearch={this.handleSearch}
- />
- </PageHeader>
-
- {children}
- </Body>
+ <NoProjectMessage organization={organization}>
+ <Body>
+ <PageHeader>
+ <HeaderTitle>
+ {t('Events')} <BetaTag />
+ </HeaderTitle>
+ <StyledSearchBar
+ organization={organization}
+ query={(location.query && location.query.query) || ''}
+ placeholder={t('Search for events, users, tags, and everything else.')}
+ onSearch={this.handleSearch}
+ />
+ </PageHeader>
+ {children}
+ </Body>
+ </NoProjectMessage>
</PageContent>
</Feature>
);
diff --git a/src/sentry/static/sentry/app/views/organizationProjectsDashboard/index.jsx b/src/sentry/static/sentry/app/views/organizationProjectsDashboard/index.jsx
index 453aa47334c45f..7d4fbacb0b6204 100644
--- a/src/sentry/static/sentry/app/views/organizationProjectsDashboard/index.jsx
+++ b/src/sentry/static/sentry/app/views/organizationProjectsDashboard/index.jsx
@@ -8,6 +8,7 @@ import styled from 'react-emotion';
import SentryTypes from 'app/sentryTypes';
import IdBadge from 'app/components/idBadge';
+import NoProjectMessage from 'app/components/noProjectMessage';
import OrganizationState from 'app/mixins/organizationState';
import ProjectsStatsStore from 'app/stores/projectsStatsStore';
import getProjectsByTeams from 'app/utils/getProjectsByTeams';
@@ -18,7 +19,6 @@ import {t} from 'app/locale';
import ProjectNav from './projectNav';
import TeamSection from './teamSection';
-import EmptyState from './emptyState';
import Resources from './resources';
class Dashboard extends React.Component {
@@ -90,9 +90,7 @@ class Dashboard extends React.Component {
);
})}
{teamSlugs.length === 0 &&
- favorites.length === 0 && (
- <EmptyState projects={projects} teams={teams} organization={organization} />
- )}
+ favorites.length === 0 && <NoProjectMessage organization={organization} />}
</React.Fragment>
);
}
diff --git a/src/sentry/static/sentry/app/views/organizationStream/container.jsx b/src/sentry/static/sentry/app/views/organizationStream/container.jsx
index 35f914dd69f183..fd1fad431ef721 100644
--- a/src/sentry/static/sentry/app/views/organizationStream/container.jsx
+++ b/src/sentry/static/sentry/app/views/organizationStream/container.jsx
@@ -5,6 +5,7 @@ import DocumentTitle from 'react-document-title';
import {PageContent} from 'app/styles/organization';
import Feature from 'app/components/acl/feature';
import GlobalSelectionHeader from 'app/components/organizations/globalSelectionHeader';
+import NoProjectMessage from 'app/components/noProjectMessage';
import SentryTypes from 'app/sentryTypes';
import withOrganization from 'app/utils/withOrganization';
@@ -25,7 +26,9 @@ class OrganizationStreamContainer extends React.Component {
<Feature features={['sentry10']} renderDisabled>
<GlobalSelectionHeader organization={organization} />
- <PageContent>{children}</PageContent>
+ <PageContent>
+ <NoProjectMessage organization={organization}>{children}</NoProjectMessage>
+ </PageContent>
</Feature>
</DocumentTitle>
);
diff --git a/src/sentry/static/sentry/app/views/releases/list/organizationReleases/index.jsx b/src/sentry/static/sentry/app/views/releases/list/organizationReleases/index.jsx
index 0ae4e3a13a1087..4bc63bd5fa71d9 100644
--- a/src/sentry/static/sentry/app/views/releases/list/organizationReleases/index.jsx
+++ b/src/sentry/static/sentry/app/views/releases/list/organizationReleases/index.jsx
@@ -11,6 +11,7 @@ import Alert from 'app/components/alert';
import EmptyStateWarning from 'app/components/emptyStateWarning';
import Feature from 'app/components/acl/feature';
import GlobalSelectionHeader from 'app/components/organizations/globalSelectionHeader';
+import NoProjectMessage from 'app/components/noProjectMessage';
import AsyncView from 'app/views/asyncView';
import withOrganization from 'app/utils/withOrganization';
import withGlobalSelection from 'app/utils/withGlobalSelection';
@@ -157,28 +158,30 @@ class OrganizationReleases extends AsyncView {
}
renderBody() {
- const {location} = this.props;
+ const {location, organization} = this.props;
return (
<PageContent>
- <PageHeader>
- <PageHeading>{t('Releases')}</PageHeading>
+ <NoProjectMessage organization={organization}>
+ <PageHeader>
+ <PageHeading>{t('Releases')}</PageHeading>
+ <div>
+ <SearchBar
+ defaultQuery=""
+ placeholder={t('Search for a release')}
+ query={location.query.query}
+ onSearch={this.onSearch}
+ />
+ </div>
+ </PageHeader>
<div>
- <SearchBar
- defaultQuery=""
- placeholder={t('Search for a release')}
- query={location.query.query}
- onSearch={this.onSearch}
- />
+ <Panel>
+ <ReleaseListHeader />
+ <PanelBody>{this.renderStreamBody()}</PanelBody>
+ </Panel>
+ <Pagination pageLinks={this.state.releaseListPageLinks} />
</div>
- </PageHeader>
- <div>
- <Panel>
- <ReleaseListHeader />
- <PanelBody>{this.renderStreamBody()}</PanelBody>
- </Panel>
- <Pagination pageLinks={this.state.releaseListPageLinks} />
- </div>
+ </NoProjectMessage>
</PageContent>
);
}
diff --git a/src/sentry/static/sentry/app/views/userFeedback/organizationUserFeedback.jsx b/src/sentry/static/sentry/app/views/userFeedback/organizationUserFeedback.jsx
index bb63cee91a4de5..99c0efaa675b44 100644
--- a/src/sentry/static/sentry/app/views/userFeedback/organizationUserFeedback.jsx
+++ b/src/sentry/static/sentry/app/views/userFeedback/organizationUserFeedback.jsx
@@ -10,6 +10,7 @@ import CompactIssue from 'app/components/compactIssue';
import EventUserFeedback from 'app/components/events/userFeedback';
import LoadingIndicator from 'app/components/loadingIndicator';
import GlobalSelectionHeader from 'app/components/organizations/globalSelectionHeader';
+import NoProjectMessage from 'app/components/noProjectMessage';
import AsyncView from 'app/views/asyncView';
import {PageContent} from 'app/styles/organization';
@@ -110,13 +111,15 @@ class OrganizationUserFeedback extends AsyncView {
>
<GlobalSelectionHeader organization={organization} />
<PageContent>
- <UserFeedbackContainer
- pageLinks={reportListPageLinks}
- status={status}
- location={location}
- >
- {this.renderStreamBody()}
- </UserFeedbackContainer>
+ <NoProjectMessage organization={organization}>
+ <UserFeedbackContainer
+ pageLinks={reportListPageLinks}
+ status={status}
+ location={location}
+ >
+ {this.renderStreamBody()}
+ </UserFeedbackContainer>
+ </NoProjectMessage>
</PageContent>
</Feature>
);
diff --git a/src/sentry/static/sentry/images/confused-io.png b/src/sentry/static/sentry/images/confused-io.png
new file mode 100644
index 00000000000000..c2bda3c2b2339c
Binary files /dev/null and b/src/sentry/static/sentry/images/confused-io.png differ
diff --git a/tests/acceptance/test_organization_releases.py b/tests/acceptance/test_organization_releases.py
index 3756c713b70932..e369674f7486b9 100644
--- a/tests/acceptance/test_organization_releases.py
+++ b/tests/acceptance/test_organization_releases.py
@@ -12,7 +12,10 @@ def setUp(self):
self.org = self.create_organization(
owner=self.user, name='Rowdy Tiger')
self.team = self.create_team(
- organization=self.org, name='Mariachi Band')
+ organization=self.org,
+ name='Mariachi Band',
+ members=[self.user],
+ )
self.project = self.create_project(
organization=self.org,
teams=[self.team],
diff --git a/tests/js/spec/views/organizationProjectsDashboard/index.spec.jsx b/tests/js/spec/views/organizationProjectsDashboard/index.spec.jsx
index 30f052770fe34e..58ecc33fefe260 100644
--- a/tests/js/spec/views/organizationProjectsDashboard/index.spec.jsx
+++ b/tests/js/spec/views/organizationProjectsDashboard/index.spec.jsx
@@ -62,7 +62,7 @@ describe('OrganizationDashboard', function() {
/>,
TestStubs.routerContext()
);
- const emptyState = wrapper.find('EmptyState');
+ const emptyState = wrapper.find('NoProjectMessage');
expect(emptyState).toHaveLength(1);
});
@@ -111,7 +111,7 @@ describe('OrganizationDashboard', function() {
/>,
TestStubs.routerContext()
);
- const emptyState = wrapper.find('EmptyState');
+ const emptyState = wrapper.find('NoProjectMessage');
const favorites = wrapper.find('TeamSection[data-test-id="favorites"]');
const teamSection = wrapper.find('TeamSection');
expect(emptyState).toHaveLength(0);
@@ -248,7 +248,7 @@ describe('OrganizationDashboard', function() {
expect(wrapper.find('TeamSection')).toHaveLength(1);
const projectCards = wrapper.find('ProjectCard');
expect(projectCards).toHaveLength(1);
- const emptyState = wrapper.find('EmptyState');
+ const emptyState = wrapper.find('NoProjectMessage');
expect(emptyState).toHaveLength(0);
});
});
diff --git a/tests/js/spec/views/organizationProjectsDashboard/emptyState.spec.jsx b/tests/js/spec/views/organizationProjectsDashboard/noProjectMessage.spec.jsx
similarity index 73%
rename from tests/js/spec/views/organizationProjectsDashboard/emptyState.spec.jsx
rename to tests/js/spec/views/organizationProjectsDashboard/noProjectMessage.spec.jsx
index b4a5987ef1d5c6..ffa5f07f243d78 100644
--- a/tests/js/spec/views/organizationProjectsDashboard/emptyState.spec.jsx
+++ b/tests/js/spec/views/organizationProjectsDashboard/noProjectMessage.spec.jsx
@@ -1,13 +1,13 @@
import {shallow} from 'enzyme';
import React from 'react';
-import EmptyState from 'app/views/organizationProjectsDashboard/emptyState';
+import NoProjectMessage from 'app/components/noProjectMessage';
-describe('EmptyState', function() {
+describe('NoProjectMessage', function() {
const org = TestStubs.Organization();
it('shows "Create Project" button when there are no projects', function() {
const wrapper = shallow(
- <EmptyState organization={org} projects={[]} />,
+ <NoProjectMessage organization={org} />,
TestStubs.routerContext()
);
expect(
@@ -17,7 +17,7 @@ describe('EmptyState', function() {
it('"Create Project" is disabled when no access to `project:write`', function() {
const wrapper = shallow(
- <EmptyState organization={TestStubs.Organization({access: []})} projects={[]} />,
+ <NoProjectMessage organization={TestStubs.Organization({access: []})} />,
TestStubs.routerContext()
);
expect(
@@ -27,7 +27,7 @@ describe('EmptyState', function() {
it('has "Join a Team" button', function() {
const wrapper = shallow(
- <EmptyState organization={org} projects={[]} />,
+ <NoProjectMessage organization={org} />,
TestStubs.routerContext()
);
expect(wrapper.find('Button[to="/settings/org-slug/teams/"]')).toHaveLength(1);
@@ -35,7 +35,7 @@ describe('EmptyState', function() {
it('has a disabled "Join a Team" button if no access to `team:read`', function() {
const wrapper = shallow(
- <EmptyState organization={TestStubs.Organization({access: []})} projects={[]} />,
+ <NoProjectMessage organization={TestStubs.Organization({access: []})} />,
TestStubs.routerContext()
);
expect(wrapper.find('Button[to="/settings/org-slug/teams/"]').prop('disabled')).toBe(
diff --git a/tests/js/spec/views/userFeedback/__snapshots__/organizationUserFeedback.spec.jsx.snap b/tests/js/spec/views/userFeedback/__snapshots__/organizationUserFeedback.spec.jsx.snap
index 2fb9dad230d6e3..71cf01679bcf0e 100644
--- a/tests/js/spec/views/userFeedback/__snapshots__/organizationUserFeedback.spec.jsx.snap
+++ b/tests/js/spec/views/userFeedback/__snapshots__/organizationUserFeedback.spec.jsx.snap
@@ -27,7 +27,17 @@ exports[`OrganizationUserFeedback renders 1`] = `
"id": "3",
"name": "Organization Name",
"onboardingTasks": Array [],
- "projects": Array [],
+ "projects": Array [
+ Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ ],
"scrapeJavaScript": true,
"slug": "org-slug",
"status": Object {
@@ -74,7 +84,17 @@ exports[`OrganizationUserFeedback renders 1`] = `
"id": "3",
"name": "Organization Name",
"onboardingTasks": Array [],
- "projects": Array [],
+ "projects": Array [
+ Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ ],
"scrapeJavaScript": true,
"slug": "org-slug",
"status": Object {
@@ -112,7 +132,17 @@ exports[`OrganizationUserFeedback renders 1`] = `
"id": "3",
"name": "Organization Name",
"onboardingTasks": Array [],
- "projects": Array [],
+ "projects": Array [
+ Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ ],
"scrapeJavaScript": true,
"slug": "org-slug",
"status": Object {
@@ -156,7 +186,17 @@ exports[`OrganizationUserFeedback renders 1`] = `
"id": "3",
"name": "Organization Name",
"onboardingTasks": Array [],
- "projects": Array [],
+ "projects": Array [
+ Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ ],
"scrapeJavaScript": true,
"slug": "org-slug",
"status": Object {
@@ -192,7 +232,17 @@ exports[`OrganizationUserFeedback renders 1`] = `
"id": "3",
"name": "Organization Name",
"onboardingTasks": Array [],
- "projects": Array [],
+ "projects": Array [
+ Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ ],
"scrapeJavaScript": true,
"slug": "org-slug",
"status": Object {
@@ -283,7 +333,9 @@ exports[`OrganizationUserFeedback renders 1`] = `
"pathname": undefined,
"query": Object {
"environment": Array [],
- "project": Array [],
+ "project": Array [
+ 2,
+ ],
"statsPeriod": "14d",
"utc": "true",
},
@@ -328,7 +380,17 @@ exports[`OrganizationUserFeedback renders 1`] = `
"id": "3",
"name": "Organization Name",
"onboardingTasks": Array [],
- "projects": Array [],
+ "projects": Array [
+ Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ ],
"scrapeJavaScript": true,
"slug": "org-slug",
"status": Object {
@@ -420,7 +482,9 @@ exports[`OrganizationUserFeedback renders 1`] = `
"pathname": undefined,
"query": Object {
"environment": Array [],
- "project": Array [],
+ "project": Array [
+ 2,
+ ],
"statsPeriod": "14d",
"utc": "true",
},
@@ -487,7 +551,17 @@ exports[`OrganizationUserFeedback renders 1`] = `
"id": "3",
"name": "Organization Name",
"onboardingTasks": Array [],
- "projects": Array [],
+ "projects": Array [
+ Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ ],
"scrapeJavaScript": true,
"slug": "org-slug",
"status": Object {
@@ -497,7 +571,19 @@ exports[`OrganizationUserFeedback renders 1`] = `
"teams": Array [],
}
}
- projects={Array []}
+ projects={
+ Array [
+ Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ ]
+ }
value={Array []}
>
<StyledProjectSelector
@@ -526,7 +612,17 @@ exports[`OrganizationUserFeedback renders 1`] = `
"id": "3",
"name": "Organization Name",
"onboardingTasks": Array [],
- "projects": Array [],
+ "projects": Array [
+ Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ ],
"scrapeJavaScript": true,
"slug": "org-slug",
"status": Object {
@@ -536,7 +632,19 @@ exports[`OrganizationUserFeedback renders 1`] = `
"teams": Array [],
}
}
- projects={Array []}
+ projects={
+ Array [
+ Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ ]
+ }
rootClassName="css-h5t9nh-rootContainerStyles"
selectedProjects={Array []}
value={Array []}
@@ -568,7 +676,17 @@ exports[`OrganizationUserFeedback renders 1`] = `
"id": "3",
"name": "Organization Name",
"onboardingTasks": Array [],
- "projects": Array [],
+ "projects": Array [
+ Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ ],
"scrapeJavaScript": true,
"slug": "org-slug",
"status": Object {
@@ -579,7 +697,19 @@ exports[`OrganizationUserFeedback renders 1`] = `
}
}
projectId={null}
- projects={Array []}
+ projects={
+ Array [
+ Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ ]
+ }
rootClassName="css-h5t9nh-rootContainerStyles"
selectedProjects={Array []}
value={Array []}
@@ -599,7 +729,23 @@ exports[`OrganizationUserFeedback renders 1`] = `
},
}
}
- items={Array []}
+ items={
+ Array [
+ Object {
+ "label": [Function],
+ "searchKey": "project-slug",
+ "value": Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ },
+ ]
+ }
maxHeight={500}
menuFooter={[Function]}
noResultsMessage="No projects found"
@@ -625,7 +771,23 @@ exports[`OrganizationUserFeedback renders 1`] = `
},
}
}
- items={Array []}
+ items={
+ Array [
+ Object {
+ "label": [Function],
+ "searchKey": "project-slug",
+ "value": Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ },
+ ]
+ }
maxHeight={500}
menuFooter={[Function]}
noResultsMessage="No projects found"
@@ -927,7 +1089,17 @@ exports[`OrganizationUserFeedback renders 1`] = `
"id": "3",
"name": "Organization Name",
"onboardingTasks": Array [],
- "projects": Array [],
+ "projects": Array [
+ Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ ],
"scrapeJavaScript": true,
"slug": "org-slug",
"status": Object {
@@ -962,7 +1134,17 @@ exports[`OrganizationUserFeedback renders 1`] = `
"id": "3",
"name": "Organization Name",
"onboardingTasks": Array [],
- "projects": Array [],
+ "projects": Array [
+ Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ ],
"scrapeJavaScript": true,
"slug": "org-slug",
"status": Object {
@@ -994,7 +1176,17 @@ exports[`OrganizationUserFeedback renders 1`] = `
"id": "3",
"name": "Organization Name",
"onboardingTasks": Array [],
- "projects": Array [],
+ "projects": Array [
+ Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ ],
"scrapeJavaScript": true,
"slug": "org-slug",
"status": Object {
@@ -1026,7 +1218,17 @@ exports[`OrganizationUserFeedback renders 1`] = `
"id": "3",
"name": "Organization Name",
"onboardingTasks": Array [],
- "projects": Array [],
+ "projects": Array [
+ Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ ],
"scrapeJavaScript": true,
"slug": "org-slug",
"status": Object {
@@ -1617,151 +1819,155 @@ exports[`OrganizationUserFeedback renders 1`] = `
<div
className="css-16fe6ul-PageContent e6lvex70"
>
- <UserFeedbackContainer
- location={
+ <NoProjectMessage
+ organization={
Object {
- "query": Object {},
- "search": "",
+ "access": Array [
+ "org:read",
+ "org:write",
+ "org:admin",
+ "project:read",
+ "project:write",
+ "project:admin",
+ "team:read",
+ "team:write",
+ "team:admin",
+ ],
+ "features": Array [
+ "sentry10",
+ ],
+ "id": "3",
+ "name": "Organization Name",
+ "onboardingTasks": Array [],
+ "projects": Array [
+ Object {
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ },
+ ],
+ "scrapeJavaScript": true,
+ "slug": "org-slug",
+ "status": Object {
+ "id": "active",
+ "name": "active",
+ },
+ "teams": Array [],
}
}
- pageLinks="<https://sentry.io/api/0/organizations/sentry/user-feedback/?statsPeriod=14d&cursor=0:0:1>; rel=\\"previous\\"; results=\\"false\\"; cursor=\\"0:0:1\\", <https://sentry.io/api/0/organizations/sentry/user-feedback/?statsPeriod=14d&cursor=0:100:0>; rel=\\"next\\"; results=\\"true\\"; cursor=\\"0:100:0\\""
- status="unresolved"
>
- <div>
- <div
- className="row"
- >
+ <UserFeedbackContainer
+ location={
+ Object {
+ "query": Object {},
+ "search": "",
+ }
+ }
+ pageLinks="<https://sentry.io/api/0/organizations/sentry/user-feedback/?statsPeriod=14d&cursor=0:0:1>; rel=\\"previous\\"; results=\\"false\\"; cursor=\\"0:0:1\\", <https://sentry.io/api/0/organizations/sentry/user-feedback/?statsPeriod=14d&cursor=0:100:0>; rel=\\"next\\"; results=\\"true\\"; cursor=\\"0:100:0\\""
+ status="unresolved"
+ >
+ <div>
<div
- className="col-sm-9"
- style={
- Object {
- "marginBottom": "5px",
- }
- }
+ className="row"
>
- <PageHeading
- withMargins={true}
+ <div
+ className="col-sm-9"
+ style={
+ Object {
+ "marginBottom": "5px",
+ }
+ }
>
- <Wrapper
+ <PageHeading
withMargins={true}
>
- <h1
- className="css-13ev48w-Wrapper e1f8hk460"
+ <Wrapper
+ withMargins={true}
>
- User Feedback
- </h1>
- </Wrapper>
- </PageHeading>
- </div>
- <div
- className="col-sm-3"
- style={
- Object {
- "marginTop": "4px",
- "textAlign": "right",
- }
- }
- >
+ <h1
+ className="css-13ev48w-Wrapper e1f8hk460"
+ >
+ User Feedback
+ </h1>
+ </Wrapper>
+ </PageHeading>
+ </div>
<div
- className="btn-group"
- >
- <Link
- className="btn btn-sm btn-default active"
- onlyActiveOnIndex={false}
- style={Object {}}
- to={
- Object {
- "pathname": undefined,
- "query": Object {},
- }
+ className="col-sm-3"
+ style={
+ Object {
+ "marginTop": "4px",
+ "textAlign": "right",
}
+ }
+ >
+ <div
+ className="btn-group"
>
- <a
+ <Link
className="btn btn-sm btn-default active"
- onClick={[Function]}
+ onlyActiveOnIndex={false}
style={Object {}}
- >
- Unresolved
- </a>
- </Link>
- <Link
- className="btn btn-sm btn-default"
- onlyActiveOnIndex={false}
- style={Object {}}
- to={
- Object {
- "pathname": undefined,
- "query": Object {
- "status": "",
- },
+ to={
+ Object {
+ "pathname": undefined,
+ "query": Object {},
+ }
}
- }
- >
- <a
+ >
+ <a
+ className="btn btn-sm btn-default active"
+ onClick={[Function]}
+ style={Object {}}
+ >
+ Unresolved
+ </a>
+ </Link>
+ <Link
className="btn btn-sm btn-default"
- onClick={[Function]}
+ onlyActiveOnIndex={false}
style={Object {}}
+ to={
+ Object {
+ "pathname": undefined,
+ "query": Object {
+ "status": "",
+ },
+ }
+ }
>
- All Issues
- </a>
- </Link>
+ <a
+ className="btn btn-sm btn-default"
+ onClick={[Function]}
+ style={Object {}}
+ >
+ All Issues
+ </a>
+ </Link>
+ </div>
</div>
</div>
- </div>
- <Panel>
- <Component
- className="css-yahxlu-Panel e1laxa7d0"
- >
- <div
+ <Panel>
+ <Component
className="css-yahxlu-Panel e1laxa7d0"
>
- <PanelBody
- className="issue-list"
- direction="column"
- disablePadding={true}
- flex={false}
+ <div
+ className="css-yahxlu-Panel e1laxa7d0"
>
- <div
- className="css-9vq8an-textStyles issue-list"
+ <PanelBody
+ className="issue-list"
+ direction="column"
+ disablePadding={true}
+ flex={false}
>
- <WithOrganizationMockWrapper
- data={
- Object {
- "assignedTo": null,
- "id": "1",
- "project": Object {
- "id": "2",
- "slug": "project-slug",
- },
- "stats": Object {
- "24h": Array [
- Array [
- 1517281200,
- 2,
- ],
- Array [
- 1517310000,
- 1,
- ],
- ],
- "30d": Array [
- Array [
- 1514764800,
- 1,
- ],
- Array [
- 1515024000,
- 122,
- ],
- ],
- },
- "tags": Array [],
- }
- }
- id="1"
- key="123"
+ <div
+ className="css-9vq8an-textStyles issue-list"
>
- <CompactIssue
+ <WithOrganizationMockWrapper
data={
Object {
"assignedTo": null,
@@ -1796,47 +2002,73 @@ exports[`OrganizationUserFeedback renders 1`] = `
}
}
id="1"
- organization={
- Object {
- "access": Array [
- "org:read",
- "org:write",
- "org:admin",
- "project:read",
- "project:write",
- "project:admin",
- "team:read",
- "team:write",
- "team:admin",
- ],
- "features": Array [],
- "id": "3",
- "name": "Organization Name",
- "onboardingTasks": Array [],
- "projects": Array [],
- "scrapeJavaScript": true,
- "slug": "org-slug",
- "status": Object {
- "id": "active",
- "name": "active",
- },
- "teams": Array [],
- }
- }
+ key="123"
>
- <PanelItem
- className="issue level-undefined"
- direction="column"
- p={2}
- style={
+ <CompactIssue
+ data={
Object {
- "paddingBottom": "6px",
- "paddingTop": "12px",
+ "assignedTo": null,
+ "id": "1",
+ "project": Object {
+ "id": "2",
+ "slug": "project-slug",
+ },
+ "stats": Object {
+ "24h": Array [
+ Array [
+ 1517281200,
+ 2,
+ ],
+ Array [
+ 1517310000,
+ 1,
+ ],
+ ],
+ "30d": Array [
+ Array [
+ 1514764800,
+ 1,
+ ],
+ Array [
+ 1515024000,
+ 122,
+ ],
+ ],
+ },
+ "tags": Array [],
+ }
+ }
+ id="1"
+ organization={
+ Object {
+ "access": Array [
+ "org:read",
+ "org:write",
+ "org:admin",
+ "project:read",
+ "project:write",
+ "project:admin",
+ "team:read",
+ "team:write",
+ "team:admin",
+ ],
+ "features": Array [],
+ "id": "3",
+ "name": "Organization Name",
+ "onboardingTasks": Array [],
+ "projects": Array [],
+ "scrapeJavaScript": true,
+ "slug": "org-slug",
+ "status": Object {
+ "id": "active",
+ "name": "active",
+ },
+ "teams": Array [],
}
}
>
- <Base
- className="issue level-undefined css-1cf8lr1-PanelItem eo8n7lk0"
+ <PanelItem
+ className="issue level-undefined"
direction="column"
p={2}
style={
@@ -1846,9 +2078,10 @@ exports[`OrganizationUserFeedback renders 1`] = `
}
}
>
- <div
+ <Base
className="issue level-undefined css-1cf8lr1-PanelItem eo8n7lk0"
- is={null}
+ direction="column"
+ p={2}
style={
Object {
"paddingBottom": "6px",
@@ -1856,297 +2089,255 @@ exports[`OrganizationUserFeedback renders 1`] = `
}
}
>
- <CompactIssueHeader
- data={
+ <div
+ className="issue level-undefined css-1cf8lr1-PanelItem eo8n7lk0"
+ is={null}
+ style={
Object {
- "assignedTo": null,
- "id": "1",
- "project": Object {
- "id": "2",
- "slug": "project-slug",
- },
- "stats": Object {
- "24h": Array [
- Array [
- 1517281200,
- 2,
- ],
- Array [
- 1517310000,
- 1,
- ],
- ],
- "30d": Array [
- Array [
- 1514764800,
- 1,
+ "paddingBottom": "6px",
+ "paddingTop": "12px",
+ }
+ }
+ >
+ <CompactIssueHeader
+ data={
+ Object {
+ "assignedTo": null,
+ "id": "1",
+ "project": Object {
+ "id": "2",
+ "slug": "project-slug",
+ },
+ "stats": Object {
+ "24h": Array [
+ Array [
+ 1517281200,
+ 2,
+ ],
+ Array [
+ 1517310000,
+ 1,
+ ],
],
- Array [
- 1515024000,
- 122,
+ "30d": Array [
+ Array [
+ 1514764800,
+ 1,
+ ],
+ Array [
+ 1515024000,
+ 122,
+ ],
],
- ],
- },
- "tags": Array [],
+ },
+ "tags": Array [],
+ }
}
- }
- organization={
- Object {
- "access": Array [
- "org:read",
- "org:write",
- "org:admin",
- "project:read",
- "project:write",
- "project:admin",
- "team:read",
- "team:write",
- "team:admin",
- ],
- "features": Array [],
- "id": "3",
- "name": "Organization Name",
- "onboardingTasks": Array [],
- "projects": Array [],
- "scrapeJavaScript": true,
- "slug": "org-slug",
- "status": Object {
- "id": "active",
- "name": "active",
- },
- "teams": Array [],
+ organization={
+ Object {
+ "access": Array [
+ "org:read",
+ "org:write",
+ "org:admin",
+ "project:read",
+ "project:write",
+ "project:admin",
+ "team:read",
+ "team:write",
+ "team:admin",
+ ],
+ "features": Array [],
+ "id": "3",
+ "name": "Organization Name",
+ "onboardingTasks": Array [],
+ "projects": Array [],
+ "scrapeJavaScript": true,
+ "slug": "org-slug",
+ "status": Object {
+ "id": "active",
+ "name": "active",
+ },
+ "teams": Array [],
+ }
}
- }
- projectId="project-slug"
- >
- <Flex
- align="center"
+ projectId="project-slug"
>
- <Base
+ <Flex
align="center"
- className="css-5ipae5"
>
- <div
+ <Base
+ align="center"
className="css-5ipae5"
- is={null}
>
- <Box
- mr={1}
+ <div
+ className="css-5ipae5"
+ is={null}
>
- <Base
- className="css-xgysgc"
+ <Box
mr={1}
>
- <div
+ <Base
className="css-xgysgc"
- is={null}
+ mr={1}
>
- <span
- className="error-level truncate"
- />
- </div>
- </Base>
- </Box>
- <h3
- className="truncate"
- >
- <ProjectLink
- to="/org-slug/project-slug/issues/1/"
+ <div
+ className="css-xgysgc"
+ is={null}
+ >
+ <span
+ className="error-level truncate"
+ />
+ </div>
+ </Base>
+ </Box>
+ <h3
+ className="truncate"
>
- <Link
- onlyActiveOnIndex={false}
- style={Object {}}
+ <ProjectLink
to="/org-slug/project-slug/issues/1/"
>
- <a
- onClick={[Function]}
+ <Link
+ onlyActiveOnIndex={false}
style={Object {}}
+ to="/org-slug/project-slug/issues/1/"
>
- <span
- className="icon icon-soundoff"
- />
- <span
- className="icon icon-star-solid"
- />
- <span />
- </a>
- </Link>
- </ProjectLink>
- </h3>
- </div>
- </Base>
- </Flex>
- <div
- className="event-extra"
- >
- <span
- className="project-name"
+ <a
+ onClick={[Function]}
+ style={Object {}}
+ >
+ <span
+ className="icon icon-soundoff"
+ />
+ <span
+ className="icon icon-star-solid"
+ />
+ <span />
+ </a>
+ </Link>
+ </ProjectLink>
+ </h3>
+ </div>
+ </Base>
+ </Flex>
+ <div
+ className="event-extra"
>
- <ProjectLink
- to="/org-slug/project-slug/"
+ <span
+ className="project-name"
>
- <Link
- onlyActiveOnIndex={false}
- style={Object {}}
+ <ProjectLink
to="/org-slug/project-slug/"
>
- <a
- onClick={[Function]}
+ <Link
+ onlyActiveOnIndex={false}
style={Object {}}
+ to="/org-slug/project-slug/"
>
- project-slug
- </a>
- </Link>
- </ProjectLink>
- </span>
- <span>
- <Link
- className="comments"
- to="/org-slug/project-slug/issues/1/activity/"
- >
+ <a
+ onClick={[Function]}
+ style={Object {}}
+ >
+ project-slug
+ </a>
+ </Link>
+ </ProjectLink>
+ </span>
+ <span>
<Link
className="comments"
- onlyActiveOnIndex={false}
- style={Object {}}
to="/org-slug/project-slug/issues/1/activity/"
>
- <a
+ <Link
className="comments"
- onClick={[Function]}
+ onlyActiveOnIndex={false}
style={Object {}}
+ to="/org-slug/project-slug/issues/1/activity/"
>
- <span
- className="icon icon-comments"
+ <a
+ className="comments"
+ onClick={[Function]}
style={Object {}}
- />
- <span
- className="tag-count"
- />
- </a>
+ >
+ <span
+ className="icon icon-comments"
+ style={Object {}}
+ />
+ <span
+ className="tag-count"
+ />
+ </a>
+ </Link>
</Link>
- </Link>
- </span>
- <span
- className="culprit"
- />
- </div>
- </CompactIssueHeader>
- <EventUserFeedback
- issueId="1"
- orgId="org-slug"
- report={
- Object {
- "comments": "Something bad happened",
- "dateCreated": "2018-12-20T00:00:00.000Z",
- "email": "[email protected]",
- "event": Object {
- "eventID": "12345678901234567890123456789012",
- "groupID": "1",
- "id": "1",
- "message": "ApiException",
- },
- "id": "123",
- "issue": Object {
- "assignedTo": null,
- "id": "1",
- "project": Object {
- "id": "2",
- "slug": "project-slug",
+ </span>
+ <span
+ className="culprit"
+ />
+ </div>
+ </CompactIssueHeader>
+ <EventUserFeedback
+ issueId="1"
+ orgId="org-slug"
+ report={
+ Object {
+ "comments": "Something bad happened",
+ "dateCreated": "2018-12-20T00:00:00.000Z",
+ "email": "[email protected]",
+ "event": Object {
+ "eventID": "12345678901234567890123456789012",
+ "groupID": "1",
+ "id": "1",
+ "message": "ApiException",
},
- "stats": Object {
- "24h": Array [
- Array [
- 1517281200,
- 2,
+ "id": "123",
+ "issue": Object {
+ "assignedTo": null,
+ "id": "1",
+ "project": Object {
+ "id": "2",
+ "slug": "project-slug",
+ },
+ "stats": Object {
+ "24h": Array [
+ Array [
+ 1517281200,
+ 2,
+ ],
+ Array [
+ 1517310000,
+ 1,
+ ],
],
- Array [
- 1517310000,
- 1,
+ "30d": Array [
+ Array [
+ 1514764800,
+ 1,
+ ],
+ Array [
+ 1515024000,
+ 122,
+ ],
],
- ],
- "30d": Array [
- Array [
- 1514764800,
- 1,
- ],
- Array [
- 1515024000,
- 122,
- ],
- ],
+ },
+ "tags": Array [],
},
- "tags": Array [],
- },
- "name": "Lyn",
+ "name": "Lyn",
+ }
}
- }
- >
- <div
- className="user-report"
>
<div
- className="activity-container"
+ className="user-report"
>
- <ul
- className="activity"
+ <div
+ className="activity-container"
>
- <li
- className="activity-note"
+ <ul
+ className="activity"
>
- <Avatar
- className="avatar"
- hasTooltip={false}
- size={38}
- user={
- Object {
- "comments": "Something bad happened",
- "dateCreated": "2018-12-20T00:00:00.000Z",
- "email": "[email protected]",
- "event": Object {
- "eventID": "12345678901234567890123456789012",
- "groupID": "1",
- "id": "1",
- "message": "ApiException",
- },
- "id": "123",
- "issue": Object {
- "assignedTo": null,
- "id": "1",
- "project": Object {
- "id": "2",
- "slug": "project-slug",
- },
- "stats": Object {
- "24h": Array [
- Array [
- 1517281200,
- 2,
- ],
- Array [
- 1517310000,
- 1,
- ],
- ],
- "30d": Array [
- Array [
- 1514764800,
- 1,
- ],
- Array [
- 1515024000,
- 122,
- ],
- ],
- },
- "tags": Array [],
- },
- "name": "Lyn",
- }
- }
+ <li
+ className="activity-note"
>
- <UserAvatar
+ <Avatar
className="avatar"
- gravatar={false}
hasTooltip={false}
size={38}
user={
@@ -2196,36 +2387,79 @@ exports[`OrganizationUserFeedback renders 1`] = `
}
}
>
- <BaseAvatar
+ <UserAvatar
className="avatar"
- gravatarId="[email protected]"
+ gravatar={false}
hasTooltip={false}
- letterId="[email protected]"
- round={true}
size={38}
- style={Object {}}
- title="Lyn"
- tooltip="Lyn ([email protected])"
- type="letter_avatar"
- uploadPath="avatar"
+ user={
+ Object {
+ "comments": "Something bad happened",
+ "dateCreated": "2018-12-20T00:00:00.000Z",
+ "email": "[email protected]",
+ "event": Object {
+ "eventID": "12345678901234567890123456789012",
+ "groupID": "1",
+ "id": "1",
+ "message": "ApiException",
+ },
+ "id": "123",
+ "issue": Object {
+ "assignedTo": null,
+ "id": "1",
+ "project": Object {
+ "id": "2",
+ "slug": "project-slug",
+ },
+ "stats": Object {
+ "24h": Array [
+ Array [
+ 1517281200,
+ 2,
+ ],
+ Array [
+ 1517310000,
+ 1,
+ ],
+ ],
+ "30d": Array [
+ Array [
+ 1514764800,
+ 1,
+ ],
+ Array [
+ 1515024000,
+ 122,
+ ],
+ ],
+ },
+ "tags": Array [],
+ },
+ "name": "Lyn",
+ }
+ }
>
- <Tooltip
- disabled={true}
- title="Lyn ([email protected])"
+ <BaseAvatar
+ className="avatar"
+ gravatarId="[email protected]"
+ hasTooltip={false}
+ letterId="[email protected]"
+ round={true}
+ size={38}
+ style={Object {}}
+ title="Lyn"
+ tooltip="Lyn ([email protected])"
+ type="letter_avatar"
+ uploadPath="avatar"
>
- <StyledBaseAvatar
- className="avatar avatar"
- loaded={true}
- round={true}
- style={
- Object {
- "height": "38px",
- "width": "38px",
- }
- }
+ <Tooltip
+ disabled={true}
+ title="Lyn ([email protected])"
>
- <span
- className="avatar avatar css-3f9bmx-StyledBaseAvatar e1z0ohzl0"
+ <StyledBaseAvatar
+ className="avatar avatar"
+ loaded={true}
+ round={true}
style={
Object {
"height": "38px",
@@ -2233,152 +2467,162 @@ exports[`OrganizationUserFeedback renders 1`] = `
}
}
>
- <LetterAvatar
- displayName="Lyn"
- identifier="[email protected]"
- round={true}
+ <span
+ className="avatar avatar css-3f9bmx-StyledBaseAvatar e1z0ohzl0"
+ style={
+ Object {
+ "height": "38px",
+ "width": "38px",
+ }
+ }
>
- <Svg
+ <LetterAvatar
+ displayName="Lyn"
+ identifier="[email protected]"
round={true}
- viewBox="0 0 120 120"
>
- <svg
- className="css-1r4mnb9-Svg e1knxa8x0"
+ <Svg
+ round={true}
viewBox="0 0 120 120"
>
- <rect
- fill="#57b1be"
- height="120"
- rx="15"
- ry="15"
- width="120"
- x="0"
- y="0"
- />
- <text
- fill="#FFFFFF"
- fontSize="65"
- style={
- Object {
- "dominantBaseline": "central",
- }
- }
- textAnchor="middle"
- x="50%"
- y="50%"
+ <svg
+ className="css-1r4mnb9-Svg e1knxa8x0"
+ viewBox="0 0 120 120"
>
- L
- </text>
- </svg>
- </Svg>
- </LetterAvatar>
- </span>
- </StyledBaseAvatar>
- </Tooltip>
- </BaseAvatar>
- </UserAvatar>
- </Avatar>
- <div
- className="activity-bubble"
- >
- <div>
- <TimeSince
- date="2018-12-20T00:00:00.000Z"
- suffix="ago"
- >
- <time
- dateTime="2018-12-20T00:00:00.000Z"
- title="December 20, 2018 12:00 AM UTC"
+ <rect
+ fill="#57b1be"
+ height="120"
+ rx="15"
+ ry="15"
+ width="120"
+ x="0"
+ y="0"
+ />
+ <text
+ fill="#FFFFFF"
+ fontSize="65"
+ style={
+ Object {
+ "dominantBaseline": "central",
+ }
+ }
+ textAnchor="middle"
+ x="50%"
+ y="50%"
+ >
+ L
+ </text>
+ </svg>
+ </Svg>
+ </LetterAvatar>
+ </span>
+ </StyledBaseAvatar>
+ </Tooltip>
+ </BaseAvatar>
+ </UserAvatar>
+ </Avatar>
+ <div
+ className="activity-bubble"
+ >
+ <div>
+ <TimeSince
+ date="2018-12-20T00:00:00.000Z"
+ suffix="ago"
>
- in a year
- </time>
- </TimeSince>
- <div
- className="activity-author"
- >
- Lyn
- <small>
- [email protected]
- </small>
- <small>
- <Link
- to="/organizations/org-slug/issues/1/events/1/"
+ <time
+ dateTime="2018-12-20T00:00:00.000Z"
+ title="December 20, 2018 12:00 AM UTC"
>
+ in a year
+ </time>
+ </TimeSince>
+ <div
+ className="activity-author"
+ >
+ Lyn
+ <small>
+ [email protected]
+ </small>
+ <small>
<Link
- onlyActiveOnIndex={false}
- style={Object {}}
to="/organizations/org-slug/issues/1/events/1/"
>
- <a
- onClick={[Function]}
+ <Link
+ onlyActiveOnIndex={false}
style={Object {}}
+ to="/organizations/org-slug/issues/1/events/1/"
>
- View event
- </a>
+ <a
+ onClick={[Function]}
+ style={Object {}}
+ >
+ View event
+ </a>
+ </Link>
</Link>
- </Link>
- </small>
- </div>
- <p
- dangerouslySetInnerHTML={
- Object {
- "__html": "Something bad happened",
+ </small>
+ </div>
+ <p
+ dangerouslySetInnerHTML={
+ Object {
+ "__html": "Something bad happened",
+ }
}
- }
- />
+ />
+ </div>
</div>
- </div>
- </li>
- </ul>
+ </li>
+ </ul>
+ </div>
</div>
- </div>
- </EventUserFeedback>
- </div>
- </Base>
- </PanelItem>
- </CompactIssue>
- </WithOrganizationMockWrapper>
- </div>
- </PanelBody>
- </div>
- </Component>
- </Panel>
- <Pagination
- className="stream-pagination"
- onCursor={[Function]}
- pageLinks="<https://sentry.io/api/0/organizations/sentry/user-feedback/?statsPeriod=14d&cursor=0:0:1>; rel=\\"previous\\"; results=\\"false\\"; cursor=\\"0:0:1\\", <https://sentry.io/api/0/organizations/sentry/user-feedback/?statsPeriod=14d&cursor=0:100:0>; rel=\\"next\\"; results=\\"true\\"; cursor=\\"0:100:0\\""
- >
- <div
- className="clearfix stream-pagination"
+ </EventUserFeedback>
+ </div>
+ </Base>
+ </PanelItem>
+ </CompactIssue>
+ </WithOrganizationMockWrapper>
+ </div>
+ </PanelBody>
+ </div>
+ </Component>
+ </Panel>
+ <Pagination
+ className="stream-pagination"
+ onCursor={[Function]}
+ pageLinks="<https://sentry.io/api/0/organizations/sentry/user-feedback/?statsPeriod=14d&cursor=0:0:1>; rel=\\"previous\\"; results=\\"false\\"; cursor=\\"0:0:1\\", <https://sentry.io/api/0/organizations/sentry/user-feedback/?statsPeriod=14d&cursor=0:100:0>; rel=\\"next\\"; results=\\"true\\"; cursor=\\"0:100:0\\""
>
<div
- className="btn-group pull-right"
+ className="clearfix stream-pagination"
>
- <a
- className="btn btn-default btn-lg prev disabled"
- disabled={true}
- onClick={[Function]}
- >
- <span
- className="icon-arrow-left"
- title="Previous"
- />
- </a>
- <a
- className="btn btn-default btn-lg next"
- disabled={false}
- onClick={[Function]}
+ <div
+ className="btn-group pull-right"
>
- <span
- className="icon-arrow-right"
- title="Next"
- />
- </a>
+ <a
+ className="btn btn-default btn-lg prev disabled"
+ disabled={true}
+ onClick={[Function]}
+ >
+ <span
+ className="icon-arrow-left"
+ title="Previous"
+ />
+ </a>
+ <a
+ className="btn btn-default btn-lg next"
+ disabled={false}
+ onClick={[Function]}
+ >
+ <span
+ className="icon-arrow-right"
+ title="Next"
+ />
+ </a>
+ </div>
</div>
- </div>
- </Pagination>
- </div>
- </UserFeedbackContainer>
+ </Pagination>
+ </div>
+ </UserFeedbackContainer>
+ </NoProjectMessage>
</div>
</PageContent>
</Feature>
diff --git a/tests/js/spec/views/userFeedback/organizationUserFeedback.spec.jsx b/tests/js/spec/views/userFeedback/organizationUserFeedback.spec.jsx
index 65dfb14ddc7ea7..f0b441bdb1361e 100644
--- a/tests/js/spec/views/userFeedback/organizationUserFeedback.spec.jsx
+++ b/tests/js/spec/views/userFeedback/organizationUserFeedback.spec.jsx
@@ -37,7 +37,10 @@ describe('OrganizationUserFeedback', function() {
it('renders', function() {
const params = {
- organization: TestStubs.Organization({features: ['sentry10']}),
+ organization: TestStubs.Organization({
+ features: ['sentry10'],
+ projects: [TestStubs.Project({isMember: true})],
+ }),
location: {query: {}, search: ''},
params: {
orgId: organization.slug,
|
09645809ea1242c3c85a6e8388c41c213462a465
|
2023-06-17 01:54:32
|
Evan Purkhiser
|
ref(js): Remove unused RadioGroupRating (#51092)
| false
|
Remove unused RadioGroupRating (#51092)
|
ref
|
diff --git a/static/app/components/radioGroupRating.spec.tsx b/static/app/components/radioGroupRating.spec.tsx
deleted file mode 100644
index f9625734872a01..00000000000000
--- a/static/app/components/radioGroupRating.spec.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
-
-import {
- RadioGroupRating,
- RadioGroupRatingProps,
-} from 'sentry/components/radioGroupRating';
-
-const options: RadioGroupRatingProps['options'] = {
- 0: {
- label: 'Very Dissatisfied',
- description: "Not disappointed (It isn't really useful)",
- },
- 1: {
- label: 'Dissatisfied',
- },
- 2: {
- label: 'Neutral',
- },
- 3: {
- label: 'Satisfied',
- },
- 4: {
- description: "Very disappointed (It's a deal breaker)",
- label: 'Very Satisfied',
- },
-};
-
-describe('RadioGroupRating', function () {
- it('render numerical labels', async function () {
- const handleChange = jest.fn();
-
- render(
- <RadioGroupRating
- name="feelingIfFeatureNotAvailableRating"
- options={options}
- onChange={handleChange}
- label="How satisfied are you with this feature?"
- />
- );
-
- expect(
- screen.getByText('How satisfied are you with this feature?')
- ).toBeInTheDocument();
-
- expect(screen.getAllByRole('radio')).toHaveLength(Object.keys(options).length);
-
- Object.keys(options).forEach((key, index) => {
- expect(screen.getByText(index + 1)).toBeInTheDocument();
- expect(
- screen.getByLabelText(`Select option ${options[key].label}`)
- ).toBeInTheDocument();
-
- const description = options[key].description;
- if (description) {
- expect(screen.getByText(description)).toBeInTheDocument();
- }
- });
-
- // Click on the first option
- await userEvent.click(screen.getByLabelText(`Select option ${options[0].label}`));
- expect(handleChange).toHaveBeenCalledWith('0');
- });
-});
diff --git a/static/app/components/radioGroupRating.tsx b/static/app/components/radioGroupRating.tsx
deleted file mode 100644
index c0c8f6fd6e7e2d..00000000000000
--- a/static/app/components/radioGroupRating.tsx
+++ /dev/null
@@ -1,107 +0,0 @@
-import {useCallback, useState} from 'react';
-import {css} from '@emotion/react';
-import styled from '@emotion/styled';
-
-import {getButtonStyles} from 'sentry/components/button';
-import FieldGroup from 'sentry/components/forms/fieldGroup';
-import {FieldGroupProps} from 'sentry/components/forms/fieldGroup/types';
-import {t} from 'sentry/locale';
-import {space} from 'sentry/styles/space';
-
-type Option = {label: string; description?: string};
-
-export type RadioGroupRatingProps = Omit<FieldGroupProps, 'children'> & {
- /**
- * Field name, used in all radio group elements
- */
- name: string;
- /**
- * An object of options, where the label is used for the aria-label,
- * the key is used for the selection and
- * the optional description to provide more context
- */
- options: Record<string, Option>;
- /**
- * The key of the option that should be selected by default
- */
- defaultValue?: string;
- /**
- * Callback function that is called when the selection changes.
- * its value is the key of the selected option
- */
- onChange?: (value: string) => void;
-};
-
-// Used to provide insights regarding opinions and experiences.
-// Currently limited to numeric options only, but can be updated to meet other needs.
-export function RadioGroupRating({
- options,
- name,
- onChange,
- defaultValue,
- ...fieldProps
-}: RadioGroupRatingProps) {
- const [selectedOption, setSelectedOption] = useState(defaultValue);
-
- const handleClickedOption = useCallback(
- (value: string) => {
- setSelectedOption(value);
- onChange?.(value);
- },
- [onChange]
- );
-
- return (
- <FieldGroup {...fieldProps}>
- <Wrapper totalOptions={Object.keys(options).length}>
- {Object.entries(options).map(([key, option], index) => (
- <OptionWrapper key={key}>
- <Label
- selected={key === selectedOption}
- htmlFor={key}
- onClick={() => handleClickedOption(key)}
- aria-label={t('Select option %s', option.label)}
- >
- {index + 1}
- </Label>
- <HiddenInput type="radio" id={key} name={name} value={option.label} />
- <Description>{option.description}</Description>
- </OptionWrapper>
- ))}
- </Wrapper>
- </FieldGroup>
- );
-}
-
-const HiddenInput = styled('input')`
- display: none;
-`;
-
-const Wrapper = styled('div')<{totalOptions: number}>`
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(50px, 1fr));
- margin-top: ${space(0.5)};
- gap: ${space(1)};
-`;
-
-const OptionWrapper = styled('div')`
- display: flex;
- align-items: center;
- flex-direction: column;
-`;
-
-const Label = styled('label')<{'aria-label': string; selected: boolean}>`
- cursor: pointer;
- ${p => css`
- ${getButtonStyles({
- theme: p.theme,
- size: 'md',
- 'aria-label': p['aria-label'],
- priority: p.selected ? 'primary' : 'default',
- })}
- `}
-`;
-
-const Description = styled('div')`
- text-align: center;
-`;
|
44ed37228bd5562e9014d778b4a21ea2cb37a2dc
|
2022-08-03 12:54:13
|
Joris Bayer
|
feat(metrics): Bring back computed measurements (#37330)
| false
|
Bring back computed measurements (#37330)
|
feat
|
diff --git a/src/sentry/relay/config/__init__.py b/src/sentry/relay/config/__init__.py
index 274d32a8ad882e..897ad938f30119 100644
--- a/src/sentry/relay/config/__init__.py
+++ b/src/sentry/relay/config/__init__.py
@@ -414,10 +414,13 @@ def _filter_option_to_config_setting(flt, setting):
"d:transactions/measurements.fid@millisecond",
"d:transactions/measurements.fp@millisecond",
"d:transactions/measurements.frames_frozen@none",
+ "d:transactions/measurements.frames_frozen_rate@ratio",
"d:transactions/measurements.frames_slow@none",
+ "d:transactions/measurements.frames_slow_rate@ratio",
"d:transactions/measurements.frames_total@none",
"d:transactions/measurements.stall_count@none",
"d:transactions/measurements.stall_longest_time@millisecond",
+ "d:transactions/measurements.stall_percentage@ratio",
"d:transactions/measurements.stall_total_time@millisecond",
"d:transactions/measurements.ttfb@millisecond",
"d:transactions/measurements.ttfb.requesttime@millisecond",
diff --git a/src/sentry/sentry_metrics/indexer/strings.py b/src/sentry/sentry_metrics/indexer/strings.py
index b821023c422178..1e79b88027b6d4 100644
--- a/src/sentry/sentry_metrics/indexer/strings.py
+++ b/src/sentry/sentry_metrics/indexer/strings.py
@@ -51,7 +51,7 @@
"d:transactions/measurements.frames_total@none": PREFIX + 113,
"d:transactions/measurements.stall_count@none": PREFIX + 114,
"d:transactions/measurements.stall_longest_time@millisecond": PREFIX + 115,
- "d:transactions/measurements.stall_percentage@percent": PREFIX + 116,
+ "d:transactions/measurements.stall_percentage@ratio": PREFIX + 116,
"d:transactions/measurements.stall_total_time@millisecond": PREFIX + 117,
"d:transactions/measurements.ttfb@millisecond": PREFIX + 118,
"d:transactions/measurements.ttfb.requesttime@millisecond": PREFIX + 119,
diff --git a/src/sentry/snuba/metrics/naming_layer/mri.py b/src/sentry/snuba/metrics/naming_layer/mri.py
index 52db7ecc784ab7..f643ec3a347ab2 100644
--- a/src/sentry/snuba/metrics/naming_layer/mri.py
+++ b/src/sentry/snuba/metrics/naming_layer/mri.py
@@ -85,7 +85,7 @@ class TransactionMRI(Enum):
MEASUREMENTS_FRAMES_TOTAL = "d:transactions/measurements.frames_total@none"
MEASUREMENTS_STALL_COUNT = "d:transactions/measurements.stall_count@none"
MEASUREMENTS_STALL_LONGEST_TIME = "d:transactions/measurements.stall_longest_time@millisecond"
- MEASUREMENTS_STALL_PERCENTAGE = "d:transactions/measurements.stall_percentage@percent"
+ MEASUREMENTS_STALL_PERCENTAGE = "d:transactions/measurements.stall_percentage@ratio"
MEASUREMENTS_STALL_TOTAL_TIME = "d:transactions/measurements.stall_total_time@millisecond"
MEASUREMENTS_TTFB = "d:transactions/measurements.ttfb@millisecond"
MEASUREMENTS_TTFB_REQUEST_TIME = "d:transactions/measurements.ttfb.requesttime@millisecond"
diff --git a/tests/relay_integration/test_metrics_extraction.py b/tests/relay_integration/test_metrics_extraction.py
index 396ccfa69b0bfe..4758c8a08b8043 100644
--- a/tests/relay_integration/test_metrics_extraction.py
+++ b/tests/relay_integration/test_metrics_extraction.py
@@ -1,4 +1,5 @@
import uuid
+from unittest import skip
import confluent_kafka as kafka
@@ -10,6 +11,7 @@
from sentry.utils import json
+@skip("Requires https://github.com/getsentry/relay/pull/1373")
class MetricsExtractionTest(RelayStoreHelper, TransactionTestCase):
def test_all_transaction_metrics_emitted(self):
with Feature(
diff --git a/tests/sentry/relay/snapshots/test_config/test_project_config_with_breakdown/with_metrics.pysnap b/tests/sentry/relay/snapshots/test_config/test_project_config_with_breakdown/with_metrics.pysnap
index 7eb2bd32dfcc44..3275540b8f077d 100644
--- a/tests/sentry/relay/snapshots/test_config/test_project_config_with_breakdown/with_metrics.pysnap
+++ b/tests/sentry/relay/snapshots/test_config/test_project_config_with_breakdown/with_metrics.pysnap
@@ -928,11 +928,14 @@ transactionMetrics:
- d:transactions/measurements.fid@millisecond
- d:transactions/measurements.fp@millisecond
- d:transactions/measurements.frames_frozen@none
+ - d:transactions/measurements.frames_frozen_rate@ratio
- d:transactions/measurements.frames_slow@none
+ - d:transactions/measurements.frames_slow_rate@ratio
- d:transactions/measurements.frames_total@none
- d:transactions/measurements.lcp@millisecond
- d:transactions/measurements.stall_count@none
- d:transactions/measurements.stall_longest_time@millisecond
+ - d:transactions/measurements.stall_percentage@ratio
- d:transactions/measurements.stall_total_time@millisecond
- d:transactions/measurements.ttfb.requesttime@millisecond
- d:transactions/measurements.ttfb@millisecond
|
2e326d4aacf3e4ae4f3cf2cca7f77086516b134e
|
2024-08-26 20:38:39
|
Raj Joshi
|
chore(pagerduty): Remove 404 of Pagerduty Installation Not Found (#76349)
| false
|
Remove 404 of Pagerduty Installation Not Found (#76349)
|
chore
|
diff --git a/src/sentry/integrations/pagerduty/utils.py b/src/sentry/integrations/pagerduty/utils.py
index 5a25a911e79df8..3ab4b1a38d69f8 100644
--- a/src/sentry/integrations/pagerduty/utils.py
+++ b/src/sentry/integrations/pagerduty/utils.py
@@ -15,6 +15,7 @@
from sentry.shared_integrations.client.proxy import infer_org_integration
from sentry.shared_integrations.exceptions import ApiError
from sentry.silo.base import control_silo_function
+from sentry.utils import metrics
logger = logging.getLogger("sentry.integrations.pagerduty")
@@ -193,7 +194,10 @@ def send_incident_alert_notification(
"target_identifier": action.target_identifier,
},
)
- raise Http404
+ metrics.incr(
+ "pagerduty.metric_alert_rule.integration_removed_after_rule_creation", sample_rate=1.0
+ )
+ return False
attachment = build_incident_attachment(
incident, client.integration_key, new_status, metric_value, notification_uuid
|
5b3a1b9b934f5c8085eb881e1c0d89ba9c99d013
|
2024-04-09 23:42:15
|
Dan Fuller
|
fix(crons): Fix bugs related to seat assignment when updating a monitor (#68491)
| false
|
Fix bugs related to seat assignment when updating a monitor (#68491)
|
fix
|
diff --git a/src/sentry/monitors/endpoints/base_monitor_details.py b/src/sentry/monitors/endpoints/base_monitor_details.py
index 2de5decd6d5a35..d0f3ebc3db6938 100644
--- a/src/sentry/monitors/endpoints/base_monitor_details.py
+++ b/src/sentry/monitors/endpoints/base_monitor_details.py
@@ -112,22 +112,22 @@ def update_monitor(
if "project" in result and result["project"].id != monitor.project_id:
raise ParameterValidationError("existing monitors may not be moved between projects")
- # Update monitor slug
- if "slug" in result:
- quotas.backend.update_monitor_slug(monitor.slug, params["slug"], monitor.project_id)
-
# Attempt to assign a monitor seat
- if params["status"] == ObjectStatus.ACTIVE:
+ if params["status"] == ObjectStatus.ACTIVE and monitor.status != ObjectStatus.ACTIVE:
outcome = quotas.backend.assign_monitor_seat(monitor)
- # The MonitorValidator checks if a seat assignment is availble.
+ # The MonitorValidator checks if a seat assignment is available.
# This protects against a race condition
if outcome != Outcome.ACCEPTED:
raise ParameterValidationError("Failed to enable monitor, please try again")
# Attempt to unassign the monitor seat
- if params["status"] == ObjectStatus.DISABLED:
+ if params["status"] == ObjectStatus.DISABLED and monitor.status != ObjectStatus.DISABLED:
quotas.backend.disable_monitor_seat(monitor)
+ # Update monitor slug in billing
+ if "slug" in result:
+ quotas.backend.update_monitor_slug(monitor.slug, params["slug"], monitor.project_id)
+
if params:
monitor.update(**params)
self.create_audit_entry(
diff --git a/tests/sentry/monitors/endpoints/test_base_monitor_details.py b/tests/sentry/monitors/endpoints/test_base_monitor_details.py
index 18f71f4267339a..8a84e2dbe51d63 100644
--- a/tests/sentry/monitors/endpoints/test_base_monitor_details.py
+++ b/tests/sentry/monitors/endpoints/test_base_monitor_details.py
@@ -686,6 +686,64 @@ def test_activate_monitor_success(self, assign_monitor_seat, check_assign_monito
assert monitor.status == ObjectStatus.ACTIVE
assert assign_monitor_seat.called
+ @patch("sentry.quotas.backend.check_assign_monitor_seat")
+ @patch("sentry.quotas.backend.assign_monitor_seat")
+ def test_no_activate_if_already_activated(self, assign_monitor_seat, check_assign_monitor_seat):
+ check_assign_monitor_seat.return_value = SeatAssignmentResult(assignable=True)
+ assign_monitor_seat.return_value = Outcome.ACCEPTED
+
+ monitor = self._create_monitor()
+
+ self.get_success_response(
+ self.organization.slug, monitor.slug, method="PUT", **{"status": "active"}
+ )
+
+ monitor = Monitor.objects.get(id=monitor.id)
+ assert monitor.status == ObjectStatus.ACTIVE
+ assert not assign_monitor_seat.called
+
+ @patch("sentry.quotas.backend.disable_monitor_seat")
+ def test_no_disable_if_already_disabled(self, disable_monitor_seat):
+ monitor = self._create_monitor()
+
+ self.get_success_response(
+ self.organization.slug, monitor.slug, method="PUT", **{"status": "active"}
+ )
+ monitor.update(status=ObjectStatus.DISABLED)
+ monitor = Monitor.objects.get(id=monitor.id)
+ assert monitor.status == ObjectStatus.DISABLED
+ assert not disable_monitor_seat.called
+
+ @patch("sentry.quotas.backend.update_monitor_slug")
+ @patch("sentry.quotas.backend.check_assign_monitor_seat")
+ @patch("sentry.quotas.backend.assign_monitor_seat")
+ def test_update_slug_sends_right_slug_to_assign(
+ self, assign_monitor_seat, check_assign_monitor_seat, update_monitor_slug
+ ):
+ check_assign_monitor_seat.return_value = SeatAssignmentResult(assignable=True)
+
+ def dummy_assign(monitor):
+ assert monitor.slug == old_slug
+ return Outcome.ACCEPTED
+
+ assign_monitor_seat.side_effect = dummy_assign
+
+ monitor = self._create_monitor()
+ monitor.update(status=ObjectStatus.DISABLED)
+ old_slug = monitor.slug
+ new_slug = "new_slug"
+ self.get_success_response(
+ self.organization.slug,
+ monitor.slug,
+ method="PUT",
+ **{"status": "active", "slug": new_slug},
+ )
+
+ monitor = Monitor.objects.get(id=monitor.id)
+ assert monitor.status == ObjectStatus.ACTIVE
+ update_call_args = update_monitor_slug.call_args
+ assert update_call_args[0] == (old_slug, new_slug, monitor.project_id)
+
@patch("sentry.quotas.backend.check_assign_monitor_seat")
@patch("sentry.quotas.backend.assign_monitor_seat")
def test_activate_monitor_invalid(self, assign_monitor_seat, check_assign_monitor_seat):
|
9afaa3818d965ddd06d28fc4fec7346ab83250f3
|
2023-07-13 22:40:40
|
Gilbert Szeto
|
feat(group-attributes): log a metric when certain fields for Group and related tables are updated (#52646)
| false
|
log a metric when certain fields for Group and related tables are updated (#52646)
|
feat
|
diff --git a/src/sentry/issues/attributes.py b/src/sentry/issues/attributes.py
new file mode 100644
index 00000000000000..201ae12f9aaf22
--- /dev/null
+++ b/src/sentry/issues/attributes.py
@@ -0,0 +1,106 @@
+import logging
+from enum import Enum
+from typing import Optional
+
+from django.db.models.signals import post_delete, post_save
+from django.dispatch import receiver
+
+from sentry.models import Group, GroupOwner
+from sentry.signals import issue_assigned, issue_deleted, issue_unassigned
+from sentry.utils import metrics
+
+logger = logging.getLogger(__name__)
+
+
+class Operation(Enum):
+ CREATED = "created"
+ UPDATED = "updated"
+ DELETED = "deleted"
+
+
+def _log_group_attributes_changed(
+ operation: Operation,
+ model_inducing_snapshot: str,
+ column_inducing_snapshot: Optional[str] = None,
+) -> None:
+ metrics.incr(
+ "group_attributes.changed",
+ tags={
+ "operation": operation.value,
+ "model": model_inducing_snapshot,
+ "column": column_inducing_snapshot,
+ },
+ )
+
+
+@receiver(
+ post_save, sender=Group, dispatch_uid="post_save_log_group_attributes_changed", weak=False
+)
+def post_save_log_group_attributes_changed(
+ instance, sender, created, update_fields, *args, **kwargs
+):
+ try:
+ if created:
+ _log_group_attributes_changed(Operation.CREATED, "group", None)
+ else:
+ # we have no guarantees update_fields is used everywhere save() is called
+ # we'll need to assume any of the attributes are updated in that case
+ attributes_updated = {"status", "substatus", "num_comments"}.intersection(
+ update_fields or ()
+ )
+ if attributes_updated:
+ _log_group_attributes_changed(
+ Operation.UPDATED, "group", "-".join(sorted(attributes_updated))
+ )
+ except Exception:
+ logger.error("failed to log group attributes after group post_save", exc_info=True)
+
+
+@issue_deleted.connect(weak=False)
+def on_issue_deleted_log_deleted(group, user, delete_type, **kwargs):
+ try:
+ _log_group_attributes_changed(Operation.DELETED, "group", "all")
+ except Exception:
+ logger.error("failed to log group attributes after group delete", exc_info=True)
+
+
+@issue_assigned.connect(weak=False)
+def on_issue_assigned_log_group_assignee_attributes_changed(project, group, user, **kwargs):
+ try:
+ _log_group_attributes_changed(Operation.UPDATED, "group_assignee", "all")
+ except Exception:
+ logger.error(
+ "failed to log group attributes after group_assignee assignment", exc_info=True
+ )
+
+
+@issue_unassigned.connect(weak=False)
+def on_issue_unassigned_log_group_assignee_attributes_changed(project, group, user, **kwargs):
+ try:
+ _log_group_attributes_changed(Operation.DELETED, "group_assignee", "all")
+ except Exception:
+ logger.error(
+ "failed to log group attributes after group_assignee unassignment", exc_info=True
+ )
+
+
+@receiver(
+ post_save, sender=GroupOwner, dispatch_uid="post_save_log_group_owner_changed", weak=False
+)
+def post_save_log_group_owner_changed(instance, sender, created, update_fields, *args, **kwargs):
+ try:
+ _log_group_attributes_changed(
+ Operation.CREATED if created else Operation.UPDATED, "group_owner", "all"
+ )
+ except Exception:
+ logger.error("failed to log group attributes after group_owner updated", exc_info=True)
+
+
+@receiver(
+ post_delete, sender=GroupOwner, dispatch_uid="post_delete_log_group_owner_changed", weak=False
+)
+def post_delete_log_group_owner_changed(instance, sender, created, update_fields, *args, **kwargs):
+ try:
+ _log_group_attributes_changed(Operation.DELETED, "group_owner", "all")
+ except Exception:
+ logger.error("failed to log group attributes after group_owner delete", exc_info=True)
diff --git a/src/sentry/models/activity.py b/src/sentry/models/activity.py
index 026f5e9043fcf4..97b8f9107188d5 100644
--- a/src/sentry/models/activity.py
+++ b/src/sentry/models/activity.py
@@ -6,6 +6,7 @@
from django.conf import settings
from django.db import models
from django.db.models import F
+from django.db.models.signals import post_save
from django.utils import timezone
from sentry.db.models import (
@@ -132,14 +133,24 @@ def save(self, *args, **kwargs):
# HACK: support Group.num_comments
if self.type == ActivityType.NOTE.value:
+ from sentry.models import Group
+
self.group.update(num_comments=F("num_comments") + 1)
+ post_save.send_robust(
+ sender=Group, instance=self.group, created=True, update_fields=["num_comments"]
+ )
def delete(self, *args, **kwargs):
super().delete(*args, **kwargs)
# HACK: support Group.num_comments
if self.type == ActivityType.NOTE.value:
+ from sentry.models import Group
+
self.group.update(num_comments=F("num_comments") - 1)
+ post_save.send_robust(
+ sender=Group, instance=self.group, created=True, update_fields=["num_comments"]
+ )
def send_notification(self):
activity.send_activity_notifications.delay(self.id)
diff --git a/src/sentry/models/groupassignee.py b/src/sentry/models/groupassignee.py
index b29799a968f650..9c0ec5d33ccf2b 100644
--- a/src/sentry/models/groupassignee.py
+++ b/src/sentry/models/groupassignee.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import logging
from typing import TYPE_CHECKING, Dict
from django.conf import settings
@@ -17,7 +18,7 @@
from sentry.models.grouphistory import GroupHistoryStatus, record_group_history
from sentry.models.groupowner import GroupOwner
from sentry.notifications.types import GroupSubscriptionReason
-from sentry.signals import issue_assigned
+from sentry.signals import issue_assigned, issue_unassigned
from sentry.types.activity import ActivityType
from sentry.utils import metrics
@@ -25,6 +26,8 @@
from sentry.models import ActorTuple, Group, Team, User
from sentry.services.hybrid_cloud.user import RpcUser
+logger = logging.getLogger(__name__)
+
class GroupAssigneeManager(BaseManager):
def assign(
@@ -134,6 +137,10 @@ def deassign(self, group: Group, acting_user: User | RpcUser | None = None) -> N
):
sync_group_assignee_outbound(group, None, assign=False)
+ issue_unassigned.send_robust(
+ project=group.project, group=group, user=acting_user, sender=self.__class__
+ )
+
@region_silo_only_model
class GroupAssignee(Model):
diff --git a/src/sentry/signals.py b/src/sentry/signals.py
index eb00380d05fa00..bc5c1ede0a9c02 100644
--- a/src/sentry/signals.py
+++ b/src/sentry/signals.py
@@ -159,6 +159,7 @@ def send_robust(self, sender, **named) -> List[Tuple[Receiver, Union[Exception,
# issues
issue_assigned = BetterSignal() # ["project", "group", "user"]
+issue_unassigned = BetterSignal() # ["project", "group", "user"]
issue_deleted = BetterSignal() # ["group", "user", "delete_type"]
# ["organization_id", "project", "group", "user", "resolution_type"]
issue_resolved = BetterSignal()
diff --git a/src/sentry/tasks/post_process.py b/src/sentry/tasks/post_process.py
index 84d4d92aee1777..c534836f339da0 100644
--- a/src/sentry/tasks/post_process.py
+++ b/src/sentry/tasks/post_process.py
@@ -7,6 +7,7 @@
import sentry_sdk
from django.conf import settings
+from django.db.models.signals import post_save
from django.utils import timezone
from google.api_core.exceptions import ServiceUnavailable
@@ -368,6 +369,12 @@ def handle_group_owners(project, group, issue_owners):
)
if new_group_owners:
GroupOwner.objects.bulk_create(new_group_owners)
+ for go in new_group_owners:
+ post_save.send_robust(
+ sender=GroupOwner,
+ instance=go,
+ created=True,
+ )
except UnableToAcquireLock:
pass
|
31cf45ff5a6ae96a4478af7e202d21180cd71d8b
|
2022-09-20 23:00:12
|
Scott Cooper
|
feat(issues): Collapse issue details tags (#39050)
| false
|
Collapse issue details tags (#39050)
|
feat
|
diff --git a/static/app/components/events/eventTags/index.tsx b/static/app/components/events/eventTags/index.tsx
index bf191990260fff..b1226b25196eea 100644
--- a/static/app/components/events/eventTags/index.tsx
+++ b/static/app/components/events/eventTags/index.tsx
@@ -1,5 +1,7 @@
+import styled from '@emotion/styled';
import {Location} from 'history';
+import ClippedBox from 'sentry/components/clippedBox';
import Pills from 'sentry/components/pills';
import {Organization} from 'sentry/types';
import {Event} from 'sentry/types/event';
@@ -31,18 +33,24 @@ export function EventTags({event, organization, projectId, location}: Props) {
const streamPath = `/organizations/${orgSlug}/issues/`;
return (
- <Pills>
- {event.tags.map((tag, index) => (
- <EventTagsPill
- key={!defined(tag.key) ? `tag-pill-${index}` : tag.key}
- tag={tag}
- projectId={projectId}
- organization={organization}
- query={generateQueryWithTag(location.query, tag)}
- streamPath={streamPath}
- meta={meta?.[index]}
- />
- ))}
- </Pills>
+ <StyledClippedBox clipHeight={150}>
+ <Pills>
+ {event.tags.map((tag, index) => (
+ <EventTagsPill
+ key={!defined(tag.key) ? `tag-pill-${index}` : tag.key}
+ tag={tag}
+ projectId={projectId}
+ organization={organization}
+ query={generateQueryWithTag(location.query, tag)}
+ streamPath={streamPath}
+ meta={meta?.[index]}
+ />
+ ))}
+ </Pills>
+ </StyledClippedBox>
);
}
+
+const StyledClippedBox = styled(ClippedBox)`
+ padding: 0;
+`;
|
c1f8632bd6972cbd0121f77ed980572b4c0bff88
|
2023-04-19 23:01:11
|
Richard Ortenberg
|
fix(monitors): Fixes multiple check-ins via upsert (#47528)
| false
|
Fixes multiple check-ins via upsert (#47528)
|
fix
|
diff --git a/src/sentry/monitors/endpoints/monitor_ingest_checkin_index.py b/src/sentry/monitors/endpoints/monitor_ingest_checkin_index.py
index b86e23ec77c421..3fd801251b35f6 100644
--- a/src/sentry/monitors/endpoints/monitor_ingest_checkin_index.py
+++ b/src/sentry/monitors/endpoints/monitor_ingest_checkin_index.py
@@ -104,7 +104,12 @@ def post(
checkin_validator = MonitorCheckInValidator(
data=request.data,
- context={"project": project, "request": request, "monitor_slug": monitor_slug},
+ context={
+ "project": project,
+ "request": request,
+ "monitor_slug": monitor_slug,
+ "monitor": monitor,
+ },
)
if not checkin_validator.is_valid():
return self.respond(checkin_validator.errors, status=400)
diff --git a/src/sentry/monitors/validators.py b/src/sentry/monitors/validators.py
index e772996cd9feb2..750729b176a9e6 100644
--- a/src/sentry/monitors/validators.py
+++ b/src/sentry/monitors/validators.py
@@ -223,6 +223,17 @@ def validate(self, attrs):
monitor_config = self.initial_data.get("monitor_config")
if monitor_config:
project = self.context["project"]
+ instance = {}
+ monitor = self.context.get("monitor", None)
+ if monitor:
+ instance = {
+ "name": monitor.name,
+ "slug": monitor.slug,
+ "status": monitor.status,
+ "type": monitor.type,
+ "config": monitor.config,
+ "project": project,
+ }
# Use context to complete the full monitor validator object
monitor_validator = MonitorValidator(
@@ -233,6 +244,7 @@ def validate(self, attrs):
"project": project.slug,
"config": monitor_config,
},
+ instance=instance,
context={
"organization": project.organization,
"access": self.context["request"].access,
diff --git a/tests/sentry/monitors/endpoints/test_monitor_ingest_checkin_index.py b/tests/sentry/monitors/endpoints/test_monitor_ingest_checkin_index.py
index 8858c460f42724..87105b89b63884 100644
--- a/tests/sentry/monitors/endpoints/test_monitor_ingest_checkin_index.py
+++ b/tests/sentry/monitors/endpoints/test_monitor_ingest_checkin_index.py
@@ -162,7 +162,7 @@ def test_deletion_in_progress(self):
resp = self.client.post(path, {"status": "error"}, **self.token_auth_headers)
assert resp.status_code == 404
- def test_monitor_creation_via_checkin(self):
+ def test_monitor_creation_and_update_via_checkin(self):
for i, path_func in enumerate(self._get_path_functions()):
slug = f"my-new-monitor-{i}"
path = path_func(slug)
@@ -182,23 +182,21 @@ def test_monitor_creation_via_checkin(self):
checkins = MonitorCheckIn.objects.filter(monitor=monitor)
assert len(checkins) == 1
- def test_monitor_update_via_checkin(self):
- for i, path_func in enumerate(self._get_path_functions()):
- monitor = self._create_monitor(slug=f"my-new-monitor-{i}")
- path = path_func(monitor.guid)
-
resp = self.client.post(
path,
{
"status": "ok",
- "monitor_config": {"schedule_type": "crontab", "schedule": "5 * * * *"},
+ "monitor_config": {"schedule_type": "crontab", "schedule": "10 * * * *"},
},
**self.dsn_auth_headers,
)
assert resp.status_code == 201, resp.content
monitor = Monitor.objects.get(guid=monitor.guid)
- assert monitor.config["schedule"] == "5 * * * *"
+ assert monitor.config["schedule"] == "10 * * * *"
+
+ checkins = MonitorCheckIn.objects.filter(monitor=monitor)
+ assert len(checkins) == 2
def test_monitor_creation_invalid_slug(self):
for i, path_func in enumerate(self._get_path_functions()):
|
b9dd3aadee35ca983d9c42eea37d1391a7441ec1
|
2022-12-01 20:40:30
|
edwardgou-sentry
|
feat(mobile-exp): adds some tracking for project and performance pages (#41870)
| false
|
adds some tracking for project and performance pages (#41870)
|
feat
|
diff --git a/static/app/views/performance/content.tsx b/static/app/views/performance/content.tsx
index 26d6320039d25b..26eebfb2e77a19 100644
--- a/static/app/views/performance/content.tsx
+++ b/static/app/views/performance/content.tsx
@@ -25,6 +25,7 @@ import usePrevious from 'sentry/utils/usePrevious';
import useProjects from 'sentry/utils/useProjects';
import withPageFilters from 'sentry/utils/withPageFilters';
+import {getLandingDisplayFromParam} from './landing/utils';
import {DEFAULT_STATS_PERIOD, generatePerformanceEventView} from './data';
import {PerformanceLanding} from './landing';
import {
@@ -97,6 +98,7 @@ function PerformanceContent({selection, location, demoMode, router}: Props) {
useRouteAnalyticsParams({
project_platforms: getSelectedProjectPlatforms(location, projects),
show_onboarding: onboardingProject !== undefined,
+ tab: getLandingDisplayFromParam(location)?.field,
});
useEffect(() => {
diff --git a/static/app/views/projectDetail/index.tsx b/static/app/views/projectDetail/index.tsx
index bdc0661d3ad3c2..7ff3721de14965 100644
--- a/static/app/views/projectDetail/index.tsx
+++ b/static/app/views/projectDetail/index.tsx
@@ -1,3 +1,5 @@
+import useRouteAnalyticsParams from 'sentry/utils/routeAnalytics/useRouteAnalyticsParams';
+import useProjects from 'sentry/utils/useProjects';
import withOrganization from 'sentry/utils/withOrganization';
import ProjectDetail from './projectDetail';
@@ -8,6 +10,16 @@ function ProjectDetailContainer(
'projects' | 'loadingProjects' | 'selection'
>
) {
+ const {projects} = useProjects();
+ const project = projects.find(p => p.slug === props.params.projectId);
+ useRouteAnalyticsParams(
+ project
+ ? {
+ project_id: project.id,
+ project_platform: project.platform,
+ }
+ : {}
+ );
return <ProjectDetail {...props} />;
}
|
7314f73f875c1db03741534076e9c0dea31a4f9c
|
2024-04-23 02:16:28
|
Stephen Cefali
|
feat(issue-platform): adds a partition key to issue platform producer (#69431)
| false
|
adds a partition key to issue platform producer (#69431)
|
feat
|
diff --git a/src/sentry/issues/producer.py b/src/sentry/issues/producer.py
index dd33b29e583572..ee846eafe8fed9 100644
--- a/src/sentry/issues/producer.py
+++ b/src/sentry/issues/producer.py
@@ -10,6 +10,7 @@
from confluent_kafka import KafkaException
from django.conf import settings
+from sentry import options
from sentry.conf.types.kafka_definition import Topic
from sentry.issues.issue_occurrence import IssueOccurrence
from sentry.issues.run import process_message
@@ -64,7 +65,14 @@ def produce_occurrence_to_kafka(
if payload_data is None:
return
- payload = KafkaPayload(None, json.dumps(payload_data).encode("utf-8"), [])
+ partition_key = None
+ if (
+ options.get("issue_platform.use_kafka_partition_key")
+ and occurrence
+ and occurrence.fingerprint
+ ):
+ partition_key = bytes(occurrence.fingerprint[0], "utf-8")
+ payload = KafkaPayload(partition_key, json.dumps(payload_data).encode("utf-8"), [])
if settings.SENTRY_EVENTSTREAM != "sentry.eventstream.kafka.KafkaEventStream":
# If we're not running Kafka then we're just in dev.
# Skip producing to Kafka and just process the message directly
diff --git a/src/sentry/options/defaults.py b/src/sentry/options/defaults.py
index 1d54ce51b04cb6..d352c230e851a3 100644
--- a/src/sentry/options/defaults.py
+++ b/src/sentry/options/defaults.py
@@ -2480,3 +2480,10 @@
default={"limit": 1000, "window": 300, "concurrent_limit": 15},
flags=FLAG_ALLOW_EMPTY | FLAG_AUTOMATOR_MODIFIABLE,
)
+
+register(
+ "issue_platform.use_kafka_partition_key",
+ type=Bool,
+ default=False,
+ flags=FLAG_PRIORITIZE_DISK | FLAG_AUTOMATOR_MODIFIABLE,
+)
diff --git a/tests/sentry/issues/test_producer.py b/tests/sentry/issues/test_producer.py
index e27a4fc2ef709e..a9253d785b112e 100644
--- a/tests/sentry/issues/test_producer.py
+++ b/tests/sentry/issues/test_producer.py
@@ -3,6 +3,9 @@
from unittest.mock import MagicMock, patch
import pytest
+from arroyo import Topic as ArroyoTopic
+from arroyo.backends.kafka import KafkaPayload
+from django.test import override_settings
from sentry.issues.ingest import process_occurrence_data
from sentry.issues.issue_occurrence import IssueOccurrence
@@ -14,9 +17,11 @@
from sentry.testutils.cases import TestCase
from sentry.testutils.helpers.datetime import before_now, iso_format
from sentry.testutils.helpers.features import apply_feature_flag_on_cls
+from sentry.testutils.helpers.options import override_options
from sentry.testutils.skips import requires_snuba
from sentry.types.activity import ActivityType
from sentry.types.group import GROUP_SUBSTATUS_TO_GROUP_HISTORY_STATUS, GroupSubStatus
+from sentry.utils import json
from sentry.utils.samples import load_data
from tests.sentry.issues.test_utils import OccurrenceTestMixin
@@ -84,6 +89,86 @@ def test_with_only_occurrence(self) -> None:
assert stored_occurrence
assert occurrence.event_id == stored_occurrence.event_id
+ @patch(
+ "sentry.issues.producer._prepare_occurrence_message", return_value={"mock_data": "great"}
+ )
+ @patch("sentry.issues.producer._occurrence_producer.produce")
+ @override_settings(SENTRY_EVENTSTREAM="sentry.eventstream.kafka.KafkaEventStream")
+ def test_payload_sent_to_kafka(self, mock_produce, mock_prepare_occurrence_message) -> None:
+ occurrence = self.build_occurrence(project_id=self.project.id)
+ produce_occurrence_to_kafka(
+ payload_type=PayloadType.OCCURRENCE,
+ occurrence=occurrence,
+ event_data={},
+ )
+ mock_produce.assert_called_once_with(
+ ArroyoTopic(name="ingest-occurrences"),
+ KafkaPayload(None, json.dumps({"mock_data": "great"}).encode("utf-8"), []),
+ )
+
+ @patch(
+ "sentry.issues.producer._prepare_occurrence_message", return_value={"mock_data": "great"}
+ )
+ @patch("sentry.issues.producer._occurrence_producer.produce")
+ @override_settings(SENTRY_EVENTSTREAM="sentry.eventstream.kafka.KafkaEventStream")
+ @override_options({"issue_platform.use_kafka_partition_key": True})
+ def test_payload_sent_to_kafka_with_partition_key(
+ self, mock_produce, mock_prepare_occurrence_message
+ ) -> None:
+ occurrence = self.build_occurrence(project_id=self.project.id, fingerprint=["group-1"])
+ produce_occurrence_to_kafka(
+ payload_type=PayloadType.OCCURRENCE,
+ occurrence=occurrence,
+ event_data={},
+ )
+ mock_produce.assert_called_once_with(
+ ArroyoTopic(name="ingest-occurrences"),
+ KafkaPayload(
+ bytes(occurrence.fingerprint[0], "utf-8"),
+ json.dumps({"mock_data": "great"}).encode("utf-8"),
+ [],
+ ),
+ )
+
+ @patch(
+ "sentry.issues.producer._prepare_occurrence_message", return_value={"mock_data": "great"}
+ )
+ @patch("sentry.issues.producer._occurrence_producer.produce")
+ @override_settings(SENTRY_EVENTSTREAM="sentry.eventstream.kafka.KafkaEventStream")
+ @override_options({"issue_platform.use_kafka_partition_key": True})
+ def test_payload_sent_to_kafka_with_partition_key_no_fingerprint(
+ self, mock_produce, mock_prepare_occurrence_message
+ ) -> None:
+ occurrence = self.build_occurrence(project_id=self.project.id, fingerprint=[])
+ produce_occurrence_to_kafka(
+ payload_type=PayloadType.OCCURRENCE,
+ occurrence=occurrence,
+ event_data={},
+ )
+ mock_produce.assert_called_once_with(
+ ArroyoTopic(name="ingest-occurrences"),
+ KafkaPayload(None, json.dumps({"mock_data": "great"}).encode("utf-8"), []),
+ )
+
+ @patch(
+ "sentry.issues.producer._prepare_occurrence_message", return_value={"mock_data": "great"}
+ )
+ @patch("sentry.issues.producer._occurrence_producer.produce")
+ @override_settings(SENTRY_EVENTSTREAM="sentry.eventstream.kafka.KafkaEventStream")
+ @override_options({"issue_platform.use_kafka_partition_key": True})
+ def test_payload_sent_to_kafka_with_partition_key_no_occurrence(
+ self, mock_produce, mock_prepare_occurrence_message
+ ) -> None:
+ produce_occurrence_to_kafka(
+ payload_type=PayloadType.OCCURRENCE,
+ occurrence=None,
+ event_data={},
+ )
+ mock_produce.assert_called_once_with(
+ ArroyoTopic(name="ingest-occurrences"),
+ KafkaPayload(None, json.dumps({"mock_data": "great"}).encode("utf-8"), []),
+ )
+
class TestProduceOccurrenceForStatusChange(TestCase, OccurrenceTestMixin):
def setUp(self):
|
66c88a0295c16a0861530b456929524993482e57
|
2021-03-19 04:39:42
|
Evan Purkhiser
|
fix(dev): Serve media directly out of uploaded files in dev (#24553)
| false
|
Serve media directly out of uploaded files in dev (#24553)
|
fix
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index 487b89b6e75114..f5d73bad24f577 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -384,7 +384,7 @@ def env(key, default="", type=None):
ASSET_VERSION = 0
# setup a default media root to somewhere useless
-MEDIA_ROOT = "/tmp/sentry-files/media"
+MEDIA_ROOT = "/tmp/sentry-files"
MEDIA_URL = "_media/"
LOCALE_PATHS = (os.path.join(PROJECT_ROOT, "locale"),)
|
1a1cb1f52bdd2537b826dc243b41fb21c6e604ee
|
2023-08-07 18:46:48
|
Radu Woinaroski
|
feat: Use organization metrics estimation endpoint (#54171)
| false
|
Use organization metrics estimation endpoint (#54171)
|
feat
|
diff --git a/static/app/components/charts/onDemandMetricRequest.spec.tsx b/static/app/components/charts/onDemandMetricRequest.spec.tsx
index e19af849156c35..8e1236f305a33d 100644
--- a/static/app/components/charts/onDemandMetricRequest.spec.tsx
+++ b/static/app/components/charts/onDemandMetricRequest.spec.tsx
@@ -5,14 +5,6 @@ import {OnDemandMetricRequest} from 'sentry/components/charts/onDemandMetricRequ
const SAMPLE_RATE = 0.5;
-const COUNT_OBJ = {
- count: 123,
-};
-
-const COUNT_OBJ_SCALED = {
- count: COUNT_OBJ.count / SAMPLE_RATE,
-};
-
jest.mock('sentry/actionCreators/events', () => ({
doEventsRequest: jest.fn(),
}));
@@ -58,14 +50,9 @@ describe('OnDemandMetricRequest', function () {
expect(mock).toHaveBeenLastCalledWith(
expect.objectContaining({
loading: false,
- seriesAdditionalInfo: {
- current: {
- isExtrapolatedData: true,
- isMetricsData: false,
- },
- },
timeseriesData: [
{
+ // isExtrapolatedData: true,
seriesName: expect.anything(),
data: [],
},
@@ -75,7 +62,7 @@ describe('OnDemandMetricRequest', function () {
)
);
- expect(doEventsRequest).toHaveBeenCalledTimes(2);
+ expect(doEventsRequest).toHaveBeenCalled();
});
it('makes a new request if projects prop changes', function () {
@@ -95,7 +82,6 @@ describe('OnDemandMetricRequest', function () {
expect.anything(),
expect.objectContaining({
project: [123],
- useOnDemandMetrics: true,
})
);
});
@@ -117,7 +103,6 @@ describe('OnDemandMetricRequest', function () {
expect.anything(),
expect.objectContaining({
environment: ['dev'],
- useOnDemandMetrics: true,
})
);
});
@@ -139,67 +124,8 @@ describe('OnDemandMetricRequest', function () {
expect.anything(),
expect.objectContaining({
period: '7d',
- useOnDemandMetrics: true,
})
);
});
});
-
- describe('transforms', function () {
- beforeEach(function () {
- (doEventsRequest as jest.Mock).mockClear();
- });
-
- it('applies sample rate to indexed if there is no metrics data`', async function () {
- (doEventsRequest as jest.Mock)
- .mockImplementation(() =>
- Promise.resolve({
- isMetricsData: true,
- data: [],
- })
- )
- .mockImplementation(() =>
- Promise.resolve({
- isMetricsData: false,
- data: [[new Date(), [COUNT_OBJ]]],
- })
- );
-
- render(<OnDemandMetricRequest {...DEFAULTS}>{mock}</OnDemandMetricRequest>);
-
- expect(mock).toHaveBeenNthCalledWith(
- 1,
- expect.objectContaining({
- loading: true,
- })
- );
-
- await waitFor(() =>
- expect(mock).toHaveBeenLastCalledWith(
- expect.objectContaining({
- loading: false,
- seriesAdditionalInfo: {
- current: {
- isExtrapolatedData: true,
- isMetricsData: false,
- },
- },
- timeseriesData: [
- {
- seriesName: expect.anything(),
- data: [
- expect.objectContaining({
- name: expect.any(Number),
- value: COUNT_OBJ_SCALED.count,
- }),
- ],
- },
- ],
- })
- )
- );
-
- expect(doEventsRequest).toHaveBeenCalledTimes(2);
- });
- });
});
diff --git a/static/app/components/charts/onDemandMetricRequest.tsx b/static/app/components/charts/onDemandMetricRequest.tsx
index 30a032efe6dcfe..6da1869594ae79 100644
--- a/static/app/components/charts/onDemandMetricRequest.tsx
+++ b/static/app/components/charts/onDemandMetricRequest.tsx
@@ -3,57 +3,20 @@ import {addErrorMessage} from 'sentry/actionCreators/indicator';
import EventsRequest from 'sentry/components/charts/eventsRequest';
import {t} from 'sentry/locale';
import {EventsStats, MultiSeriesEventsStats} from 'sentry/types';
-import {DiscoverDatasets} from 'sentry/utils/discover/types';
-
-function numOfEvents(timeseriesData) {
- return timeseriesData.data.reduce((acc, item) => {
- const count = item[1][0].count;
- return acc + count;
- }, 0);
-}
-
-function applySampleRate(timeseriesData, sampleRate = 1) {
- const scaledData = timeseriesData.data.map(([timestamp, value]) => {
- return [timestamp, value.map(item => ({count: Math.round(item.count / sampleRate)}))];
- });
-
- return {
- ...timeseriesData,
- isExtrapolatedData: true,
- isMetricsData: false,
- data: scaledData,
- };
-}
export class OnDemandMetricRequest extends EventsRequest {
- fetchMetricsData = async () => {
- const {api, ...props} = this.props;
-
- try {
- const timeseriesData = await doEventsRequest(api, {
- ...props,
- useOnDemandMetrics: true,
- });
-
- return timeseriesData;
- } catch {
- return {
- data: [],
- isMetricsData: false,
- };
- }
- };
-
- fetchIndexedData = async () => {
- const {api, sampleRate, ...props} = this.props;
-
- const timeseriesData = await doEventsRequest(api, {
+ fetchExtrapolatedData = async (): Promise<EventsStats> => {
+ const {api, organization, ...props} = this.props;
+ const retVal = await doEventsRequest(api, {
...props,
- useOnDemandMetrics: false,
- queryExtras: {dataset: DiscoverDatasets.DISCOVER},
+ organization,
+ generatePathname: () =>
+ `/organizations/${organization.slug}/metrics-estimation-stats/`,
});
-
- return applySampleRate(timeseriesData, sampleRate);
+ return {
+ ...retVal,
+ isExtrapolatedData: true,
+ } as EventsStats;
};
fetchData = async () => {
@@ -83,14 +46,7 @@ export class OnDemandMetricRequest extends EventsRequest {
try {
api.clear();
- timeseriesData = await this.fetchMetricsData();
-
- const fallbackToIndexed =
- !timeseriesData.isMetricsData || numOfEvents(timeseriesData) === 0;
-
- if (fallbackToIndexed) {
- timeseriesData = await this.fetchIndexedData();
- }
+ timeseriesData = await this.fetchExtrapolatedData();
} catch (resp) {
if (resp && resp.responseJSON && resp.responseJSON.detail) {
errorMessage = resp.responseJSON.detail;
diff --git a/static/app/views/alerts/rules/metric/ruleForm.spec.tsx b/static/app/views/alerts/rules/metric/ruleForm.spec.tsx
index 8ca1345261a76a..aaa01349f6e009 100644
--- a/static/app/views/alerts/rules/metric/ruleForm.spec.tsx
+++ b/static/app/views/alerts/rules/metric/ruleForm.spec.tsx
@@ -74,6 +74,10 @@ describe('Incident Rules Form', () => {
},
],
});
+ MockApiClient.addMockResponse({
+ url: '/organizations/org-slug/metrics-estimation-stats/',
+ body: TestStubs.EventsStats(),
+ });
});
afterEach(() => {
diff --git a/static/app/views/alerts/rules/metric/triggers/chart/index.tsx b/static/app/views/alerts/rules/metric/triggers/chart/index.tsx
index 1b0d8e09e6d570..dd3b9c3927d063 100644
--- a/static/app/views/alerts/rules/metric/triggers/chart/index.tsx
+++ b/static/app/views/alerts/rules/metric/triggers/chart/index.tsx
@@ -174,9 +174,6 @@ class TriggersChart extends PureComponent<Props, State> {
!isEqual(prevState.statsPeriod, statsPeriod))
) {
this.fetchTotalCount();
- if (this.props.isOnDemandMetricAlert) {
- this.fetchSampleRate();
- }
}
}
@@ -214,18 +211,6 @@ class TriggersChart extends PureComponent<Props, State> {
);
}
- async fetchSampleRate() {
- const {api, organization, projects} = this.props;
- try {
- const {sampleRate} = await api.requestPromise(
- `/api/0/projects/${organization.slug}/${projects[0].slug}/dynamic-sampling/rate/`
- );
- this.setState({sampleRate});
- } catch {
- this.setState({sampleRate: 1});
- }
- }
-
async fetchTotalCount() {
const {
api,
|
137781525c3fe65c1ced3f3c1e423dabf73f149a
|
2021-02-16 22:37:18
|
Alberto Leal
|
fix: Various fixes for Dashboards (#23864)
| false
|
Various fixes for Dashboards (#23864)
|
fix
|
diff --git a/src/sentry/static/sentry/app/views/dashboardsV2/sortableWidget.tsx b/src/sentry/static/sentry/app/views/dashboardsV2/sortableWidget.tsx
index 8a9b67137c7ec6..29e399e8a9ceaf 100644
--- a/src/sentry/static/sentry/app/views/dashboardsV2/sortableWidget.tsx
+++ b/src/sentry/static/sentry/app/views/dashboardsV2/sortableWidget.tsx
@@ -8,12 +8,12 @@ import {Widget} from './types';
import WidgetCard from './widgetCard';
import WidgetWrapper from './widgetWrapper';
-const initialStyles = {
+const initialStyles: React.ComponentProps<typeof WidgetWrapper>['animate'] = {
x: 0,
y: 0,
scaleX: 1,
scaleY: 1,
- zIndex: 0,
+ zIndex: 'auto',
};
type Props = {
@@ -69,7 +69,7 @@ function SortableWidget(props: Props) {
y: transform.y,
scaleX: transform?.scaleX && transform.scaleX <= 1 ? transform.scaleX : 1,
scaleY: transform?.scaleY && transform.scaleY <= 1 ? transform.scaleY : 1,
- zIndex: currentWidgetDragging ? theme.zIndex.modal : 0,
+ zIndex: currentWidgetDragging ? theme.zIndex.modal : 'auto',
}
: initialStyles
}
diff --git a/src/sentry/static/sentry/app/views/dashboardsV2/widgetCard.tsx b/src/sentry/static/sentry/app/views/dashboardsV2/widgetCard.tsx
index f9bdea5c10a8ee..7dbe27e49d842f 100644
--- a/src/sentry/static/sentry/app/views/dashboardsV2/widgetCard.tsx
+++ b/src/sentry/static/sentry/app/views/dashboardsV2/widgetCard.tsx
@@ -168,7 +168,6 @@ const StyledPanel = styled(Panel, {
/* If a panel overflows due to a long title stretch its grid sibling */
height: 100%;
min-height: 96px;
- overflow: hidden;
`;
const ToolbarPanel = styled('div')`
@@ -185,6 +184,7 @@ const ToolbarPanel = styled('div')`
align-items: flex-start;
background-color: rgba(255, 255, 255, 0.7);
+ border-radius: ${p => p.theme.borderRadius};
`;
const IconContainer = styled('div')`
diff --git a/src/sentry/static/sentry/app/views/dashboardsV2/widgetCardChart.tsx b/src/sentry/static/sentry/app/views/dashboardsV2/widgetCardChart.tsx
index 36762bdd0464dc..edc1ce1d53e442 100644
--- a/src/sentry/static/sentry/app/views/dashboardsV2/widgetCardChart.tsx
+++ b/src/sentry/static/sentry/app/views/dashboardsV2/widgetCardChart.tsx
@@ -367,6 +367,8 @@ const StyledSimpleTableChart = styled(SimpleTableChart)`
/* align with other card charts */
height: 216px;
margin-top: ${space(1.5)};
+ border-bottom-left-radius: ${p => p.theme.borderRadius};
+ border-bottom-right-radius: ${p => p.theme.borderRadius};
`;
export default WidgetCardChart;
|
7560f88b69daead48899e655c99e4169d7acf67f
|
2019-03-18 23:44:24
|
Markus Unterwaditzer
|
fix: Add sentry tag to renormalized events (#12434)
| false
|
Add sentry tag to renormalized events (#12434)
|
fix
|
diff --git a/src/sentry/models/event.py b/src/sentry/models/event.py
index 6755589206fe67..79b4d3008d6722 100644
--- a/src/sentry/models/event.py
+++ b/src/sentry/models/event.py
@@ -39,6 +39,7 @@
from sentry.utils.canonical import CanonicalKeyDict, CanonicalKeyView
from sentry.utils.safe import get_path
from sentry.utils.strings import truncatechars
+from sentry.utils.sdk import configure_scope
def _should_skip_to_python(event_data):
@@ -62,6 +63,10 @@ def __init__(self, data, **kwargs):
metrics.incr('rust.renormalized',
tags={'value': rust_renormalized})
+
+ with configure_scope() as scope:
+ scope.set_tag("rust.renormalized", rust_renormalized)
+
CanonicalKeyDict.__init__(self, data, **kwargs)
|
24148cba43a5614f911da80fd06a05072d66cf7a
|
2024-07-10 02:25:11
|
Tony Xiao
|
ref(trace-explorer): Split traces hooks into separate files (#74036)
| false
|
Split traces hooks into separate files (#74036)
|
ref
|
diff --git a/static/app/views/traces/content.tsx b/static/app/views/traces/content.tsx
index f280a9c39aa374..56b0ba07b80845 100644
--- a/static/app/views/traces/content.tsx
+++ b/static/app/views/traces/content.tsx
@@ -1,4 +1,4 @@
-import {Fragment, useCallback, useEffect, useMemo, useState} from 'react';
+import {Fragment, useCallback, useMemo, useState} from 'react';
import {useTheme} from '@emotion/react';
import styled from '@emotion/styled';
import debounce from 'lodash/debounce';
@@ -15,7 +15,6 @@ import LoadingIndicator from 'sentry/components/loadingIndicator';
import {DatePageFilter} from 'sentry/components/organizations/datePageFilter';
import {EnvironmentPageFilter} from 'sentry/components/organizations/environmentPageFilter';
import PageFilterBar from 'sentry/components/organizations/pageFilterBar';
-import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
import {ProjectPageFilter} from 'sentry/components/organizations/projectPageFilter';
import Panel from 'sentry/components/panels/panel';
import PanelHeader from 'sentry/components/panels/panelHeader';
@@ -27,7 +26,6 @@ import {IconClose} from 'sentry/icons/iconClose';
import {IconWarning} from 'sentry/icons/iconWarning';
import {t, tct} from 'sentry/locale';
import {space} from 'sentry/styles/space';
-import type {PageFilters} from 'sentry/types/core';
import type {MetricAggregation, MRI} from 'sentry/types/metrics';
import type {Organization} from 'sentry/types/organization';
import {defined} from 'sentry/utils';
@@ -35,17 +33,20 @@ import {trackAnalytics} from 'sentry/utils/analytics';
import {browserHistory} from 'sentry/utils/browserHistory';
import {getUtcDateString} from 'sentry/utils/dates';
import {getFormattedMQL} from 'sentry/utils/metrics';
-import {useApiQuery} from 'sentry/utils/queryClient';
-import {decodeInteger, decodeList, decodeScalar} from 'sentry/utils/queryString';
+import {decodeInteger, decodeList} from 'sentry/utils/queryString';
import {useLocation} from 'sentry/utils/useLocation';
import useOrganization from 'sentry/utils/useOrganization';
import usePageFilters from 'sentry/utils/usePageFilters';
import useProjects from 'sentry/utils/useProjects';
import * as ModuleLayout from 'sentry/views/insights/common/components/moduleLayout';
+import {usePageParams} from './hooks/usePageParams';
+import type {TraceResult} from './hooks/useTraces';
+import {useTraces} from './hooks/useTraces';
+import type {SpanResult} from './hooks/useTraceSpans';
+import {useTraceSpans} from './hooks/useTraceSpans';
import {type Field, FIELDS, SORTS} from './data';
import {
- BREAKDOWN_SLICES,
Description,
ProjectBadgeWrapper,
ProjectsRenderer,
@@ -72,27 +73,6 @@ const SPAN_PROPS_DOCS_URL =
'https://docs.sentry.io/concepts/search/searchable-properties/spans/';
const ONE_MINUTE = 60 * 1000; // in milliseconds
-function usePageParams(location) {
- const queries = useMemo(() => {
- return decodeList(location.query.query);
- }, [location.query.query]);
-
- const metricsMax = decodeScalar(location.query.metricsMax);
- const metricsMin = decodeScalar(location.query.metricsMin);
- const metricsOp = decodeScalar(location.query.metricsOp);
- const metricsQuery = decodeScalar(location.query.metricsQuery);
- const mri = decodeScalar(location.query.mri);
-
- return {
- queries,
- metricsMax,
- metricsMin,
- metricsOp,
- metricsQuery,
- mri,
- };
-}
-
export function Content() {
const location = useLocation();
@@ -592,227 +572,6 @@ function SpanRow({
);
}
-export type SpanResult<F extends string> = Record<F, any>;
-
-export interface TraceResult {
- breakdowns: TraceBreakdownResult[];
- duration: number;
- end: number;
- matchingSpans: number;
- name: string | null;
- numErrors: number;
- numOccurrences: number;
- numSpans: number;
- project: string | null;
- slices: number;
- start: number;
- trace: string;
-}
-
-interface TraceBreakdownBase {
- duration: number; // Contains the accurate duration for display. Start and end may be quantized.
- end: number;
- opCategory: string | null;
- sdkName: string | null;
- sliceEnd: number;
- sliceStart: number;
- sliceWidth: number;
- start: number;
-}
-
-type TraceBreakdownProject = TraceBreakdownBase & {
- kind: 'project';
- project: string;
-};
-
-type TraceBreakdownMissing = TraceBreakdownBase & {
- kind: 'missing';
- project: null;
-};
-
-export type TraceBreakdownResult = TraceBreakdownProject | TraceBreakdownMissing;
-
-interface TraceResults {
- data: TraceResult[];
- meta: any;
-}
-
-interface UseTracesOptions {
- datetime?: PageFilters['datetime'];
- enabled?: boolean;
- limit?: number;
- metricsMax?: string;
- metricsMin?: string;
- metricsOp?: string;
- metricsQuery?: string;
- mri?: string;
- query?: string | string[];
- sort?: '-timestamp';
-}
-
-function useTraces({
- datetime,
- enabled,
- limit,
- mri,
- metricsMax,
- metricsMin,
- metricsOp,
- metricsQuery,
- query,
- sort,
-}: UseTracesOptions) {
- const organization = useOrganization();
- const {projects} = useProjects();
- const {selection} = usePageFilters();
-
- const path = `/organizations/${organization.slug}/traces/`;
-
- const endpointOptions = {
- query: {
- project: selection.projects,
- environment: selection.environments,
- ...(datetime ?? normalizeDateTimeParams(selection.datetime)),
- query,
- sort,
- per_page: limit,
- breakdownSlices: BREAKDOWN_SLICES,
- mri,
- metricsMax,
- metricsMin,
- metricsOp,
- metricsQuery,
- },
- };
- const serializedEndpointOptions = JSON.stringify(endpointOptions);
-
- let queries: string[] = [];
- if (Array.isArray(query)) {
- queries = query;
- } else if (query !== undefined) {
- queries = [query];
- }
-
- useEffect(() => {
- trackAnalytics('trace_explorer.search_request', {
- organization,
- queries,
- });
- // `queries` is already included as a dep in serializedEndpointOptions
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [serializedEndpointOptions, organization]);
-
- const result = useApiQuery<TraceResults>([path, endpointOptions], {
- staleTime: 0,
- refetchOnWindowFocus: false,
- retry: false,
- enabled,
- });
-
- useEffect(() => {
- if (result.status === 'success') {
- const project_slugs = [...new Set(result.data.data.map(trace => trace.project))];
- const project_platforms = projects
- .filter(p => project_slugs.includes(p.slug))
- .map(p => p.platform ?? '');
-
- trackAnalytics('trace_explorer.search_success', {
- organization,
- queries,
- has_data: result.data.data.length > 0,
- num_traces: result.data.data.length,
- num_missing_trace_root: result.data.data.filter(trace => trace.name === null)
- .length,
- project_platforms,
- });
- } else if (result.status === 'error') {
- const response = result.error.responseJSON;
- const error =
- typeof response?.detail === 'string'
- ? response?.detail
- : response?.detail?.message;
- trackAnalytics('trace_explorer.search_failure', {
- organization,
- queries,
- error: error ?? '',
- });
- }
- // result.status is tied to result.data. No need to explicitly
- // include result.data as an additional dep.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [serializedEndpointOptions, result.status, organization]);
-
- return result;
-}
-
-interface SpanResults<F extends string> {
- data: SpanResult<F>[];
- meta: any;
-}
-
-interface UseTraceSpansOptions<F extends string> {
- fields: F[];
- trace: TraceResult;
- datetime?: PageFilters['datetime'];
- enabled?: boolean;
- limit?: number;
- metricsMax?: string;
- metricsMin?: string;
- metricsOp?: string;
- metricsQuery?: string;
- mri?: string;
- query?: string | string[];
- sort?: string[];
-}
-
-function useTraceSpans<F extends string>({
- fields,
- trace,
- datetime,
- enabled,
- limit,
- mri,
- metricsMax,
- metricsMin,
- metricsOp,
- metricsQuery,
- query,
- sort,
-}: UseTraceSpansOptions<F>) {
- const organization = useOrganization();
- const {selection} = usePageFilters();
-
- const path = `/organizations/${organization.slug}/trace/${trace.trace}/spans/`;
-
- const endpointOptions = {
- query: {
- project: selection.projects,
- environment: selection.environments,
- ...(datetime ?? normalizeDateTimeParams(selection.datetime)),
- field: fields,
- query,
- sort,
- per_page: limit,
- breakdownSlices: BREAKDOWN_SLICES,
- maxSpansPerTrace: 10,
- mri,
- metricsMax,
- metricsMin,
- metricsOp,
- metricsQuery,
- },
- };
-
- const result = useApiQuery<SpanResults<F>>([path, endpointOptions], {
- staleTime: 0,
- refetchOnWindowFocus: false,
- retry: false,
- enabled,
- });
-
- return result;
-}
-
const LayoutMain = styled(Layout.Main)`
display: flex;
flex-direction: column;
diff --git a/static/app/views/traces/fieldRenderers.spec.tsx b/static/app/views/traces/fieldRenderers.spec.tsx
index e470a91693f65a..782bc1f84c8568 100644
--- a/static/app/views/traces/fieldRenderers.spec.tsx
+++ b/static/app/views/traces/fieldRenderers.spec.tsx
@@ -6,7 +6,6 @@ import {act, fireEvent, render, screen} from 'sentry-test/reactTestingLibrary';
import ProjectsStore from 'sentry/stores/projectsStore';
import type {Project} from 'sentry/types/project';
-import type {SpanResult} from 'sentry/views/traces/content';
import type {Field} from 'sentry/views/traces/data';
import {
ProjectRenderer,
@@ -17,6 +16,7 @@ import {
TraceIssuesRenderer,
TransactionRenderer,
} from 'sentry/views/traces/fieldRenderers';
+import type {SpanResult} from 'sentry/views/traces/hooks/useTraceSpans';
describe('Renderers', function () {
let context;
diff --git a/static/app/views/traces/fieldRenderers.tsx b/static/app/views/traces/fieldRenderers.tsx
index 3e2301919d43d0..643a456a66bf40 100644
--- a/static/app/views/traces/fieldRenderers.tsx
+++ b/static/app/views/traces/fieldRenderers.tsx
@@ -29,7 +29,9 @@ import {transactionSummaryRouteWithQuery} from 'sentry/views/performance/transac
import {TraceViewSources} from '../performance/newTraceDetails/traceMetadataHeader';
-import type {SpanResult, TraceResult} from './content';
+import type {TraceResult} from './hooks/useTraces';
+import {BREAKDOWN_SLICES} from './hooks/useTraces';
+import type {SpanResult} from './hooks/useTraceSpans';
import type {Field} from './data';
import {getShortenedSdkName, getStylingSliceName} from './utils';
@@ -281,7 +283,6 @@ export function TraceBreakdownRenderer({
}
const BREAKDOWN_SIZE_PX = 200;
-export const BREAKDOWN_SLICES = 40;
/**
* This renders slices in two different ways;
diff --git a/static/app/views/traces/hooks/usePageParams.spec.tsx b/static/app/views/traces/hooks/usePageParams.spec.tsx
new file mode 100644
index 00000000000000..a1766fab548c92
--- /dev/null
+++ b/static/app/views/traces/hooks/usePageParams.spec.tsx
@@ -0,0 +1,56 @@
+import {renderHook} from 'sentry-test/reactTestingLibrary';
+
+import {usePageParams} from 'sentry/views/traces/hooks/usePageParams';
+
+describe('usePageParams', function () {
+ it('decodes no queries on page', function () {
+ const location = {query: {}};
+ const {result} = renderHook(() => usePageParams(location), {
+ initialProps: {location},
+ });
+
+ expect(result.current.queries).toEqual([]);
+ });
+
+ it('decodes single query on page', function () {
+ const location = {query: {query: 'query1'}};
+ const {result} = renderHook(() => usePageParams(location), {
+ initialProps: {location},
+ });
+
+ expect(result.current.queries).toEqual(['query1']);
+ });
+
+ it('decodes multiple queries on page', function () {
+ const location = {query: {query: ['query1', 'query2', 'query3']}};
+ const {result} = renderHook(() => usePageParams(location), {
+ initialProps: {location},
+ });
+
+ expect(result.current.queries).toEqual(['query1', 'query2', 'query3']);
+ });
+
+ it('decodes metrics related params', function () {
+ const location = {
+ query: {
+ metricsMax: '456',
+ metricsMin: '123',
+ metricsOp: 'sum',
+ metricsQuery: 'foo:bar',
+ mri: 'd:transactions/duration@millisecond',
+ },
+ };
+ const {result} = renderHook(() => usePageParams(location), {
+ initialProps: {location},
+ });
+
+ expect(result.current).toEqual({
+ queries: [],
+ metricsMax: '456',
+ metricsMin: '123',
+ metricsOp: 'sum',
+ metricsQuery: 'foo:bar',
+ mri: 'd:transactions/duration@millisecond',
+ });
+ });
+});
diff --git a/static/app/views/traces/hooks/usePageParams.tsx b/static/app/views/traces/hooks/usePageParams.tsx
new file mode 100644
index 00000000000000..36d6671ba23b80
--- /dev/null
+++ b/static/app/views/traces/hooks/usePageParams.tsx
@@ -0,0 +1,24 @@
+import {useMemo} from 'react';
+
+import {decodeList, decodeScalar} from 'sentry/utils/queryString';
+
+export function usePageParams(location) {
+ const queries = useMemo(() => {
+ return decodeList(location.query.query);
+ }, [location.query.query]);
+
+ const metricsMax = decodeScalar(location.query.metricsMax);
+ const metricsMin = decodeScalar(location.query.metricsMin);
+ const metricsOp = decodeScalar(location.query.metricsOp);
+ const metricsQuery = decodeScalar(location.query.metricsQuery);
+ const mri = decodeScalar(location.query.mri);
+
+ return {
+ queries,
+ metricsMax,
+ metricsMin,
+ metricsOp,
+ metricsQuery,
+ mri,
+ };
+}
diff --git a/static/app/views/traces/hooks/useTraceSpans.spec.tsx b/static/app/views/traces/hooks/useTraceSpans.spec.tsx
new file mode 100644
index 00000000000000..d077ea20835aa6
--- /dev/null
+++ b/static/app/views/traces/hooks/useTraceSpans.spec.tsx
@@ -0,0 +1,134 @@
+import {OrganizationFixture} from 'sentry-fixture/organization';
+import {ProjectFixture} from 'sentry-fixture/project';
+
+import {initializeOrg} from 'sentry-test/initializeOrg';
+import {makeTestQueryClient} from 'sentry-test/queryClient';
+import {act, renderHook, waitFor} from 'sentry-test/reactTestingLibrary';
+
+import PageFiltersStore from 'sentry/stores/pageFiltersStore';
+import ProjectsStore from 'sentry/stores/projectsStore';
+import type {Organization} from 'sentry/types';
+import {QueryClientProvider} from 'sentry/utils/queryClient';
+import {OrganizationContext} from 'sentry/views/organizationContext';
+import type {TraceResult} from 'sentry/views/traces/hooks/useTraces';
+import type {SpanResults} from 'sentry/views/traces/hooks/useTraceSpans';
+import {useTraceSpans} from 'sentry/views/traces/hooks/useTraceSpans';
+
+function createTraceResult(trace?: Partial<TraceResult>): TraceResult {
+ return {
+ breakdowns: [],
+ duration: 333,
+ end: 456,
+ matchingSpans: 1,
+ name: 'name',
+ numErrors: 1,
+ numOccurrences: 1,
+ numSpans: 2,
+ project: 'project',
+ slices: 10,
+ start: 123,
+ trace: '00000000000000000000000000000000',
+ ...trace,
+ };
+}
+
+function createWrapper(organization: Organization) {
+ return function ({children}: {children?: React.ReactNode}) {
+ return (
+ <QueryClientProvider client={makeTestQueryClient()}>
+ <OrganizationContext.Provider value={organization}>
+ {children}
+ </OrganizationContext.Provider>
+ </QueryClientProvider>
+ );
+ };
+}
+
+describe('useTraceSpans', function () {
+ const project = ProjectFixture();
+ const organization = OrganizationFixture();
+ const context = initializeOrg({
+ organization,
+ projects: [project],
+ router: {
+ location: {
+ pathname: '/organizations/org-slug/issues/',
+ query: {project: project.id},
+ },
+ params: {},
+ },
+ });
+
+ beforeEach(function () {
+ MockApiClient.clearMockResponses();
+ act(() => {
+ ProjectsStore.loadInitialData([project]);
+ PageFiltersStore.init();
+ PageFiltersStore.onInitializeUrlState(
+ {
+ projects: [project].map(p => parseInt(p.id, 10)),
+ environments: [],
+ datetime: {
+ period: '3d',
+ start: null,
+ end: null,
+ utc: null,
+ },
+ },
+ new Set()
+ );
+ });
+ });
+
+ it('handles querying the api', async function () {
+ const trace = createTraceResult();
+
+ const body: SpanResults<'id'> = {
+ data: [{id: '0000000000000000'}],
+ meta: {},
+ };
+
+ MockApiClient.addMockResponse({
+ url: `/organizations/${organization.slug}/trace/${trace.trace}/spans/`,
+ body,
+ match: [
+ MockApiClient.matchQuery({
+ project: [parseInt(project.id, 10)],
+ field: ['id'],
+ maxSpansPerTrace: 10,
+ query: 'foo:bar',
+ period: '3d',
+ mri: 'd:transactions/duration@millisecond',
+ metricsMax: '456',
+ metricsMin: '123',
+ metricsOp: 'sum',
+ metricsQuery: 'foo:bar',
+ }),
+ ],
+ });
+
+ const {result} = renderHook(useTraceSpans, {
+ ...context,
+ wrapper: createWrapper(organization),
+ initialProps: {
+ fields: ['id'],
+ trace,
+ datetime: {
+ end: null,
+ period: '3d',
+ start: null,
+ utc: null,
+ },
+ query: 'foo:bar',
+ mri: 'd:transactions/duration@millisecond',
+ metricsMax: '456',
+ metricsMin: '123',
+ metricsOp: 'sum',
+ metricsQuery: 'foo:bar',
+ },
+ });
+
+ await waitFor(() => result.current.isSuccess);
+ expect(result.current.data).toEqual(body);
+ });
+});
diff --git a/static/app/views/traces/hooks/useTraceSpans.tsx b/static/app/views/traces/hooks/useTraceSpans.tsx
new file mode 100644
index 00000000000000..411a17cd44b0d4
--- /dev/null
+++ b/static/app/views/traces/hooks/useTraceSpans.tsx
@@ -0,0 +1,76 @@
+import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
+import type {PageFilters} from 'sentry/types/core';
+import {useApiQuery} from 'sentry/utils/queryClient';
+import useOrganization from 'sentry/utils/useOrganization';
+import usePageFilters from 'sentry/utils/usePageFilters';
+
+import type {TraceResult} from './useTraces';
+
+export type SpanResult<F extends string> = Record<F, any>;
+
+export interface SpanResults<F extends string> {
+ data: SpanResult<F>[];
+ meta: any;
+}
+
+interface UseTraceSpansOptions<F extends string> {
+ fields: F[];
+ trace: TraceResult;
+ datetime?: PageFilters['datetime'];
+ enabled?: boolean;
+ limit?: number;
+ metricsMax?: string;
+ metricsMin?: string;
+ metricsOp?: string;
+ metricsQuery?: string;
+ mri?: string;
+ query?: string | string[];
+ sort?: string[];
+}
+
+export function useTraceSpans<F extends string>({
+ fields,
+ trace,
+ datetime,
+ enabled,
+ limit,
+ mri,
+ metricsMax,
+ metricsMin,
+ metricsOp,
+ metricsQuery,
+ query,
+ sort,
+}: UseTraceSpansOptions<F>) {
+ const organization = useOrganization();
+ const {selection} = usePageFilters();
+
+ const path = `/organizations/${organization.slug}/trace/${trace.trace}/spans/`;
+
+ const endpointOptions = {
+ query: {
+ project: selection.projects,
+ environment: selection.environments,
+ ...(datetime ?? normalizeDateTimeParams(selection.datetime)),
+ field: fields,
+ query,
+ sort,
+ per_page: limit,
+ maxSpansPerTrace: 10,
+ mri,
+ metricsMax,
+ metricsMin,
+ metricsOp,
+ metricsQuery,
+ },
+ };
+
+ const result = useApiQuery<SpanResults<F>>([path, endpointOptions], {
+ staleTime: 0,
+ refetchOnWindowFocus: false,
+ retry: false,
+ enabled,
+ });
+
+ return result;
+}
diff --git a/static/app/views/traces/hooks/useTraces.spec.tsx b/static/app/views/traces/hooks/useTraces.spec.tsx
new file mode 100644
index 00000000000000..355ceb731134f9
--- /dev/null
+++ b/static/app/views/traces/hooks/useTraces.spec.tsx
@@ -0,0 +1,132 @@
+import {OrganizationFixture} from 'sentry-fixture/organization';
+import {ProjectFixture} from 'sentry-fixture/project';
+
+import {initializeOrg} from 'sentry-test/initializeOrg';
+import {makeTestQueryClient} from 'sentry-test/queryClient';
+import {act, renderHook, waitFor} from 'sentry-test/reactTestingLibrary';
+
+import PageFiltersStore from 'sentry/stores/pageFiltersStore';
+import ProjectsStore from 'sentry/stores/projectsStore';
+import type {Organization} from 'sentry/types';
+import {QueryClientProvider} from 'sentry/utils/queryClient';
+import {OrganizationContext} from 'sentry/views/organizationContext';
+import type {TraceResult} from 'sentry/views/traces/hooks/useTraces';
+import {useTraces} from 'sentry/views/traces/hooks/useTraces';
+
+function createTraceResult(trace?: Partial<TraceResult>): TraceResult {
+ return {
+ breakdowns: [],
+ duration: 333,
+ end: 456,
+ matchingSpans: 1,
+ name: 'name',
+ numErrors: 1,
+ numOccurrences: 1,
+ numSpans: 2,
+ project: 'project',
+ slices: 10,
+ start: 123,
+ trace: '00000000000000000000000000000000',
+ ...trace,
+ };
+}
+
+function createWrapper(organization: Organization) {
+ return function ({children}: {children?: React.ReactNode}) {
+ return (
+ <QueryClientProvider client={makeTestQueryClient()}>
+ <OrganizationContext.Provider value={organization}>
+ {children}
+ </OrganizationContext.Provider>
+ </QueryClientProvider>
+ );
+ };
+}
+
+describe('useTraces', function () {
+ const project = ProjectFixture();
+ const organization = OrganizationFixture();
+ const context = initializeOrg({
+ organization,
+ projects: [project],
+ router: {
+ location: {
+ pathname: '/organizations/org-slug/issues/',
+ query: {project: project.id},
+ },
+ params: {},
+ },
+ });
+
+ beforeEach(function () {
+ MockApiClient.clearMockResponses();
+ act(() => {
+ ProjectsStore.loadInitialData([project]);
+ PageFiltersStore.init();
+ PageFiltersStore.onInitializeUrlState(
+ {
+ projects: [project].map(p => parseInt(p.id, 10)),
+ environments: [],
+ datetime: {
+ period: '3d',
+ start: null,
+ end: null,
+ utc: null,
+ },
+ },
+ new Set()
+ );
+ });
+ });
+
+ it('handles querying the api', async function () {
+ const trace = createTraceResult();
+
+ const body = {
+ data: [trace],
+ meta: {},
+ };
+
+ MockApiClient.addMockResponse({
+ url: `/organizations/${organization.slug}/traces/`,
+ body,
+ match: [
+ MockApiClient.matchQuery({
+ project: [parseInt(project.id, 10)],
+ query: 'foo:bar',
+ period: '3d',
+ per_page: 10,
+ breakdownSlices: 40,
+ mri: 'd:transactions/duration@millisecond',
+ metricsMax: '456',
+ metricsMin: '123',
+ metricsOp: 'sum',
+ metricsQuery: 'foo:bar',
+ }),
+ ],
+ });
+
+ const {result} = renderHook(useTraces, {
+ ...context,
+ wrapper: createWrapper(organization),
+ initialProps: {
+ datetime: {
+ end: null,
+ period: '3d',
+ start: null,
+ utc: null,
+ },
+ limit: 10,
+ query: 'foo:bar',
+ mri: 'd:transactions/duration@millisecond',
+ metricsMax: '456',
+ metricsMin: '123',
+ metricsOp: 'sum',
+ metricsQuery: 'foo:bar',
+ },
+ });
+
+ await waitFor(() => result.current.isSuccess);
+ expect(result.current.data).toEqual(body);
+ });
+});
diff --git a/static/app/views/traces/hooks/useTraces.tsx b/static/app/views/traces/hooks/useTraces.tsx
new file mode 100644
index 00000000000000..6d24121cb76bd9
--- /dev/null
+++ b/static/app/views/traces/hooks/useTraces.tsx
@@ -0,0 +1,163 @@
+import {useEffect} from 'react';
+
+import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
+import type {PageFilters} from 'sentry/types/core';
+import {trackAnalytics} from 'sentry/utils/analytics';
+import {useApiQuery} from 'sentry/utils/queryClient';
+import useOrganization from 'sentry/utils/useOrganization';
+import usePageFilters from 'sentry/utils/usePageFilters';
+import useProjects from 'sentry/utils/useProjects';
+
+export const BREAKDOWN_SLICES = 40;
+
+interface TraceBreakdownBase {
+ duration: number; // Contains the accurate duration for display. Start and end may be quantized.
+ end: number;
+ opCategory: string | null;
+ sdkName: string | null;
+ sliceEnd: number;
+ sliceStart: number;
+ sliceWidth: number;
+ start: number;
+}
+
+type TraceBreakdownProject = TraceBreakdownBase & {
+ kind: 'project';
+ project: string;
+};
+
+type TraceBreakdownMissing = TraceBreakdownBase & {
+ kind: 'missing';
+ project: null;
+};
+
+export interface TraceResult {
+ breakdowns: TraceBreakdownResult[];
+ duration: number;
+ end: number;
+ matchingSpans: number;
+ name: string | null;
+ numErrors: number;
+ numOccurrences: number;
+ numSpans: number;
+ project: string | null;
+ slices: number;
+ start: number;
+ trace: string;
+}
+
+export type TraceBreakdownResult = TraceBreakdownProject | TraceBreakdownMissing;
+
+interface TraceResults {
+ data: TraceResult[];
+ meta: any;
+}
+
+interface UseTracesOptions {
+ datetime?: PageFilters['datetime'];
+ enabled?: boolean;
+ limit?: number;
+ metricsMax?: string;
+ metricsMin?: string;
+ metricsOp?: string;
+ metricsQuery?: string;
+ mri?: string;
+ query?: string | string[];
+ sort?: '-timestamp';
+}
+
+export function useTraces({
+ datetime,
+ enabled,
+ limit,
+ mri,
+ metricsMax,
+ metricsMin,
+ metricsOp,
+ metricsQuery,
+ query,
+ sort,
+}: UseTracesOptions) {
+ const organization = useOrganization();
+ const {projects} = useProjects();
+ const {selection} = usePageFilters();
+
+ const path = `/organizations/${organization.slug}/traces/`;
+
+ const endpointOptions = {
+ query: {
+ project: selection.projects,
+ environment: selection.environments,
+ ...(datetime ?? normalizeDateTimeParams(selection.datetime)),
+ query,
+ sort,
+ per_page: limit,
+ breakdownSlices: BREAKDOWN_SLICES,
+ mri,
+ metricsMax,
+ metricsMin,
+ metricsOp,
+ metricsQuery,
+ },
+ };
+
+ const serializedEndpointOptions = JSON.stringify(endpointOptions);
+
+ let queries: string[] = [];
+ if (Array.isArray(query)) {
+ queries = query;
+ } else if (query !== undefined) {
+ queries = [query];
+ }
+
+ useEffect(() => {
+ trackAnalytics('trace_explorer.search_request', {
+ organization,
+ queries,
+ });
+ // `queries` is already included as a dep in serializedEndpointOptions
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [serializedEndpointOptions, organization]);
+
+ const result = useApiQuery<TraceResults>([path, endpointOptions], {
+ staleTime: 0,
+ refetchOnWindowFocus: false,
+ retry: false,
+ enabled,
+ });
+
+ useEffect(() => {
+ if (result.status === 'success') {
+ const project_slugs = [...new Set(result.data.data.map(trace => trace.project))];
+ const project_platforms = projects
+ .filter(p => project_slugs.includes(p.slug))
+ .map(p => p.platform ?? '');
+
+ trackAnalytics('trace_explorer.search_success', {
+ organization,
+ queries,
+ has_data: result.data.data.length > 0,
+ num_traces: result.data.data.length,
+ num_missing_trace_root: result.data.data.filter(trace => trace.name === null)
+ .length,
+ project_platforms,
+ });
+ } else if (result.status === 'error') {
+ const response = result.error.responseJSON;
+ const error =
+ typeof response?.detail === 'string'
+ ? response?.detail
+ : response?.detail?.message;
+ trackAnalytics('trace_explorer.search_failure', {
+ organization,
+ queries,
+ error: error ?? '',
+ });
+ }
+ // result.status is tied to result.data. No need to explicitly
+ // include result.data as an additional dep.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [serializedEndpointOptions, result.status, organization]);
+
+ return result;
+}
diff --git a/static/app/views/traces/utils.tsx b/static/app/views/traces/utils.tsx
index d76b866c3b3e98..a2e7510db4fadb 100644
--- a/static/app/views/traces/utils.tsx
+++ b/static/app/views/traces/utils.tsx
@@ -2,7 +2,8 @@ import type {Location, LocationDescriptor} from 'history';
import type {Organization} from 'sentry/types/organization';
-import type {SpanResult, TraceResult} from './content';
+import type {TraceResult} from './hooks/useTraces';
+import type {SpanResult} from './hooks/useTraceSpans';
import type {Field} from './data';
export function normalizeTraces(traces: TraceResult[] | undefined) {
|
e334d098a9eddbb33823522beb325b9b134c711b
|
2019-06-10 21:07:43
|
Billy Vong
|
build(babel): Add file and line #s to React JSX warnings (#13607)
| false
|
Add file and line #s to React JSX warnings (#13607)
|
build
|
diff --git a/babel.config.js b/babel.config.js
index 20a51fe7662969..99f00dad0d49a4 100644
--- a/babel.config.js
+++ b/babel.config.js
@@ -18,7 +18,10 @@ module.exports = {
env: {
production: {},
development: {
- plugins: [['emotion', {sourceMap: true, autoLabel: true}]],
+ plugins: [
+ ['emotion', {sourceMap: true, autoLabel: true}],
+ '@babel/plugin-transform-react-jsx-source',
+ ],
},
test: {
plugins: [['emotion', {autoLabel: true}], 'dynamic-import-node'],
diff --git a/package.json b/package.json
index 19abbf04318c36..8967e6718acae4 100644
--- a/package.json
+++ b/package.json
@@ -97,6 +97,7 @@
"zxcvbn": "^4.4.2"
},
"devDependencies": {
+ "@babel/plugin-transform-react-jsx-source": "^7.2.0",
"@storybook/addon-a11y": "^4.1.3",
"@storybook/addon-actions": "^4.1.3",
"@storybook/addon-info": "^4.1.3",
diff --git a/yarn.lock b/yarn.lock
index 7786a1369aeb11..7b974a19453fbe 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -698,7 +698,7 @@
"@babel/helper-plugin-utils" "^7.0.0"
"@babel/plugin-syntax-jsx" "^7.2.0"
-"@babel/plugin-transform-react-jsx-source@^7.0.0":
+"@babel/plugin-transform-react-jsx-source@^7.0.0", "@babel/plugin-transform-react-jsx-source@^7.2.0":
version "7.2.0"
resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.2.0.tgz#20c8c60f0140f5dd3cd63418d452801cf3f7180f"
integrity sha512-A32OkKTp4i5U6aE88GwwcuV4HAprUgHcTq0sSafLxjr6AW0QahrCRCjxogkbbcdtpbXkuTOlgpjophCxb6sh5g==
@@ -11108,12 +11108,7 @@ react-is@^16.4.2:
resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.4.2.tgz#84891b56c2b6d9efdee577cc83501dfc5ecead88"
integrity sha512-rI3cGFj/obHbBz156PvErrS5xc6f1eWyTwyV4mo0vF2lGgXgS+mm7EKD5buLJq6jNgIagQescGSVG2YzgXt8Yg==
-react-is@^16.7.0:
- version "16.8.6"
- resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.8.6.tgz#5bbc1e2d29141c9fbdfed456343fe2bc430a6a16"
- integrity sha512-aUk3bHfZ2bRSVFFbbeVS4i+lNPZr3/WM5jT2J5omUVV1zzcs1nAaf3l51ctA5FFvCRbhrH0bdAsRRQddFJZPtA==
-
-react-is@^16.8.1, react-is@^16.8.6:
+react-is@^16.7.0, react-is@^16.8.1, react-is@^16.8.6:
version "16.8.6"
resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.8.6.tgz#5bbc1e2d29141c9fbdfed456343fe2bc430a6a16"
integrity sha512-aUk3bHfZ2bRSVFFbbeVS4i+lNPZr3/WM5jT2J5omUVV1zzcs1nAaf3l51ctA5FFvCRbhrH0bdAsRRQddFJZPtA==
|
5a7f5625d1d8a86b74644d4fd91fdc77f31bbd62
|
2018-09-27 21:36:34
|
Billy Vong
|
fix(ui): Fix Alert Editor when no plugins (#9900)
| false
|
Fix Alert Editor when no plugins (#9900)
|
fix
|
diff --git a/src/sentry/static/sentry/app/views/settings/projectAlerts/ruleEditor/ruleNode.jsx b/src/sentry/static/sentry/app/views/settings/projectAlerts/ruleEditor/ruleNode.jsx
index 61d01f289a6b8d..57df693f5f78b0 100644
--- a/src/sentry/static/sentry/app/views/settings/projectAlerts/ruleEditor/ruleNode.jsx
+++ b/src/sentry/static/sentry/app/views/settings/projectAlerts/ruleEditor/ruleNode.jsx
@@ -1,7 +1,9 @@
import PropTypes from 'prop-types';
import React from 'react';
import styled from 'react-emotion';
+
import Button from 'app/components/button';
+import {t} from 'app/locale';
import {SelectField, NumberField, TextField} from 'app/components/forms';
class RuleNode extends React.Component {
@@ -20,7 +22,7 @@ class RuleNode extends React.Component {
// If it's not yet defined, call handlePropertyChange to make sure the value is set on state
let initialVal;
- if (this.props.data[name] === undefined) {
+ if (this.props.data[name] === undefined && !!data.choices.length) {
initialVal = data.choices[0][0];
this.props.handlePropertyChange(name, initialVal);
} else {
@@ -30,6 +32,8 @@ class RuleNode extends React.Component {
return (
<SelectField
clearable={false}
+ placeholder={t('Select integration')}
+ noResultsText={t('No integrations available')}
name={name}
value={initialVal}
choices={data.choices}
@@ -145,6 +149,10 @@ const RuleNodeForm = styled('div')`
line-height: 26px;
min-width: 150px;
}
+ .Select-placeholder {
+ height: 26px;
+ line-height: 26px;
+ }
.Select-control {
height: 24px;
}
diff --git a/tests/js/spec/views/__snapshots__/projectAlertRuleDetails.spec.jsx.snap b/tests/js/spec/views/__snapshots__/projectAlertRuleDetails.spec.jsx.snap
index f8be6655b46cfd..35cb8c8e809043 100644
--- a/tests/js/spec/views/__snapshots__/projectAlertRuleDetails.spec.jsx.snap
+++ b/tests/js/spec/views/__snapshots__/projectAlertRuleDetails.spec.jsx.snap
@@ -653,7 +653,7 @@ exports[`ProjectAlertRuleDetails Edit alert rule renders 1`] = `
>
<RuleNodeForm>
<div
- className="css-xqmzt9-RuleNodeForm e1qnqozx1"
+ className="css-1by90re-RuleNodeForm e1qnqozx1"
>
<input
name="id"
@@ -1412,7 +1412,7 @@ exports[`ProjectAlertRuleDetails Edit alert rule renders 1`] = `
>
<RuleNodeForm>
<div
- className="css-xqmzt9-RuleNodeForm e1qnqozx1"
+ className="css-1by90re-RuleNodeForm e1qnqozx1"
>
<input
name="id"
|
9caf0af959c42afb6d73ca5b2943708ffd527e15
|
2021-04-28 03:06:58
|
Evan Purkhiser
|
ref(ts): Fix a couple arbitrary any's (#25683)
| false
|
Fix a couple arbitrary any's (#25683)
|
ref
|
diff --git a/static/app/components/alerts/toastIndicator.tsx b/static/app/components/alerts/toastIndicator.tsx
index 822d3bf016c620..818e9eb71f70f5 100644
--- a/static/app/components/alerts/toastIndicator.tsx
+++ b/static/app/components/alerts/toastIndicator.tsx
@@ -87,7 +87,7 @@ function ToastIndicator({indicator, onDismiss, className, ...props}: Props) {
const {options, message, type} = indicator;
const {undo, disableDismiss} = options || {};
const showUndo = typeof undo === 'function';
- const handleClick = e => {
+ const handleClick = (e: React.MouseEvent) => {
if (disableDismiss) {
return;
}
diff --git a/static/app/views/settings/organizationTeams/allTeamsRow.tsx b/static/app/views/settings/organizationTeams/allTeamsRow.tsx
index 0e1df435a8fb8a..8a410cf5364c8d 100644
--- a/static/app/views/settings/organizationTeams/allTeamsRow.tsx
+++ b/static/app/views/settings/organizationTeams/allTeamsRow.tsx
@@ -65,7 +65,13 @@ class AllTeamsRow extends React.Component<Props, State> {
});
};
- joinTeam = ({successMessage, errorMessage}) => {
+ joinTeam = ({
+ successMessage,
+ errorMessage,
+ }: {
+ successMessage: React.ReactNode;
+ errorMessage: React.ReactNode;
+ }) => {
const {api, organization, team} = this.props;
this.setState({
|
6712918f5af7c2345d7c42f6fdf125d84f4e6b2d
|
2024-02-16 02:22:36
|
Yagiz Nizipli
|
build: add jsx/tsx to pre-commit-hook (#65266)
| false
|
add jsx/tsx to pre-commit-hook (#65266)
|
build
|
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 7e281110a6f8d2..a8dbc8b8c51f07 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -119,11 +119,12 @@ repos:
name: biome (javascript, typescript, json)
additional_dependencies: ['@biomejs/[email protected]']
- repo: https://github.com/pre-commit/mirrors-prettier
- rev: 'v3.0.3' # Use the sha or tag you want to point at
+ rev: 'v3.1.0' # Use the sha or tag you want to point at
hooks:
- id: prettier
- name: prettier (yaml, markdown)
- types_or: [yaml, markdown]
+ name: prettier (yaml, markdown, tsx, jsx, css)
+ # TODO: Remove tsx and jsx when Biome supports styled CSS formatting.
+ types_or: [yaml, markdown, tsx, jsx, css]
# https://pre-commit.com/#regular-expressions
exclude: |
(?x)^($^
diff --git a/.vscode/extensions.json b/.vscode/extensions.json
index 74d9783e2f7ef8..16077bc55b2e05 100644
--- a/.vscode/extensions.json
+++ b/.vscode/extensions.json
@@ -2,6 +2,7 @@
// See https://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
+ "esbenp.prettier-vscode",
"biomejs.biome",
"ms-python.python",
"ms-python.black-formatter",
|
44e82becd67e9c8da69d6e8e5ff2a5f98e5b4790
|
2024-11-21 00:22:41
|
Colleen O'Rourke
|
chore(alerts): Rm unused incidents endpoints (#81026)
| false
|
Rm unused incidents endpoints (#81026)
|
chore
|
diff --git a/pyproject.toml b/pyproject.toml
index 71087452d5c44e..2430cb3c36673c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -198,7 +198,6 @@ module = [
"sentry.incidents.endpoints.bases",
"sentry.incidents.endpoints.organization_alert_rule_details",
"sentry.incidents.endpoints.organization_alert_rule_index",
- "sentry.incidents.endpoints.organization_incident_comment_details",
"sentry.incidents.endpoints.organization_incident_index",
"sentry.incidents.subscription_processor",
"sentry.incidents.tasks",
diff --git a/src/sentry/api/urls.py b/src/sentry/api/urls.py
index c1155a74b3502e..d631b249dc97e6 100644
--- a/src/sentry/api/urls.py
+++ b/src/sentry/api/urls.py
@@ -100,23 +100,10 @@
OrganizationAlertRuleIndexEndpoint,
OrganizationCombinedRuleIndexEndpoint,
)
-from sentry.incidents.endpoints.organization_incident_activity_index import (
- OrganizationIncidentActivityIndexEndpoint,
-)
-from sentry.incidents.endpoints.organization_incident_comment_details import (
- OrganizationIncidentCommentDetailsEndpoint,
-)
-from sentry.incidents.endpoints.organization_incident_comment_index import (
- OrganizationIncidentCommentIndexEndpoint,
-)
from sentry.incidents.endpoints.organization_incident_details import (
OrganizationIncidentDetailsEndpoint,
)
from sentry.incidents.endpoints.organization_incident_index import OrganizationIncidentIndexEndpoint
-from sentry.incidents.endpoints.organization_incident_seen import OrganizationIncidentSeenEndpoint
-from sentry.incidents.endpoints.organization_incident_subscription_index import (
- OrganizationIncidentSubscriptionIndexEndpoint,
-)
from sentry.incidents.endpoints.project_alert_rule_details import ProjectAlertRuleDetailsEndpoint
from sentry.incidents.endpoints.project_alert_rule_index import ProjectAlertRuleIndexEndpoint
from sentry.incidents.endpoints.project_alert_rule_task_details import (
@@ -1206,21 +1193,6 @@ def create_group_urls(name_prefix: str) -> list[URLPattern | URLResolver]:
name="sentry-api-0-data-secrecy",
),
# Incidents
- re_path(
- r"^(?P<organization_id_or_slug>[^\/]+)/incidents/(?P<incident_identifier>[^\/]+)/activity/$",
- OrganizationIncidentActivityIndexEndpoint.as_view(),
- name="sentry-api-0-organization-incident-activity",
- ),
- re_path(
- r"^(?P<organization_id_or_slug>[^\/]+)/incidents/(?P<incident_identifier>[^\/]+)/comments/$",
- OrganizationIncidentCommentIndexEndpoint.as_view(),
- name="sentry-api-0-organization-incident-comments",
- ),
- re_path(
- r"^(?P<organization_id_or_slug>[^\/]+)/incidents/(?P<incident_identifier>[^\/]+)/comments/(?P<activity_id>[^\/]+)/$",
- OrganizationIncidentCommentDetailsEndpoint.as_view(),
- name="sentry-api-0-organization-incident-comment-details",
- ),
re_path(
r"^(?P<organization_id_or_slug>[^\/]+)/incidents/(?P<incident_identifier>[^\/]+)/$",
OrganizationIncidentDetailsEndpoint.as_view(),
@@ -1231,16 +1203,6 @@ def create_group_urls(name_prefix: str) -> list[URLPattern | URLResolver]:
OrganizationIncidentIndexEndpoint.as_view(),
name="sentry-api-0-organization-incident-index",
),
- re_path(
- r"^(?P<organization_id_or_slug>[^\/]+)/incidents/(?P<incident_identifier>[^\/]+)/seen/$",
- OrganizationIncidentSeenEndpoint.as_view(),
- name="sentry-api-0-organization-incident-seen",
- ),
- re_path(
- r"^(?P<organization_id_or_slug>[^\/]+)/incidents/(?P<incident_identifier>[^\/]+)/subscriptions/$",
- OrganizationIncidentSubscriptionIndexEndpoint.as_view(),
- name="sentry-api-0-organization-incident-subscription-index",
- ),
re_path(
r"^(?P<organization_id_or_slug>[^\/]+)/chunk-upload/$",
ChunkUploadEndpoint.as_view(),
diff --git a/src/sentry/incidents/endpoints/organization_incident_activity_index.py b/src/sentry/incidents/endpoints/organization_incident_activity_index.py
deleted file mode 100644
index 0437f5fa249a03..00000000000000
--- a/src/sentry/incidents/endpoints/organization_incident_activity_index.py
+++ /dev/null
@@ -1,33 +0,0 @@
-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.incident import IncidentEndpoint, IncidentPermission
-from sentry.api.paginator import OffsetPaginator
-from sentry.api.serializers import serialize
-from sentry.incidents.logic import get_incident_activity
-
-
-@region_silo_endpoint
-class OrganizationIncidentActivityIndexEndpoint(IncidentEndpoint):
- owner = ApiOwner.ISSUES
- publish_status = {
- "GET": ApiPublishStatus.UNKNOWN,
- }
- permission_classes = (IncidentPermission,)
-
- def get(self, request: Request, organization, incident) -> Response:
- if request.GET.get("desc", "1") == "1":
- order_by = "-date_added"
- else:
- order_by = "date_added"
-
- return self.paginate(
- request=request,
- queryset=get_incident_activity(incident),
- order_by=order_by,
- paginator_cls=OffsetPaginator,
- on_results=lambda x: serialize(x, request.user),
- )
diff --git a/src/sentry/incidents/endpoints/organization_incident_comment_details.py b/src/sentry/incidents/endpoints/organization_incident_comment_details.py
deleted file mode 100644
index fdfc47e8a31cfb..00000000000000
--- a/src/sentry/incidents/endpoints/organization_incident_comment_details.py
+++ /dev/null
@@ -1,88 +0,0 @@
-from rest_framework import serializers
-from rest_framework.exceptions import PermissionDenied
-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.incident import IncidentEndpoint, IncidentPermission
-from sentry.api.exceptions import ResourceDoesNotExist
-from sentry.api.serializers import serialize
-from sentry.incidents.models.incident import IncidentActivity, IncidentActivityType
-
-
-class CommentSerializer(serializers.Serializer):
- comment = serializers.CharField(required=True)
-
-
-class CommentDetailsEndpoint(IncidentEndpoint):
- def convert_args(self, request: Request, activity_id, *args, **kwargs):
- # See GroupNotesDetailsEndpoint:
- # We explicitly don't allow a request with an ApiKey
- # since an ApiKey is bound to the Organization, not
- # an individual. Not sure if we'd want to allow an ApiKey
- # to delete/update other users' comments
- if not request.user.is_authenticated:
- raise PermissionDenied(detail="Key doesn't have permission to delete Note")
-
- args, kwargs = super().convert_args(request, *args, **kwargs)
-
- try:
- # Superusers may mutate any comment
- user_filter = {} if request.user.is_superuser else {"user_id": request.user.id}
-
- kwargs["activity"] = IncidentActivity.objects.get(
- id=activity_id,
- incident=kwargs["incident"],
- # Only allow modifying comments
- type=IncidentActivityType.COMMENT.value,
- **user_filter,
- )
- except IncidentActivity.DoesNotExist:
- raise ResourceDoesNotExist
-
- return args, kwargs
-
-
-@region_silo_endpoint
-class OrganizationIncidentCommentDetailsEndpoint(CommentDetailsEndpoint):
- owner = ApiOwner.ISSUES
- publish_status = {
- "DELETE": ApiPublishStatus.UNKNOWN,
- "PUT": ApiPublishStatus.UNKNOWN,
- }
- permission_classes = (IncidentPermission,)
-
- def delete(self, request: Request, organization, incident, activity) -> Response:
- """
- Delete a comment
- ````````````````
- :auth: required
- """
-
- try:
- activity.delete()
- except IncidentActivity.DoesNotExist:
- raise ResourceDoesNotExist
-
- return Response(status=204)
-
- def put(self, request: Request, organization, incident, activity) -> Response:
- """
- Update an existing comment
- ``````````````````````````
- :auth: required
- """
-
- serializer = CommentSerializer(data=request.data)
- if serializer.is_valid():
- result = serializer.validated_data
-
- try:
- comment = activity.update(comment=result.get("comment"))
- except IncidentActivity.DoesNotExist:
- raise ResourceDoesNotExist
-
- return Response(serialize(comment, request.user), status=200)
- return Response(serializer.errors, status=400)
diff --git a/src/sentry/incidents/endpoints/organization_incident_comment_index.py b/src/sentry/incidents/endpoints/organization_incident_comment_index.py
deleted file mode 100644
index b2a534ed598b23..00000000000000
--- a/src/sentry/incidents/endpoints/organization_incident_comment_index.py
+++ /dev/null
@@ -1,56 +0,0 @@
-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 region_silo_endpoint
-from sentry.api.bases.incident import IncidentEndpoint, IncidentPermission
-from sentry.api.fields.actor import ActorField
-from sentry.api.serializers import serialize
-from sentry.api.serializers.rest_framework.mentions import (
- MentionsMixin,
- extract_user_ids_from_mentions,
-)
-from sentry.incidents.logic import create_incident_activity
-from sentry.incidents.models.incident import IncidentActivityType
-from sentry.users.services.user.serial import serialize_generic_user
-
-
-class CommentSerializer(serializers.Serializer, MentionsMixin):
- comment = serializers.CharField(required=True)
- mentions = serializers.ListField(child=ActorField(), required=False)
- external_id = serializers.CharField(allow_null=True, required=False)
-
-
-@region_silo_endpoint
-class OrganizationIncidentCommentIndexEndpoint(IncidentEndpoint):
- owner = ApiOwner.ISSUES
- publish_status = {
- "POST": ApiPublishStatus.UNKNOWN,
- }
- permission_classes = (IncidentPermission,)
-
- def post(self, request: Request, organization, incident) -> Response:
- serializer = CommentSerializer(
- data=request.data,
- context={
- "projects": incident.projects.all(),
- "organization": organization,
- "organization_id": organization.id,
- },
- )
- if serializer.is_valid():
- mentions = extract_user_ids_from_mentions(
- organization.id, serializer.validated_data.get("mentions", [])
- )
- mentioned_user_ids = mentions["users"] | mentions["team_users"]
- activity = create_incident_activity(
- incident,
- IncidentActivityType.COMMENT,
- user=serialize_generic_user(request.user),
- comment=serializer.validated_data["comment"],
- mentioned_user_ids=mentioned_user_ids,
- )
- return Response(serialize(activity, request.user), status=201)
- return Response(serializer.errors, status=400)
diff --git a/src/sentry/incidents/endpoints/organization_incident_seen.py b/src/sentry/incidents/endpoints/organization_incident_seen.py
deleted file mode 100644
index 869596a422b021..00000000000000
--- a/src/sentry/incidents/endpoints/organization_incident_seen.py
+++ /dev/null
@@ -1,53 +0,0 @@
-from django.utils import timezone as django_timezone
-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.incident import IncidentEndpoint, IncidentPermission
-from sentry.incidents.models.incident import Incident, IncidentProject, IncidentSeen
-from sentry.models.organization import Organization
-from sentry.users.services.user import RpcUser
-from sentry.users.services.user.serial import serialize_generic_user
-
-
-@region_silo_endpoint
-class OrganizationIncidentSeenEndpoint(IncidentEndpoint):
- owner = ApiOwner.ISSUES
- publish_status = {
- "POST": ApiPublishStatus.UNKNOWN,
- }
- permission_classes = (IncidentPermission,)
-
- def post(self, request: Request, organization: Organization, incident: Incident) -> Response:
- """
- Mark an incident as seen by the user
- ````````````````````````````````````
-
- :auth: required
- """
-
- user = serialize_generic_user(request.user)
- if user is not None:
- _set_incident_seen(incident, user)
- return Response({}, status=201)
-
-
-def _set_incident_seen(incident: Incident, user: RpcUser) -> None:
- """
- Updates the incident to be seen
- """
-
- def is_project_member() -> bool:
- incident_projects = IncidentProject.objects.filter(incident=incident)
- for incident_project in incident_projects.select_related("project"):
- if incident_project.project.member_set.filter(user_id=user.id).exists():
- return True
- return False
-
- is_org_member = incident.organization.has_access(user)
- if is_org_member and is_project_member():
- IncidentSeen.objects.create_or_update(
- incident=incident, user_id=user.id, values={"last_seen": django_timezone.now()}
- )
diff --git a/src/sentry/incidents/endpoints/organization_incident_subscription_index.py b/src/sentry/incidents/endpoints/organization_incident_subscription_index.py
deleted file mode 100644
index dd22eea9d5a32e..00000000000000
--- a/src/sentry/incidents/endpoints/organization_incident_subscription_index.py
+++ /dev/null
@@ -1,52 +0,0 @@
-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.incident import IncidentEndpoint, IncidentPermission
-from sentry.incidents.logic import subscribe_to_incident, unsubscribe_from_incident
-
-
-class IncidentSubscriptionPermission(IncidentPermission):
- scope_map = IncidentPermission.scope_map.copy()
- scope_map["DELETE"] = [
- "org:write",
- "org:admin",
- "project:read",
- "project:write",
- "project:admin",
- ]
-
-
-@region_silo_endpoint
-class OrganizationIncidentSubscriptionIndexEndpoint(IncidentEndpoint):
- owner = ApiOwner.ISSUES
- publish_status = {
- "DELETE": ApiPublishStatus.UNKNOWN,
- "POST": ApiPublishStatus.UNKNOWN,
- }
- permission_classes = (IncidentSubscriptionPermission,)
-
- def post(self, request: Request, organization, incident) -> Response:
- """
- Subscribes the authenticated user to the incident.
- ``````````````````````````````````````````````````
- Subscribes the user to the incident. If they are already subscribed
- then no-op.
- :auth: required
- """
-
- subscribe_to_incident(incident, request.user.id)
- return Response({}, status=201)
-
- def delete(self, request: Request, organization, incident) -> Response:
- """
- Unsubscribes the authenticated user from the incident.
- ``````````````````````````````````````````````````````
- Unsubscribes the user from the incident. If they are not subscribed then
- no-op.
- :auth: required
- """
- unsubscribe_from_incident(incident, request.user.id)
- return Response({}, status=200)
diff --git a/tests/sentry/incidents/endpoints/test_organization_incident_activity_index.py b/tests/sentry/incidents/endpoints/test_organization_incident_activity_index.py
deleted file mode 100644
index 01a2b9b33d5f0d..00000000000000
--- a/tests/sentry/incidents/endpoints/test_organization_incident_activity_index.py
+++ /dev/null
@@ -1,75 +0,0 @@
-from datetime import timedelta
-from functools import cached_property
-
-from django.utils import timezone
-
-from sentry.api.serializers import serialize
-from sentry.incidents.logic import create_incident_activity
-from sentry.incidents.models.incident import IncidentActivityType
-from sentry.testutils.cases import APITestCase
-
-
-class OrganizationIncidentActivityIndexTest(APITestCase):
- endpoint = "sentry-api-0-organization-incident-activity"
-
- def setUp(self):
- self.create_team(organization=self.organization, members=[self.user])
- self.login_as(self.user)
-
- @cached_property
- def organization(self):
- return self.create_organization(owner=self.create_user())
-
- @cached_property
- def project(self):
- return self.create_project(organization=self.organization)
-
- @cached_property
- def user(self):
- return self.create_user()
-
- def test_no_perms(self):
- incident = self.create_incident()
- self.login_as(self.create_user())
- with self.feature("organizations:incidents"):
- resp = self.get_response(incident.organization.slug, incident.id)
- assert resp.status_code == 403
-
- def test_no_feature(self):
- incident = self.create_incident()
- resp = self.get_response(incident.organization.slug, incident.id)
- assert resp.status_code == 404
-
- def test_simple(self):
- incident = self.create_incident(
- date_started=timezone.now() - timedelta(hours=2), projects=[self.project], query=""
- )
- activities = [
- create_incident_activity(
- incident=incident,
- activity_type=IncidentActivityType.CREATED,
- user=self.user,
- comment="hello",
- ),
- create_incident_activity(
- incident=incident,
- activity_type=IncidentActivityType.COMMENT,
- user=self.user,
- comment="goodbye",
- ),
- ]
-
- expected = serialize(activities, user=self.user)
-
- with self.feature("organizations:incidents"):
- resp = self.get_success_response(
- incident.organization.slug, incident.identifier, desc=0
- )
-
- assert resp.data == expected
-
- expected.reverse()
- with self.feature("organizations:incidents"):
- resp = self.get_success_response(incident.organization.slug, incident.identifier)
-
- assert resp.data == expected
diff --git a/tests/sentry/incidents/endpoints/test_organization_incident_comment_details.py b/tests/sentry/incidents/endpoints/test_organization_incident_comment_details.py
deleted file mode 100644
index f03ec7ff51563e..00000000000000
--- a/tests/sentry/incidents/endpoints/test_organization_incident_comment_details.py
+++ /dev/null
@@ -1,146 +0,0 @@
-from functools import cached_property
-
-from sentry.incidents.models.incident import IncidentActivity, IncidentActivityType
-from sentry.silo.base import SiloMode
-from sentry.testutils.cases import APITestCase
-from sentry.testutils.silo import assume_test_silo_mode
-
-
-class BaseIncidentCommentDetailsTest(APITestCase):
- method = "put"
- endpoint = "sentry-api-0-organization-incident-comment-details"
-
- def setUp(self):
- self.create_member(
- user=self.user, organization=self.organization, role="owner", teams=[self.team]
- )
- self.login_as(self.user)
- self.activity = self.create_incident_comment(self.incident, user_id=self.user.id)
- self.detected_activity = self.create_incident_activity(
- self.incident, user_id=self.user.id, type=IncidentActivityType.CREATED.value
- )
-
- user2 = self.create_user()
- self.user2_activity = self.create_incident_comment(
- incident=self.incident, user_id=user2.id, comment="hello from another user"
- )
-
- @cached_property
- def organization(self):
- return self.create_organization()
-
- @cached_property
- def project(self):
- return self.create_project(organization=self.organization)
-
- @cached_property
- def user(self):
- return self.create_user()
-
- @cached_property
- def incident(self):
- return self.create_incident()
-
- def test_not_found(self):
- comment = "hello"
- with self.feature("organizations:incidents"):
- self.get_error_response(
- self.organization.slug,
- self.incident.identifier,
- 123,
- comment=comment,
- status_code=404,
- )
-
- def test_non_comment_type(self):
- comment = "hello"
- with self.feature("organizations:incidents"):
- self.get_error_response(
- self.organization.slug,
- self.incident.identifier,
- self.detected_activity.id,
- comment=comment,
- status_code=404,
- )
-
-
-class OrganizationIncidentCommentUpdateEndpointTest(BaseIncidentCommentDetailsTest):
- method = "put"
-
- def test_simple(self):
- comment = "hello"
- with self.feature("organizations:incidents"):
- self.get_success_response(
- self.organization.slug,
- self.incident.identifier,
- self.activity.id,
- comment=comment,
- status_code=200,
- )
- activity = IncidentActivity.objects.get(id=self.activity.id)
- assert activity.type == IncidentActivityType.COMMENT.value
- assert activity.user_id == self.user.id
- assert activity.comment == comment
-
- def test_cannot_edit_others_comment(self):
- with self.feature("organizations:incidents"):
- self.get_error_response(
- self.organization.slug,
- self.incident.identifier,
- self.user2_activity.id,
- comment="edited comment",
- status_code=404,
- )
-
- def test_superuser_can_edit(self):
- self.user.is_superuser = True
- with assume_test_silo_mode(SiloMode.CONTROL):
- self.user.save()
-
- edited_comment = "this comment has been edited"
-
- with self.feature("organizations:incidents"):
- self.get_success_response(
- self.organization.slug,
- self.incident.identifier,
- self.user2_activity.id,
- comment=edited_comment,
- status_code=200,
- )
- activity = IncidentActivity.objects.get(id=self.user2_activity.id)
- assert activity.user_id != self.user.id
- assert activity.comment == edited_comment
-
-
-class OrganizationIncidentCommentDeleteEndpointTest(BaseIncidentCommentDetailsTest):
- method = "delete"
-
- def test_simple(self):
- with self.feature("organizations:incidents"):
- self.get_success_response(
- self.organization.slug, self.incident.identifier, self.activity.id, status_code=204
- )
- assert not IncidentActivity.objects.filter(id=self.activity.id).exists()
-
- def test_cannot_delete_others_comments(self):
- with self.feature("organizations:incidents"):
- self.get_error_response(
- self.organization.slug,
- self.incident.identifier,
- self.user2_activity.id,
- status_code=404,
- )
-
- def test_superuser_can_delete(self):
- self.user.is_superuser = True
- with assume_test_silo_mode(SiloMode.CONTROL):
- self.user.save()
-
- with self.feature("organizations:incidents"):
- self.get_success_response(
- self.organization.slug,
- self.incident.identifier,
- self.user2_activity.id,
- status_code=204,
- )
- assert not IncidentActivity.objects.filter(id=self.user2_activity.id).exists()
diff --git a/tests/sentry/incidents/endpoints/test_organization_incident_comment_index.py b/tests/sentry/incidents/endpoints/test_organization_incident_comment_index.py
deleted file mode 100644
index 6837a56bfd4d85..00000000000000
--- a/tests/sentry/incidents/endpoints/test_organization_incident_comment_index.py
+++ /dev/null
@@ -1,84 +0,0 @@
-from functools import cached_property
-
-from sentry.api.serializers import serialize
-from sentry.incidents.models.incident import (
- IncidentActivity,
- IncidentActivityType,
- IncidentSubscription,
-)
-from sentry.testutils.cases import APITestCase
-
-
-class OrganizationIncidentCommentCreateEndpointTest(APITestCase):
- endpoint = "sentry-api-0-organization-incident-comments"
- method = "post"
-
- @cached_property
- def organization(self):
- return self.create_organization()
-
- @cached_property
- def project(self):
- return self.create_project(organization=self.organization)
-
- @cached_property
- def user(self):
- return self.create_user()
-
- def test_simple(self):
- self.create_member(
- user=self.user, organization=self.organization, role="owner", teams=[self.team]
- )
- self.login_as(self.user)
- comment = "hello"
- incident = self.create_incident()
- with self.feature("organizations:incidents"):
- resp = self.get_success_response(
- self.organization.slug, incident.identifier, comment=comment, status_code=201
- )
- activity = IncidentActivity.objects.get(id=resp.data["id"])
- assert activity.type == IncidentActivityType.COMMENT.value
- assert activity.user_id == self.user.id
- assert activity.comment == comment
- assert resp.data == serialize([activity], self.user)[0]
-
- def test_mentions(self):
- self.create_member(
- user=self.user, organization=self.organization, role="owner", teams=[self.team]
- )
- mentioned_member = self.create_user()
- self.create_member(
- user=mentioned_member, organization=self.organization, role="owner", teams=[self.team]
- )
- self.login_as(self.user)
- comment = "hello **@%s**" % mentioned_member.username
- incident = self.create_incident()
- with self.feature("organizations:incidents"):
- resp = self.get_success_response(
- self.organization.slug,
- incident.identifier,
- comment=comment,
- mentions=["user:%s" % mentioned_member.id],
- status_code=201,
- )
- activity = IncidentActivity.objects.get(id=resp.data["id"])
- assert activity.type == IncidentActivityType.COMMENT.value
- assert activity.user_id == self.user.id
- assert activity.comment == comment
- assert resp.data == serialize([activity], self.user)[0]
- assert IncidentSubscription.objects.filter(
- user_id=mentioned_member.id, incident=incident
- ).exists()
-
- def test_access(self):
- other_user = self.create_user()
- self.login_as(other_user)
- other_team = self.create_team()
- self.create_member(
- user=self.user, organization=self.organization, role="member", teams=[self.team]
- )
- other_project = self.create_project(teams=[other_team])
- incident = self.create_incident(projects=[other_project])
- with self.feature("organizations:incidents"):
- resp = self.get_response(self.organization.slug, incident.identifier, comment="hi")
- assert resp.status_code == 403
diff --git a/tests/sentry/incidents/endpoints/test_organization_incident_seen.py b/tests/sentry/incidents/endpoints/test_organization_incident_seen.py
deleted file mode 100644
index 323a2523461a72..00000000000000
--- a/tests/sentry/incidents/endpoints/test_organization_incident_seen.py
+++ /dev/null
@@ -1,69 +0,0 @@
-from functools import cached_property
-
-from django.urls import reverse
-
-from sentry.incidents.models.incident import IncidentSeen
-from sentry.testutils.cases import APITestCase
-
-
-class OrganizationIncidentSeenTest(APITestCase):
- method = "post"
- endpoint = "sentry-api-0-organization-incident-seen"
-
- def setUp(self):
- self.create_team(organization=self.organization, members=[self.user])
- self.login_as(self.user)
-
- @cached_property
- def organization(self):
- return self.create_organization(owner=self.create_user())
-
- @cached_property
- def project(self):
- return self.create_project(organization=self.organization)
-
- @cached_property
- def user(self):
- return self.create_user()
-
- def test_has_user_seen(self):
- incident = self.create_incident()
- with self.feature("organizations:incidents"):
- resp = self.get_response(incident.organization.slug, incident.identifier)
-
- assert resp.status_code == 201
-
- # should not be seen by different user
- new_user = self.create_user()
- self.create_member(user=new_user, organization=self.organization, teams=[self.team])
- self.login_as(new_user)
-
- seen_incidents = IncidentSeen.objects.filter(incident=incident)
- assert len(seen_incidents) == 1
- assert seen_incidents[0].user_id == self.user.id
-
- # mark set as seen by new_user
- resp = self.get_response(incident.organization.slug, incident.identifier)
- assert resp.status_code == 201
-
- seen_incidents = IncidentSeen.objects.filter(incident=incident)
- assert len(seen_incidents) == 2
- assert seen_incidents[0].user_id == self.user.id
- assert seen_incidents[1].user_id == new_user.id
-
- url = reverse(
- "sentry-api-0-organization-incident-details",
- kwargs={
- "organization_id_or_slug": incident.organization.slug,
- "incident_identifier": incident.identifier,
- },
- )
-
- resp = self.client.get(url, format="json")
- assert resp.status_code == 200
- assert resp.data["hasSeen"]
-
- assert len(resp.data["seenBy"]) == 2
- # seenBy is sorted by most recently seen
- assert resp.data["seenBy"][0]["username"] == new_user.username
- assert resp.data["seenBy"][1]["username"] == self.user.username
diff --git a/tests/sentry/incidents/endpoints/test_organization_incident_subscription_index.py b/tests/sentry/incidents/endpoints/test_organization_incident_subscription_index.py
deleted file mode 100644
index 35df013a3c84b5..00000000000000
--- a/tests/sentry/incidents/endpoints/test_organization_incident_subscription_index.py
+++ /dev/null
@@ -1,70 +0,0 @@
-from functools import cached_property
-
-from sentry.incidents.logic import subscribe_to_incident
-from sentry.incidents.models.incident import IncidentSubscription
-from sentry.testutils.abstract import Abstract
-from sentry.testutils.cases import APITestCase
-
-
-class BaseOrganizationSubscriptionEndpointTest(APITestCase):
- __test__ = Abstract(__module__, __qualname__)
-
- endpoint = "sentry-api-0-organization-incident-subscription-index"
-
- @cached_property
- def organization(self):
- return self.create_organization()
-
- @cached_property
- def project(self):
- return self.create_project(organization=self.organization)
-
- @cached_property
- def user(self):
- return self.create_user()
-
- def test_access(self):
- other_user = self.create_user()
- self.login_as(other_user)
- other_team = self.create_team()
- self.create_member(
- user=self.user, organization=self.organization, role="member", teams=[self.team]
- )
- other_project = self.create_project(teams=[other_team])
- incident = self.create_incident(projects=[other_project])
- with self.feature("organizations:incidents"):
- resp = self.get_response(self.organization.slug, incident.identifier, comment="hi")
- assert resp.status_code == 403
-
-
-class OrganizationIncidentSubscribeEndpointTest(BaseOrganizationSubscriptionEndpointTest):
- method = "post"
-
- def test_simple(self):
- self.create_member(
- user=self.user, organization=self.organization, role="owner", teams=[self.team]
- )
- self.login_as(self.user)
- incident = self.create_incident()
- with self.feature("organizations:incidents"):
- self.get_success_response(self.organization.slug, incident.identifier, status_code=201)
- sub = IncidentSubscription.objects.filter(incident=incident, user_id=self.user.id).get()
- assert sub.incident == incident
- assert sub.user_id == self.user.id
-
-
-class OrganizationIncidentUnsubscribeEndpointTest(BaseOrganizationSubscriptionEndpointTest):
- method = "delete"
-
- def test_simple(self):
- self.create_member(
- user=self.user, organization=self.organization, role="owner", teams=[self.team]
- )
- self.login_as(self.user)
- incident = self.create_incident()
- subscribe_to_incident(incident, self.user.id)
- with self.feature("organizations:incidents"):
- self.get_success_response(self.organization.slug, incident.identifier, status_code=200)
- assert not IncidentSubscription.objects.filter(
- incident=incident, user_id=self.user.id
- ).exists()
|
1962b6e720bd2dce1b731b7f9156c2885e48f442
|
2025-01-03 22:09:12
|
Tony Xiao
|
fix: Missing optional chaining (#82860)
| false
|
Missing optional chaining (#82860)
|
fix
|
diff --git a/static/app/components/stream/group.tsx b/static/app/components/stream/group.tsx
index 47b9f6a62f336b..1268f8cb11862c 100644
--- a/static/app/components/stream/group.tsx
+++ b/static/app/components/stream/group.tsx
@@ -184,7 +184,7 @@ function BaseGroupRow({
const {period, start, end} = selection.datetime || {};
const summary =
- customStatsPeriod?.label.toLowerCase() ??
+ customStatsPeriod?.label?.toLowerCase() ??
(!!start && !!end
? 'time range'
: getRelativeSummary(period || DEFAULT_STATS_PERIOD).toLowerCase());
|
435cfdadc9f4f6f644963c82cfb55caa1be0a740
|
2020-05-15 12:07:39
|
Matej Minar
|
feat(ui): Improve release detail loading state (#18837)
| false
|
Improve release detail loading state (#18837)
|
feat
|
diff --git a/src/sentry/static/sentry/app/views/releasesV2/detail/index.tsx b/src/sentry/static/sentry/app/views/releasesV2/detail/index.tsx
index e034cec0411f51..19a9a87489307e 100644
--- a/src/sentry/static/sentry/app/views/releasesV2/detail/index.tsx
+++ b/src/sentry/static/sentry/app/views/releasesV2/detail/index.tsx
@@ -102,6 +102,14 @@ class ReleasesV2Detail extends AsyncView<Props, State> {
return super.renderError(...args);
}
+ renderLoading() {
+ return (
+ <PageContent>
+ <LoadingIndicator />
+ </PageContent>
+ );
+ }
+
renderBody() {
const {organization, location, selection, releaseProjects} = this.props;
const {release, deploys, reloading} = this.state;
@@ -175,6 +183,14 @@ class ReleasesV2DetailContainer extends AsyncComponent<Omit<Props, 'releaseProje
return !projectId || typeof projectId !== 'string';
}
+ renderLoading() {
+ return (
+ <PageContent>
+ <LoadingIndicator />
+ </PageContent>
+ );
+ }
+
renderProjectsFooterMessage() {
return (
<ProjectsFooterMessage>
|
8c6994eb8981ff51db49a4bd8bf5d66f4dfea17c
|
2022-11-16 04:04:21
|
Ryan Albrecht
|
ref(test): Convert eventOrGroupExtraDetails to typescript (#41376)
| false
|
Convert eventOrGroupExtraDetails to typescript (#41376)
|
ref
|
diff --git a/static/app/components/eventOrGroupExtraDetails.spec.jsx b/static/app/components/eventOrGroupExtraDetails.spec.jsx
deleted file mode 100644
index abad0f5494942e..00000000000000
--- a/static/app/components/eventOrGroupExtraDetails.spec.jsx
+++ /dev/null
@@ -1,131 +0,0 @@
-import {initializeOrg} from 'sentry-test/initializeOrg';
-import {render} from 'sentry-test/reactTestingLibrary';
-
-import EventOrGroupExtraDetails from 'sentry/components/eventOrGroupExtraDetails';
-
-describe('EventOrGroupExtraDetails', function () {
- const {routerContext} = initializeOrg();
-
- it('renders last and first seen', function () {
- const {container} = render(
- <EventOrGroupExtraDetails
- data={{
- orgId: 'orgId',
- projectId: 'projectId',
- groupId: 'groupId',
- lastSeen: '2017-07-25T22:56:12Z',
- firstSeen: '2017-07-01T02:06:02Z',
- }}
- />,
- {context: routerContext}
- );
-
- expect(container).toSnapshot();
- });
-
- it('renders only first seen', function () {
- const {container} = render(
- <EventOrGroupExtraDetails
- data={{
- orgId: 'orgId',
- projectId: 'projectId',
- groupId: 'groupId',
- firstSeen: '2017-07-01T02:06:02Z',
- }}
- />,
- {context: routerContext}
- );
-
- expect(container).toSnapshot();
- });
-
- it('renders only last seen', function () {
- const {container} = render(
- <EventOrGroupExtraDetails
- data={{
- orgId: 'orgId',
- projectId: 'projectId',
- groupId: 'groupId',
- lastSeen: '2017-07-25T22:56:12Z',
- }}
- />,
- {context: routerContext}
- );
-
- expect(container).toSnapshot();
- });
-
- it('renders all details', function () {
- const {container} = render(
- <EventOrGroupExtraDetails
- data={{
- orgId: 'orgId',
- projectId: 'projectId',
- groupId: 'groupId',
- lastSeen: '2017-07-25T22:56:12Z',
- firstSeen: '2017-07-01T02:06:02Z',
- numComments: 14,
- shortId: 'shortId',
- logger: 'javascript logger',
- annotations: ['annotation1', 'annotation2'],
- assignedTo: {
- name: 'Assignee Name',
- },
- status: 'resolved',
- }}
- />,
- {context: routerContext}
- );
-
- expect(container).toSnapshot();
- });
-
- it('renders assignee and status', function () {
- const {container} = render(
- <EventOrGroupExtraDetails
- data={{
- orgId: 'orgId',
- projectId: 'projectId',
- groupId: 'groupId',
- lastSeen: '2017-07-25T22:56:12Z',
- firstSeen: '2017-07-01T02:06:02Z',
- numComments: 14,
- shortId: 'shortId',
- logger: 'javascript logger',
- annotations: ['annotation1', 'annotation2'],
- assignedTo: {
- name: 'Assignee Name',
- },
- status: 'resolved',
- showStatus: true,
- }}
- showAssignee
- />,
- {context: routerContext}
- );
-
- expect(container).toSnapshot();
- });
-
- it('details when mentioned', function () {
- const {container} = render(
- <EventOrGroupExtraDetails
- data={{
- orgId: 'orgId',
- projectId: 'projectId',
- groupId: 'groupId',
- lastSeen: '2017-07-25T22:56:12Z',
- firstSeen: '2017-07-01T02:06:02Z',
- numComments: 14,
- shortId: 'shortId',
- logger: 'javascript logger',
- annotations: ['annotation1', 'annotation2'],
- subscriptionDetails: {reason: 'mentioned'},
- }}
- />,
- {context: routerContext}
- );
-
- expect(container).toSnapshot();
- });
-});
diff --git a/static/app/components/eventOrGroupExtraDetails.spec.tsx b/static/app/components/eventOrGroupExtraDetails.spec.tsx
new file mode 100644
index 00000000000000..4d79af31211dfd
--- /dev/null
+++ b/static/app/components/eventOrGroupExtraDetails.spec.tsx
@@ -0,0 +1,134 @@
+import {initializeOrg} from 'sentry-test/initializeOrg';
+import {render} from 'sentry-test/reactTestingLibrary';
+
+import EventOrGroupExtraDetails from 'sentry/components/eventOrGroupExtraDetails';
+import {Group} from 'sentry/types';
+
+describe('EventOrGroupExtraDetails', function () {
+ const {routerContext} = initializeOrg();
+
+ it('renders last and first seen', function () {
+ const {container} = render(
+ <EventOrGroupExtraDetails
+ data={
+ {
+ project: {id: 'projectId'},
+ id: 'groupId',
+ lastSeen: '2017-07-25T22:56:12Z',
+ firstSeen: '2017-07-01T02:06:02Z',
+ } as Group
+ }
+ />,
+ {context: routerContext}
+ );
+
+ expect(container).toSnapshot();
+ });
+
+ it('renders only first seen', function () {
+ const {container} = render(
+ <EventOrGroupExtraDetails
+ data={
+ {
+ project: {id: 'projectId'},
+ id: 'groupId',
+ firstSeen: '2017-07-01T02:06:02Z',
+ } as Group
+ }
+ />,
+ {context: routerContext}
+ );
+
+ expect(container).toSnapshot();
+ });
+
+ it('renders only last seen', function () {
+ const {container} = render(
+ <EventOrGroupExtraDetails
+ data={
+ {
+ project: {id: 'projectId'},
+ id: 'groupId',
+ lastSeen: '2017-07-25T22:56:12Z',
+ } as Group
+ }
+ />,
+ {context: routerContext}
+ );
+
+ expect(container).toSnapshot();
+ });
+
+ it('renders all details', function () {
+ const {container} = render(
+ <EventOrGroupExtraDetails
+ data={
+ {
+ id: 'groupId',
+ lastSeen: '2017-07-25T22:56:12Z',
+ firstSeen: '2017-07-01T02:06:02Z',
+ numComments: 14,
+ shortId: 'shortId',
+ logger: 'javascript logger',
+ annotations: ['annotation1', 'annotation2'],
+ assignedTo: {
+ name: 'Assignee Name',
+ },
+ status: 'resolved',
+ } as Group
+ }
+ />,
+ {context: routerContext}
+ );
+
+ expect(container).toSnapshot();
+ });
+
+ it('renders assignee and status', function () {
+ const {container} = render(
+ <EventOrGroupExtraDetails
+ data={
+ {
+ id: 'groupId',
+ lastSeen: '2017-07-25T22:56:12Z',
+ firstSeen: '2017-07-01T02:06:02Z',
+ numComments: 14,
+ shortId: 'shortId',
+ logger: 'javascript logger',
+ annotations: ['annotation1', 'annotation2'],
+ assignedTo: {
+ name: 'Assignee Name',
+ },
+ status: 'resolved',
+ } as Group
+ }
+ showAssignee
+ />,
+ {context: routerContext}
+ );
+
+ expect(container).toSnapshot();
+ });
+
+ it('details when mentioned', function () {
+ const {container} = render(
+ <EventOrGroupExtraDetails
+ data={
+ {
+ id: 'groupId',
+ lastSeen: '2017-07-25T22:56:12Z',
+ firstSeen: '2017-07-01T02:06:02Z',
+ numComments: 14,
+ shortId: 'shortId',
+ logger: 'javascript logger',
+ annotations: ['annotation1', 'annotation2'],
+ subscriptionDetails: {reason: 'mentioned'},
+ } as Group
+ }
+ />,
+ {context: routerContext}
+ );
+
+ expect(container).toSnapshot();
+ });
+});
|
b39d6ccdd15a4c3f14d173e1b694167466a1f442
|
2022-09-09 03:44:06
|
Ryan Skonnord
|
fix(hybrid): Add "pending_silo_endpoint" decorator (#38547)
| false
|
Add "pending_silo_endpoint" decorator (#38547)
|
fix
|
diff --git a/src/sentry/api/base.py b/src/sentry/api/base.py
index fa1cda5e62a5d1..57cfb55ef4cb17 100644
--- a/src/sentry/api/base.py
+++ b/src/sentry/api/base.py
@@ -43,6 +43,7 @@
"StatsMixin",
"control_silo_endpoint",
"customer_silo_endpoint",
+ "pending_silo_endpoint",
]
ONE_MINUTE = 60
@@ -497,7 +498,7 @@ def resolve_region(request: Request):
class EndpointSiloLimit(SiloLimit):
def modify_endpoint_class(self, decorated_class: Type[Endpoint]) -> type:
dispatch_override = self.create_override(decorated_class.dispatch)
- return type(
+ new_class = type(
decorated_class.__name__,
(decorated_class,),
{
@@ -505,6 +506,8 @@ def modify_endpoint_class(self, decorated_class: Type[Endpoint]) -> type:
"__silo_limit": self, # For internal tooling only
},
)
+ new_class.__module__ = decorated_class.__module__
+ return new_class
def modify_endpoint_method(self, decorated_method: Callable[..., Any]) -> Callable[..., Any]:
return self.create_override(decorated_method)
@@ -543,3 +546,10 @@ def __call__(self, decorated_obj: Any) -> Any:
control_silo_endpoint = EndpointSiloLimit(SiloMode.CONTROL)
customer_silo_endpoint = EndpointSiloLimit(SiloMode.CUSTOMER)
+
+# Use this decorator to mark endpoints that still need to be marked as either
+# control_silo_endpoint or customer_silo_endpoint. Marking a class with
+# pending_silo_endpoint keeps it from tripping SiloLimitCoverageTest, while ensuring
+# that the test will fail if a new endpoint is added with no decorator at all.
+# Eventually we should replace all instances of this decorator and delete it.
+pending_silo_endpoint = EndpointSiloLimit()
diff --git a/src/sentry/silo.py b/src/sentry/silo.py
index 7e7cb1b4094e94..809afeb83b679b 100644
--- a/src/sentry/silo.py
+++ b/src/sentry/silo.py
@@ -41,8 +41,6 @@ class SiloLimit(abc.ABC):
def __init__(self, *modes: SiloMode) -> None:
self.modes = frozenset(modes)
- if not self.modes:
- raise ValueError
@abc.abstractmethod
def __call__(self, decorated_object: Any) -> Any:
diff --git a/src/sentry/utils/silo/add_silo_decorators.py b/src/sentry/utils/silo/add_silo_decorators.py
index 04d05cc11db1b0..924b7867cb0b63 100644
--- a/src/sentry/utils/silo/add_silo_decorators.py
+++ b/src/sentry/utils/silo/add_silo_decorators.py
@@ -27,9 +27,7 @@ def execute(
predicate: Callable[[TargetClass], bool],
) -> None:
filtered_targets = (
- (c.module, c.name)
- for c in classes
- if c.category == category and not c.is_decorated and predicate(c)
+ (c.module, c.name) for c in classes if c.category == category and predicate(c)
)
apply_decorators(decorator_name, import_stmt, filtered_targets, path_name)
@@ -74,6 +72,12 @@ def control_endpoint_predicate(c: TargetClass) -> bool:
ClassCategory.ENDPOINT,
control_endpoint_predicate,
)
+ execute(
+ "pending_silo_endpoint",
+ "from sentry.api.base import pending_silo_endpoint",
+ ClassCategory.ENDPOINT,
+ (lambda c: not (customer_endpoint_predicate(c) or control_endpoint_predicate(c))),
+ )
@dataclass
diff --git a/src/sentry/utils/silo/audit_silo_decorators.py b/src/sentry/utils/silo/audit_silo_decorators.py
index 6a19a19435763b..c928233098d537 100644
--- a/src/sentry/utils/silo/audit_silo_decorators.py
+++ b/src/sentry/utils/silo/audit_silo_decorators.py
@@ -58,7 +58,7 @@ def get_endpoint_classes():
if not endpoint_class.__module__.startswith(app_label):
continue
limit = getattr(endpoint_class, "__silo_limit", None)
- key = limit.modes if limit else None
+ key = frozenset(limit.modes if limit else ())
table[key].append(endpoint_class)
return table
diff --git a/src/sentry/utils/silo/common.py b/src/sentry/utils/silo/common.py
index 74274b79c70e7c..6f57c9f28725ca 100644
--- a/src/sentry/utils/silo/common.py
+++ b/src/sentry/utils/silo/common.py
@@ -2,6 +2,7 @@
import os
import re
+from collections import defaultdict
from dataclasses import dataclass
from enum import Enum, auto
from typing import Iterable, Mapping, Sequence, Tuple
@@ -25,11 +26,30 @@ def find_source_paths():
yield os.path.join(dirpath, filename)
def find_class_declarations():
+ """Find the target class declarations.
+
+ For each module-class pair in `target_names`, check the Python source file
+ corresponding to that module. If the named class is declared in that module,
+ yield it.
+ """
+ targets = defaultdict(set)
+ for (module_name, class_name) in target_names:
+ targets[class_name].add(module_name)
+
for src_path in find_source_paths():
with open(src_path) as f:
src_code = f.read()
- for match in re.findall(r"\nclass\s+(\w+)\(", src_code):
- yield src_path, match
+ for class_name in re.findall(r"\nclass\s+(\w+)\(", src_code):
+ for module_name in targets[class_name]:
+ if is_module(src_path, module_name):
+ yield src_path, class_name
+
+ def is_module(src_path: str, module_name: str) -> bool:
+ """Check whether a source file path is for the correct module."""
+ suffix = ".py"
+ return src_path.endswith(suffix) and (
+ src_path[: -len(suffix)].replace("/", ".").endswith(module_name)
+ )
def insert_import(src_code: str) -> str:
future_import = None
@@ -41,24 +61,40 @@ def insert_import(src_code: str) -> str:
else:
return import_stmt + "\n" + src_code
- def is_module(src_path: str, module_name: str | None) -> bool:
- if module_name is None:
- return False
- suffix = ".py"
- return src_path.endswith(suffix) and (
- src_path[: -len(suffix)].replace("/", ".").endswith(module_name)
+ for src_path, class_name in find_class_declarations():
+ with open(src_path) as f:
+ src_code = f.read()
+ decorator_is_new = False
+
+ def replace(match):
+ nonlocal decorator_is_new
+
+ existing_decorator, class_decl = match.groups()
+ if existing_decorator == decorator_name:
+ return match.group()
+ decorator_is_new = True
+ return f"\n@{decorator_name}\n{class_decl}"
+
+ # Try to detect a pre-existing decorator, if possible, and replace it if it
+ # doesn't match the decorator we are trying to add. This works only if the
+ # decorator is immediately above the class, which is usually a safe
+ # assumption because that's where this script writes it. In the long run,
+ # it could be disrupted by the insertion of a comment, another unrelated
+ # decorator, or such.
+ new_code = re.sub(
+ (
+ r"(?:\n@((?:control|customer|pending)_silo_(?:model|endpoint|test)))?"
+ rf"\n(class\s+{class_name}\()"
+ ),
+ replace,
+ src_code,
)
- targets = {class_name: module_name for (module_name, class_name) in target_names}
- for src_path, class_name in find_class_declarations():
- if is_module(src_path, targets.get(class_name)):
- with open(src_path) as f:
- src_code = f.read()
- new_code = re.sub(
- rf"\nclass\s+{class_name}\(",
- rf"\n@{decorator_name}\g<0>",
- src_code,
- )
+ if decorator_is_new:
+ # Naively insert a new import statement. This may add duplicate import
+ # statements if we decorate more than one class in the same file,
+ # or leave behind an old import statement if we are replacing an existing
+ # decorator. Rely on pre-commit hooks or IDE tools to clean it up.
new_code = insert_import(new_code)
with open(src_path, mode="w") as f:
f.write(new_code)
|
95837ea7835dd9cd234a49f32250e333a71ff9f6
|
2021-05-19 00:17:53
|
Alberto Leal
|
chore: Remove unused trace hover card (#26089)
| false
|
Remove unused trace hover card (#26089)
|
chore
|
diff --git a/static/app/components/events/eventTags/eventTags.tsx b/static/app/components/events/eventTags/eventTags.tsx
index 59f2f335a5ea44..fc5244897f6d5e 100644
--- a/static/app/components/events/eventTags/eventTags.tsx
+++ b/static/app/components/events/eventTags/eventTags.tsx
@@ -44,7 +44,6 @@ const EventTags = ({
tag={tag}
projectId={projectId}
organization={organization}
- location={location}
query={generateQueryWithTag(location.query, tag)}
streamPath={streamPath}
releasesPath={releasesPath}
diff --git a/static/app/components/events/eventTags/eventTagsPill.tsx b/static/app/components/events/eventTags/eventTagsPill.tsx
index c8c2f2f4aa2273..f9c27de9961934 100644
--- a/static/app/components/events/eventTags/eventTagsPill.tsx
+++ b/static/app/components/events/eventTags/eventTagsPill.tsx
@@ -1,6 +1,6 @@
import {Link} from 'react-router';
import {css} from '@emotion/react';
-import {Location, Query} from 'history';
+import {Query} from 'history';
import * as queryString from 'query-string';
import AnnotatedText from 'app/components/events/meta/annotatedText';
@@ -12,7 +12,6 @@ import {IconInfo, IconOpen} from 'app/icons';
import {Organization} from 'app/types';
import {EventTag} from 'app/types/event';
import {isUrl} from 'app/utils';
-import TraceHoverCard from 'app/utils/discover/traceHoverCard';
import EventTagsPillValue from './eventTagsPillValue';
@@ -26,7 +25,6 @@ type Props = {
streamPath: string;
releasesPath: string;
query: Query;
- location: Location;
organization: Organization;
projectId: string;
hasQueryFeature: boolean;
@@ -39,13 +37,10 @@ const EventTagsPill = ({
projectId,
streamPath,
releasesPath,
- location,
- hasQueryFeature,
}: Props) => {
const locationSearch = `?${queryString.stringify(query)}`;
const {key, value} = tag;
const isRelease = key === 'release';
- const isTrace = key === 'trace';
const name = !key ? <AnnotatedText value={key} meta={getMeta(tag, 'key')} /> : key;
const type = !key ? 'error' : undefined;
@@ -76,22 +71,6 @@ const EventTagsPill = ({
</VersionHoverCard>
</div>
)}
- {isTrace && hasQueryFeature && (
- <TraceHoverCard
- containerClassName="pill-icon"
- traceId={value}
- orgSlug={organization.slug}
- location={location}
- >
- {({to}) => {
- return (
- <Link to={to}>
- <IconOpen size="xs" css={iconStyle} />
- </Link>
- );
- }}
- </TraceHoverCard>
- )}
</Pill>
);
};
diff --git a/static/app/utils/discover/traceHoverCard.tsx b/static/app/utils/discover/traceHoverCard.tsx
deleted file mode 100644
index 1227abb70e8e8e..00000000000000
--- a/static/app/utils/discover/traceHoverCard.tsx
+++ /dev/null
@@ -1,199 +0,0 @@
-import * as React from 'react';
-import styled from '@emotion/styled';
-import {Location, LocationDescriptor} from 'history';
-
-import {Client} from 'app/api';
-import Clipboard from 'app/components/clipboard';
-import Hovercard from 'app/components/hovercard';
-import LoadingError from 'app/components/loadingError';
-import LoadingIndicator from 'app/components/loadingIndicator';
-import Version from 'app/components/version';
-import {IconCopy} from 'app/icons';
-import {t} from 'app/locale';
-import space from 'app/styles/space';
-import {Organization} from 'app/types';
-import withApi from 'app/utils/withApi';
-
-import DiscoverQuery, {TableData} from './discoverQuery';
-import EventView from './eventView';
-
-type ChildrenProps = {to: LocationDescriptor};
-
-type Props = {
- api: Client;
-
- orgSlug: Organization['slug'];
- traceId: string;
-
- location: Location;
-
- children: (props: ChildrenProps) => React.ReactNode;
-
- // hover card props
- containerClassName: string;
-};
-
-class TraceHoverCard extends React.Component<Props> {
- renderHeader() {
- const {traceId} = this.props;
-
- return (
- <HeaderWrapper>
- <span>{t('Trace')}</span>
- <TraceWrapper>
- <StyledTrace version={traceId} truncate anchor={false} />
- <Clipboard value={traceId}>
- <ClipboardIconWrapper>
- <IconCopy size="xs" />
- </ClipboardIconWrapper>
- </Clipboard>
- </TraceWrapper>
- </HeaderWrapper>
- );
- }
-
- renderBody({
- tableData,
- isLoading,
- error,
- }: {
- tableData: TableData | null;
- isLoading: boolean;
- error: null | string;
- }) {
- if (isLoading) {
- return (
- <LoadingWrapper>
- <LoadingIndicator mini />
- </LoadingWrapper>
- );
- }
-
- if (error) {
- return <LoadingError />;
- }
-
- if (!tableData) {
- return null;
- }
-
- let numOfTransactions = 0;
- let numOfErrors = 0;
- // aggregate transaction and error (default, csp, error) counts
- for (const row of tableData.data) {
- if (row['event.type'] === 'transaction') {
- numOfTransactions = (row.count as number) ?? 0;
- } else {
- numOfErrors += (row.count as number) ?? 0;
- }
- }
-
- return (
- <CardBodyWrapper>
- <EventCountWrapper>
- <h6>{t('Transactions')}</h6>
- <div className="count-since">{numOfTransactions.toLocaleString()}</div>
- </EventCountWrapper>
- <EventCountWrapper>
- <h6>{t('Errors')}</h6>
- <div className="count-since">{numOfErrors.toLocaleString()}</div>
- </EventCountWrapper>
- </CardBodyWrapper>
- );
- }
-
- render() {
- const {traceId, location, api, orgSlug} = this.props;
-
- // used to fetch number of transactions to display in hovercard
- const numTransactionsEventView = EventView.fromNewQueryWithLocation(
- {
- id: undefined,
- name: `Transactions with Trace ID ${traceId}`,
- fields: ['event.type', 'count()'],
- query: `trace:${traceId}`,
- projects: [],
- version: 2,
- },
- location
- );
-
- // used to create link to discover page with relevant query
- const traceEventView = EventView.fromNewQueryWithLocation(
- {
- id: undefined,
- name: `Events with Trace ID ${traceId}`,
- fields: ['transaction', 'project', 'trace.span', 'event.type', 'timestamp'],
- orderby: '-timestamp',
- query: `trace:${traceId}`,
- projects: [],
- version: 2,
- },
- location
- );
-
- const to = traceEventView.getResultsViewUrlTarget(orgSlug);
-
- return (
- <DiscoverQuery
- api={api}
- location={location}
- eventView={numTransactionsEventView}
- orgSlug={orgSlug}
- referrer="api.trace-view.hover-card"
- >
- {({isLoading, error, tableData}) => {
- return (
- <Hovercard
- {...this.props}
- header={this.renderHeader()}
- body={this.renderBody({isLoading, error, tableData})}
- >
- {this.props.children({to})}
- </Hovercard>
- );
- }}
- </DiscoverQuery>
- );
- }
-}
-
-const HeaderWrapper = styled('div')`
- display: flex;
- align-items: center;
- justify-content: space-between;
-`;
-
-const TraceWrapper = styled('div')`
- display: flex;
- flex: 1;
- align-items: center;
- justify-content: flex-end;
-`;
-
-const StyledTrace = styled(Version)`
- margin-right: ${space(0.5)};
- max-width: 190px;
-`;
-
-const ClipboardIconWrapper = styled('span')`
- &:hover {
- cursor: pointer;
- }
-`;
-
-const LoadingWrapper = styled('div')`
- display: flex;
- align-items: center;
- justify-content: center;
-`;
-
-const CardBodyWrapper = styled('div')`
- display: flex;
-`;
-
-const EventCountWrapper = styled('div')`
- flex: 1;
-`;
-
-export default withApi(TraceHoverCard);
diff --git a/static/app/views/performance/traceDetails/styles.tsx b/static/app/views/performance/traceDetails/styles.tsx
index 6445a01db590be..0227e91b8e2c95 100644
--- a/static/app/views/performance/traceDetails/styles.tsx
+++ b/static/app/views/performance/traceDetails/styles.tsx
@@ -110,7 +110,6 @@ export function Tags({
tag={tag}
projectId={transaction.project_slug}
organization={organization}
- location={location}
query={query}
streamPath={streamPath}
releasesPath={releasesPath}
|
a2f243ee8beaa90418fb00759b25600585e06e30
|
2023-08-30 13:24:10
|
ArthurKnaus
|
feat(onboarding): Add profiling platform python (others) (#55346)
| false
|
Add profiling platform python (others) (#55346)
|
feat
|
diff --git a/static/app/components/onboarding/productSelection.tsx b/static/app/components/onboarding/productSelection.tsx
index 1cebe3716888ed..a2b8b4b20978f7 100644
--- a/static/app/components/onboarding/productSelection.tsx
+++ b/static/app/components/onboarding/productSelection.tsx
@@ -64,7 +64,31 @@ export const platformProductAvailability = {
ProductSolution.SESSION_REPLAY,
],
python: [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
+ 'python-aiohttp': [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
+ 'python-awslambda': [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
+ 'python-bottle': [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
+ 'python-celery': [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
+ 'python-chalice': [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
'python-django': [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
+ 'python-falcon': [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
+ 'python-fastapi': [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
+ 'python-flask': [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
+ 'python-gcpfunctions': [
+ ProductSolution.PERFORMANCE_MONITORING,
+ ProductSolution.PROFILING,
+ ],
+ 'python-pyramid': [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
+ 'python-quart': [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
+ 'python-rq': [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
+ 'python-sanic': [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
+ 'python-serverless': [
+ ProductSolution.PERFORMANCE_MONITORING,
+ ProductSolution.PROFILING,
+ ],
+ 'python-tornado': [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
+ 'python-starlette': [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
+ 'python-tryton': [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
+ 'python-wsgi': [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING],
} as Record<PlatformKey, ProductSolution[]>;
export type DisabledProduct = {
diff --git a/static/app/data/platformCategories.tsx b/static/app/data/platformCategories.tsx
index 56821296beadd2..7f7884d0f199e4 100644
--- a/static/app/data/platformCategories.tsx
+++ b/static/app/data/platformCategories.tsx
@@ -112,6 +112,12 @@ export const backend = [
'python-starlette',
'python-sanic',
'python-celery',
+ 'python-aiohttp',
+ 'python-chalice',
+ 'python-falcon',
+ 'python-quart',
+ 'python-tryton',
+ 'python-wsgi',
'python-bottle',
'python-pylons',
'python-pyramid',
@@ -129,6 +135,7 @@ export const serverless = [
'python-awslambda',
'python-azurefunctions',
'python-gcpfunctions',
+ 'python-serverless',
'node-awslambda',
'node-azurefunctions',
'node-gcpfunctions',
diff --git a/static/app/gettingStartedDocs/python/aiohttp.spec.tsx b/static/app/gettingStartedDocs/python/aiohttp.spec.tsx
index c1b9ddf6a4d0ec..a92dea7e96b6e5 100644
--- a/static/app/gettingStartedDocs/python/aiohttp.spec.tsx
+++ b/static/app/gettingStartedDocs/python/aiohttp.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithAIOHTTP', function () {
const {container} = render(<GettingStartedWithAIOHTTP dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/aiohttp.tsx b/static/app/gettingStartedDocs/python/aiohttp.tsx
index acea5ca5c2cf7f..b45cc5b1c44f16 100644
--- a/static/app/gettingStartedDocs/python/aiohttp.tsx
+++ b/static/app/gettingStartedDocs/python/aiohttp.tsx
@@ -2,9 +2,21 @@ import ExternalLink from 'sentry/components/links/externalLink';
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {t, tct} from 'sentry/locale';
// Configuration Start
+
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
+
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
+
const introduction = (
<p>
{tct(
@@ -17,8 +29,10 @@ const introduction = (
);
export const steps = ({
- dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.INSTALL,
description: (
@@ -60,15 +74,7 @@ import sentry_sdk
from sentry_sdk.integrations.aiohttp import AioHttpIntegration
sentry_sdk.init(
- dsn="${dsn}",
- integrations=[
- AioHttpIntegration(),
- ],
-
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
+${sentryInitContent}
)
from aiohttp import web
@@ -87,8 +93,37 @@ web.run_app(app)
];
// Configuration End
-export function GettingStartedWithAIOHTTP({dsn, ...props}: ModuleProps) {
- return <Layout steps={steps({dsn})} introduction={introduction} {...props} />;
+export function GettingStartedWithAIOHTTP({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [
+ ` dsn="${dsn}",`,
+ ` integrations=[AioHttpIntegration()],`,
+ ];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
+ return (
+ <Layout
+ introduction={introduction}
+ steps={steps({
+ sentryInitContent: sentryInitContent.join('\n'),
+ })}
+ {...props}
+ />
+ );
}
export default GettingStartedWithAIOHTTP;
diff --git a/static/app/gettingStartedDocs/python/awslambda.spec.tsx b/static/app/gettingStartedDocs/python/awslambda.spec.tsx
index 3406c669bf5898..19acf6ddd1afee 100644
--- a/static/app/gettingStartedDocs/python/awslambda.spec.tsx
+++ b/static/app/gettingStartedDocs/python/awslambda.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithAwsLambda', function () {
const {container} = render(<GettingStartedWithAwsLambda dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content', dsn: 'test-dsn'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/awslambda.tsx b/static/app/gettingStartedDocs/python/awslambda.tsx
index f2563efc656390..14bc04cfe49634 100644
--- a/static/app/gettingStartedDocs/python/awslambda.tsx
+++ b/static/app/gettingStartedDocs/python/awslambda.tsx
@@ -6,10 +6,22 @@ import ExternalLink from 'sentry/components/links/externalLink';
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {t, tct} from 'sentry/locale';
import {space} from 'sentry/styles/space';
// Configuration Start
+
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
+
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
+
const introduction = (
<p>
{tct(
@@ -25,7 +37,11 @@ const introduction = (
export const steps = ({
dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ dsn: string;
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.INSTALL,
description: (
@@ -51,15 +67,7 @@ import sentry_sdk
from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration
sentry_sdk.init(
- dsn="${dsn}",
- integrations=[
- AwsLambdaIntegration(),
- ],
-
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
+${sentryInitContent}
)
def my_function(event, context):
@@ -108,10 +116,6 @@ sentry_sdk.init(
integrations=[
AwsLambdaIntegration(timeout_warning=True),
],
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
)
`,
},
@@ -123,10 +127,35 @@ sentry_sdk.init(
];
// Configuration End
-export function GettingStartedWithAwsLambda({dsn, ...props}: ModuleProps) {
+export function GettingStartedWithAwsLambda({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [
+ ` dsn="${dsn}",`,
+ ` integrations=[AwsLambdaIntegration()],`,
+ ];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
return (
<Fragment>
- <Layout steps={steps({dsn})} introduction={introduction} {...props} />
+ <Layout
+ introduction={introduction}
+ steps={steps({dsn, sentryInitContent: sentryInitContent.join('\n')})}
+ {...props}
+ />
<AlertWithMarginBottom type="info">
{tct(
'If you are using another web framework inside of AWS Lambda, the framework might catch those exceptions before we get to see them. Make sure to enable the framework specific integration as well, if one exists. See [link:Integrations] for more information.',
diff --git a/static/app/gettingStartedDocs/python/bottle.spec.tsx b/static/app/gettingStartedDocs/python/bottle.spec.tsx
index f9260a6a640182..052731acba579b 100644
--- a/static/app/gettingStartedDocs/python/bottle.spec.tsx
+++ b/static/app/gettingStartedDocs/python/bottle.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithBottle', function () {
const {container} = render(<GettingStartedWithBottle dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/bottle.tsx b/static/app/gettingStartedDocs/python/bottle.tsx
index bab134199e265e..04ab294cb9f1da 100644
--- a/static/app/gettingStartedDocs/python/bottle.tsx
+++ b/static/app/gettingStartedDocs/python/bottle.tsx
@@ -2,9 +2,21 @@ import ExternalLink from 'sentry/components/links/externalLink';
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {t, tct} from 'sentry/locale';
// Configuration Start
+
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
+
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
+
const introduction = (
<p>
{tct(
@@ -17,8 +29,10 @@ const introduction = (
);
export const steps = ({
- dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.INSTALL,
description: (
@@ -54,14 +68,7 @@ from bottle import Bottle, run
from sentry_sdk.integrations.bottle import BottleIntegration
sentry_sdk.init(
- dsn="${dsn}",
- integrations=[
- BottleIntegration(),
- ],
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
+${sentryInitContent}
)
app = Bottle()
@@ -72,8 +79,37 @@ app = Bottle()
];
// Configuration End
-export function GettingStartedWithBottle({dsn, ...props}: ModuleProps) {
- return <Layout steps={steps({dsn})} introduction={introduction} {...props} />;
+export function GettingStartedWithBottle({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [
+ ` dsn="${dsn}",`,
+ ` integrations=[BottleIntegration()],`,
+ ];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
+ return (
+ <Layout
+ introduction={introduction}
+ steps={steps({
+ sentryInitContent: sentryInitContent.join('\n'),
+ })}
+ {...props}
+ />
+ );
}
export default GettingStartedWithBottle;
diff --git a/static/app/gettingStartedDocs/python/celery.spec.tsx b/static/app/gettingStartedDocs/python/celery.spec.tsx
index 6f63b36600bfda..3b7622b6d77091 100644
--- a/static/app/gettingStartedDocs/python/celery.spec.tsx
+++ b/static/app/gettingStartedDocs/python/celery.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithCelery', function () {
const {container} = render(<GettingStartedWithCelery dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/celery.tsx b/static/app/gettingStartedDocs/python/celery.tsx
index 53ebe57dea3e0a..87edc336e6dbc5 100644
--- a/static/app/gettingStartedDocs/python/celery.tsx
+++ b/static/app/gettingStartedDocs/python/celery.tsx
@@ -4,9 +4,21 @@ import ExternalLink from 'sentry/components/links/externalLink';
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {t, tct} from 'sentry/locale';
// Configuration Start
+
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
+
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
+
const introduction = (
<p>
{tct('The celery integration adds support for the [link:Celery Task Queue System].', {
@@ -16,8 +28,10 @@ const introduction = (
);
export const steps = ({
- dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.CONFIGURE,
description: (
@@ -39,15 +53,7 @@ import sentry_sdk
from sentry_sdk.integrations.celery import CeleryIntegration
sentry_sdk.init(
- dsn='${dsn}',
- integrations=[
- CeleryIntegration(),
- ],
-
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
+${sentryInitContent}
)
`,
},
@@ -66,8 +72,37 @@ sentry_sdk.init(
];
// Configuration End
-export function GettingStartedWithCelery({dsn, ...props}: ModuleProps) {
- return <Layout steps={steps({dsn})} introduction={introduction} {...props} />;
+export function GettingStartedWithCelery({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [
+ ` dsn="${dsn}",`,
+ ` integrations=[CeleryIntegration()],`,
+ ];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
+ return (
+ <Layout
+ introduction={introduction}
+ steps={steps({
+ sentryInitContent: sentryInitContent.join('\n'),
+ })}
+ {...props}
+ />
+ );
}
export default GettingStartedWithCelery;
diff --git a/static/app/gettingStartedDocs/python/chalice.spec.tsx b/static/app/gettingStartedDocs/python/chalice.spec.tsx
index 954771244c5cd5..d6228184d05d8e 100644
--- a/static/app/gettingStartedDocs/python/chalice.spec.tsx
+++ b/static/app/gettingStartedDocs/python/chalice.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithChalice', function () {
const {container} = render(<GettingStartedWithChalice dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/chalice.tsx b/static/app/gettingStartedDocs/python/chalice.tsx
index 24c1c97a6ec997..d28d32db0d36ca 100644
--- a/static/app/gettingStartedDocs/python/chalice.tsx
+++ b/static/app/gettingStartedDocs/python/chalice.tsx
@@ -1,13 +1,26 @@
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {tct} from 'sentry/locale';
// Configuration Start
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
+
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
+
export const steps = ({
- dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.INSTALL,
description: (
@@ -37,15 +50,7 @@ from sentry_sdk.integrations.chalice import ChaliceIntegration
sentry_sdk.init(
- dsn="${dsn}",
- integrations=[
- ChaliceIntegration(),
- ],
-
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
+${sentryInitContent}
)
app = Chalice(app_name="appname")
@@ -56,8 +61,35 @@ app = Chalice(app_name="appname")
];
// Configuration End
-export function GettingStartedWithChalice({dsn, ...props}: ModuleProps) {
- return <Layout steps={steps({dsn})} {...props} />;
-}
+export function GettingStartedWithChalice({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [
+ ` dsn="${dsn}",`,
+ ` integrations=[ChaliceIntegration()],`,
+ ];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
+ return (
+ <Layout
+ steps={steps({
+ sentryInitContent: sentryInitContent.join('\n'),
+ })}
+ {...props}
+ />
+ );
+}
export default GettingStartedWithChalice;
diff --git a/static/app/gettingStartedDocs/python/django.tsx b/static/app/gettingStartedDocs/python/django.tsx
index 5062654d390ba3..9fab29d4c37d60 100644
--- a/static/app/gettingStartedDocs/python/django.tsx
+++ b/static/app/gettingStartedDocs/python/django.tsx
@@ -7,19 +7,19 @@ import {t, tct} from 'sentry/locale';
// Configuration Start
-const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
- # of sampled transactions.
- # We recommend adjusting this value in production.
- profiles_sample_rate=1.0,`;
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
-const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production.
- traces_sample_rate=1.0,`;
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
-const piiConfiguration = ` # If you wish to associate users to errors (assuming you are using
- # django.contrib.auth) you may enable sending PII data.
- send_default_pii=True,`;
+const piiConfiguration = ` # If you wish to associate users to errors (assuming you are using
+ # django.contrib.auth) you may enable sending PII data.
+ send_default_pii=True,`;
export const steps = ({
sentryInitContent,
@@ -80,12 +80,12 @@ ${sentryInitContent}
from django.urls import path
def trigger_error(request):
- division_by_zero = 1 / 0
+ division_by_zero = 1 / 0
- urlpatterns = [
- path('sentry-debug/', trigger_error),
- # ...
- ]
+ urlpatterns = [
+ path('sentry-debug/', trigger_error),
+ # ...
+ ]
`,
},
],
@@ -104,8 +104,8 @@ export function GettingStartedWithDjango({
const otherConfigs: string[] = [];
let sentryInitContent: string[] = [
- ` dsn="${dsn}",`,
- ` integrations=[DjangoIntegration()],`,
+ ` dsn="${dsn}",`,
+ ` integrations=[DjangoIntegration()],`,
piiConfiguration,
];
diff --git a/static/app/gettingStartedDocs/python/falcon.spec.tsx b/static/app/gettingStartedDocs/python/falcon.spec.tsx
index 5f27afdc562610..1c888ed1c2a673 100644
--- a/static/app/gettingStartedDocs/python/falcon.spec.tsx
+++ b/static/app/gettingStartedDocs/python/falcon.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithFalcon', function () {
const {container} = render(<GettingStartedWithFalcon dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/falcon.tsx b/static/app/gettingStartedDocs/python/falcon.tsx
index e3fa713c34eebd..6c0617c34a94d4 100644
--- a/static/app/gettingStartedDocs/python/falcon.tsx
+++ b/static/app/gettingStartedDocs/python/falcon.tsx
@@ -2,9 +2,21 @@ import ExternalLink from 'sentry/components/links/externalLink';
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {t, tct} from 'sentry/locale';
// Configuration Start
+
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
+
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
+
const introduction = (
<p>
{tct(
@@ -17,8 +29,10 @@ const introduction = (
);
export const steps = ({
- dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.INSTALL,
description: (
@@ -53,15 +67,7 @@ import sentry_sdk
from sentry_sdk.integrations.falcon import FalconIntegration
sentry_sdk.init(
- dsn="${dsn}",
- integrations=[
- FalconIntegration(),
- ],
-
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
+${sentryInitContent}
)
api = falcon.API()
@@ -72,8 +78,37 @@ api = falcon.API()
];
// Configuration End
-export function GettingStartedWithFalcon({dsn, ...props}: ModuleProps) {
- return <Layout steps={steps({dsn})} introduction={introduction} {...props} />;
+export function GettingStartedWithFalcon({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [
+ ` dsn="${dsn}",`,
+ ` integrations=[FalconIntegration()],`,
+ ];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
+ return (
+ <Layout
+ introduction={introduction}
+ steps={steps({
+ sentryInitContent: sentryInitContent.join('\n'),
+ })}
+ {...props}
+ />
+ );
}
export default GettingStartedWithFalcon;
diff --git a/static/app/gettingStartedDocs/python/fastapi.spec.tsx b/static/app/gettingStartedDocs/python/fastapi.spec.tsx
index e836ef82b995d5..8eb49e13340da5 100644
--- a/static/app/gettingStartedDocs/python/fastapi.spec.tsx
+++ b/static/app/gettingStartedDocs/python/fastapi.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithFastApi', function () {
const {container} = render(<GettingStartedWithFastApi dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/fastapi.tsx b/static/app/gettingStartedDocs/python/fastapi.tsx
index c8a8c3c7f0af0f..b6fdefe1e2ced0 100644
--- a/static/app/gettingStartedDocs/python/fastapi.tsx
+++ b/static/app/gettingStartedDocs/python/fastapi.tsx
@@ -2,9 +2,21 @@ import ExternalLink from 'sentry/components/links/externalLink';
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {t, tct} from 'sentry/locale';
// Configuration Start
+
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
+
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
+
const introduction = (
<p>
{tct('The FastAPI integration adds support for the [link:FastAPI Framework].', {
@@ -14,8 +26,10 @@ const introduction = (
);
export const steps = ({
- dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.INSTALL,
description: (
@@ -51,12 +65,7 @@ import sentry_sdk
sentry_sdk.init(
- dsn="${dsn}",
-
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
+${sentryInitContent}
)
app = FastAPI()
@@ -100,8 +109,34 @@ division_by_zero = 1 / 0
];
// Configuration End
-export function GettingStartedWithFastApi({dsn, ...props}: ModuleProps) {
- return <Layout steps={steps({dsn})} introduction={introduction} {...props} />;
+export function GettingStartedWithFastApi({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [` dsn="${dsn}",`];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
+ return (
+ <Layout
+ introduction={introduction}
+ steps={steps({
+ sentryInitContent: sentryInitContent.join('\n'),
+ })}
+ {...props}
+ />
+ );
}
export default GettingStartedWithFastApi;
diff --git a/static/app/gettingStartedDocs/python/flask.spec.tsx b/static/app/gettingStartedDocs/python/flask.spec.tsx
index d3495777731c22..39ab492bc57642 100644
--- a/static/app/gettingStartedDocs/python/flask.spec.tsx
+++ b/static/app/gettingStartedDocs/python/flask.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithDjango', function () {
const {container} = render(<GettingStartedWithFlask dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/flask.tsx b/static/app/gettingStartedDocs/python/flask.tsx
index 83ad6ba926c975..d29e46d5e94d43 100644
--- a/static/app/gettingStartedDocs/python/flask.tsx
+++ b/static/app/gettingStartedDocs/python/flask.tsx
@@ -2,12 +2,26 @@ import ExternalLink from 'sentry/components/links/externalLink';
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {t, tct} from 'sentry/locale';
// Configuration Start
+
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
+
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
+
export const steps = ({
- dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.INSTALL,
description: (
@@ -54,15 +68,7 @@ from flask import Flask
from sentry_sdk.integrations.flask import FlaskIntegration
sentry_sdk.init(
- dsn="${dsn}",
- integrations=[
- FlaskIntegration(),
- ],
-
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production.
- traces_sample_rate=1.0
+${sentryInitContent}
)
app = Flask(__name__)
@@ -100,8 +106,36 @@ def trigger_error():
];
// Configuration End
-export function GettingStartedWithFlask({dsn, ...props}: ModuleProps) {
- return <Layout steps={steps({dsn})} {...props} />;
+export function GettingStartedWithFlask({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [
+ ` dsn="${dsn}",`,
+ ` integrations=[FlaskIntegration()],`,
+ ];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
+ return (
+ <Layout
+ steps={steps({
+ sentryInitContent: sentryInitContent.join('\n'),
+ })}
+ {...props}
+ />
+ );
}
export default GettingStartedWithFlask;
diff --git a/static/app/gettingStartedDocs/python/gcpfunctions.spec.tsx b/static/app/gettingStartedDocs/python/gcpfunctions.spec.tsx
index febad135a18a42..f24fddcfdaa53e 100644
--- a/static/app/gettingStartedDocs/python/gcpfunctions.spec.tsx
+++ b/static/app/gettingStartedDocs/python/gcpfunctions.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithGCPFunctions', function () {
const {container} = render(<GettingStartedWithGCPFunctions dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content', dsn: 'test-dsn'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/gcpfunctions.tsx b/static/app/gettingStartedDocs/python/gcpfunctions.tsx
index 31a165a0698c12..2c2b3189ffe614 100644
--- a/static/app/gettingStartedDocs/python/gcpfunctions.tsx
+++ b/static/app/gettingStartedDocs/python/gcpfunctions.tsx
@@ -6,13 +6,29 @@ import ExternalLink from 'sentry/components/links/externalLink';
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {t, tct} from 'sentry/locale';
import {space} from 'sentry/styles/space';
// Configuration Start
+
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
+
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
+
export const steps = ({
dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ dsn: string;
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.INSTALL,
description: (
@@ -38,19 +54,11 @@ import sentry_sdk
from sentry_sdk.integrations.gcp import GcpIntegration
sentry_sdk.init(
- dsn="${dsn}",
- integrations=[
- GcpIntegration(),
- ],
-
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
+${sentryInitContent}
)
def http_function_entrypoint(request):
- ...
+ ...
`,
},
],
@@ -91,15 +99,10 @@ def http_function_entrypoint(request):
language: 'python',
code: `
sentry_sdk.init(
- dsn="${dsn}",
- integrations=[
- GcpIntegration(timeout_warning=True),
- ],
-
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
+ dsn="${dsn}",
+ integrations=[
+ GcpIntegration(timeout_warning=True),
+ ],
)
`,
},
@@ -111,10 +114,34 @@ sentry_sdk.init(
];
// Configuration End
-export function GettingStartedWithGCPFunctions({dsn, ...props}: ModuleProps) {
+export function GettingStartedWithGCPFunctions({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [
+ ` dsn="${dsn}",`,
+ ` integrations=[GcpIntegration()],`,
+ ];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
return (
<Fragment>
- <Layout steps={steps({dsn})} {...props} />
+ <Layout
+ steps={steps({dsn, sentryInitContent: sentryInitContent.join('\n')})}
+ {...props}
+ />
<AlertWithMarginBottom type="info">
{tct(
'If you are using a web framework in your Cloud Function, the framework might catch those exceptions before we get to see them. Make sure to enable the framework specific integration as well, if one exists. See [link:Integrations] for more information.',
diff --git a/static/app/gettingStartedDocs/python/pyramid.spec.tsx b/static/app/gettingStartedDocs/python/pyramid.spec.tsx
index ff05c418454580..d2019c494a2cb0 100644
--- a/static/app/gettingStartedDocs/python/pyramid.spec.tsx
+++ b/static/app/gettingStartedDocs/python/pyramid.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithPyramid', function () {
const {container} = render(<GettingStartedWithPyramid dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/pyramid.tsx b/static/app/gettingStartedDocs/python/pyramid.tsx
index 7fb8994f8d8491..224ab2b221ef05 100644
--- a/static/app/gettingStartedDocs/python/pyramid.tsx
+++ b/static/app/gettingStartedDocs/python/pyramid.tsx
@@ -2,9 +2,21 @@ import ExternalLink from 'sentry/components/links/externalLink';
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {t, tct} from 'sentry/locale';
// Configuration Start
+
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
+
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
+
const introduction = (
<p>
{tct(
@@ -17,8 +29,10 @@ const introduction = (
);
export const steps = ({
- dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.INSTALL,
description: <p>{tct('Install [code:sentry-sdk] from PyPI:', {code: <code />})}</p>,
@@ -45,26 +59,18 @@ import sentry_sdk
from sentry_sdk.integrations.pyramid import PyramidIntegration
sentry_sdk.init(
- dsn="${dsn}",
- integrations=[
- PyramidIntegration(),
- ],
-
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production.
- traces_sample_rate=1.0,
+${sentryInitContent}
)
def sentry_debug(request):
-division_by_zero = 1 / 0
+ division_by_zero = 1 / 0
with Configurator() as config:
-config.add_route('sentry-debug', '/')
-config.add_view(sentry_debug, route_name='sentry-debug')
-app = config.make_wsgi_app()
-server = make_server('0.0.0.0', 6543, app)
-server.serve_forever()
+ config.add_route('sentry-debug', '/')
+ config.add_view(sentry_debug, route_name='sentry-debug')
+ app = config.make_wsgi_app()
+ server = make_server('0.0.0.0', 6543, app)
+ server.serve_forever()
`,
},
],
@@ -72,8 +78,37 @@ server.serve_forever()
];
// Configuration End
-export function GettingStartedWithPyramid({dsn, ...props}: ModuleProps) {
- return <Layout steps={steps({dsn})} introduction={introduction} {...props} />;
+export function GettingStartedWithPyramid({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [
+ ` dsn="${dsn}",`,
+ ` integrations=[PyramidIntegration()],`,
+ ];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
+ return (
+ <Layout
+ introduction={introduction}
+ steps={steps({
+ sentryInitContent: sentryInitContent.join('\n'),
+ })}
+ {...props}
+ />
+ );
}
export default GettingStartedWithPyramid;
diff --git a/static/app/gettingStartedDocs/python/python.tsx b/static/app/gettingStartedDocs/python/python.tsx
index dbfd0fbf90b035..4b9c23b9d9d7c9 100644
--- a/static/app/gettingStartedDocs/python/python.tsx
+++ b/static/app/gettingStartedDocs/python/python.tsx
@@ -6,15 +6,15 @@ import {t, tct} from 'sentry/locale';
// Configuration Start
-const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
- # of sampled transactions.
- # We recommend adjusting this value in production.
- profiles_sample_rate=1.0,`;
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
-const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production.
- traces_sample_rate=1.0,`;
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
export const steps = ({
sentryInitContent,
@@ -87,7 +87,7 @@ export function GettingStartedWithPython({
}: ModuleProps) {
const otherConfigs: string[] = [];
- let sentryInitContent: string[] = [` dsn="${dsn}",`];
+ let sentryInitContent: string[] = [` dsn="${dsn}",`];
if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
otherConfigs.push(performanceConfiguration);
diff --git a/static/app/gettingStartedDocs/python/quart.spec.tsx b/static/app/gettingStartedDocs/python/quart.spec.tsx
index a795acab8c67f3..773506f59d18c5 100644
--- a/static/app/gettingStartedDocs/python/quart.spec.tsx
+++ b/static/app/gettingStartedDocs/python/quart.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithDjango', function () {
const {container} = render(<GettingStartedWithQuart dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/quart.tsx b/static/app/gettingStartedDocs/python/quart.tsx
index 9295db403c08da..ff63823952b5d0 100644
--- a/static/app/gettingStartedDocs/python/quart.tsx
+++ b/static/app/gettingStartedDocs/python/quart.tsx
@@ -4,9 +4,21 @@ import ExternalLink from 'sentry/components/links/externalLink';
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {t, tct} from 'sentry/locale';
// Configuration Start
+
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
+
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
+
const introduction = (
<Fragment>
<p>
@@ -22,8 +34,10 @@ const introduction = (
);
export const steps = ({
- dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.INSTALL,
description: <p>{tct('Install [code:sentry-sdk] from PyPI:', {code: <code />})}</p>,
@@ -48,14 +62,7 @@ from sentry_sdk.integrations.quart import QuartIntegration
from quart import Quart
sentry_sdk.init(
- dsn="${dsn}",
- integrations=[
- QuartIntegration(),
- ],
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
+${sentryInitContent}
)
app = Quart(__name__)
@@ -66,8 +73,37 @@ app = Quart(__name__)
];
// Configuration End
-export function GettingStartedWithQuart({dsn, ...props}: ModuleProps) {
- return <Layout steps={steps({dsn})} introduction={introduction} {...props} />;
+export function GettingStartedWithQuart({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [
+ ` dsn="${dsn}",`,
+ ` integrations=[QuartIntegration()],`,
+ ];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
+ return (
+ <Layout
+ introduction={introduction}
+ steps={steps({
+ sentryInitContent: sentryInitContent.join('\n'),
+ })}
+ {...props}
+ />
+ );
}
export default GettingStartedWithQuart;
diff --git a/static/app/gettingStartedDocs/python/rq.spec.tsx b/static/app/gettingStartedDocs/python/rq.spec.tsx
index 29dacd3d8acc45..4f713c4ef0517d 100644
--- a/static/app/gettingStartedDocs/python/rq.spec.tsx
+++ b/static/app/gettingStartedDocs/python/rq.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithRq', function () {
const {container} = render(<GettingStartedWithRq dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/rq.tsx b/static/app/gettingStartedDocs/python/rq.tsx
index 53beac47fbf502..3917e1f684fb27 100644
--- a/static/app/gettingStartedDocs/python/rq.tsx
+++ b/static/app/gettingStartedDocs/python/rq.tsx
@@ -2,9 +2,21 @@ import ExternalLink from 'sentry/components/links/externalLink';
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {t, tct} from 'sentry/locale';
// Configuration Start
+
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
+
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
+
const introduction = (
<p>
{tct('The RQ integration adds support for the [link:RQ Job Queue System].', {
@@ -14,8 +26,10 @@ const introduction = (
);
export const steps = ({
- dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.CONFIGURE,
description: (
@@ -33,15 +47,7 @@ import sentry_sdk
from sentry_sdk.integrations.rq import RqIntegration
sentry_sdk.init(
- dsn="${dsn}",
- integrations=[
- RqIntegration(),
- ],
-
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
+${sentryInitContent}
)
`,
},
@@ -59,8 +65,37 @@ rq worker \
];
// Configuration End
-export function GettingStartedWithRq({dsn, ...props}: ModuleProps) {
- return <Layout steps={steps({dsn})} introduction={introduction} {...props} />;
+export function GettingStartedWithRq({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [
+ ` dsn="${dsn}",`,
+ ` integrations=[RqIntegration()],`,
+ ];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
+ return (
+ <Layout
+ introduction={introduction}
+ steps={steps({
+ sentryInitContent: sentryInitContent.join('\n'),
+ })}
+ {...props}
+ />
+ );
}
export default GettingStartedWithRq;
diff --git a/static/app/gettingStartedDocs/python/sanic.spec.tsx b/static/app/gettingStartedDocs/python/sanic.spec.tsx
index 26f65fd9ae9925..a3dfb9efa2af7d 100644
--- a/static/app/gettingStartedDocs/python/sanic.spec.tsx
+++ b/static/app/gettingStartedDocs/python/sanic.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithSanic', function () {
const {container} = render(<GettingStartedWithSanic dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/sanic.tsx b/static/app/gettingStartedDocs/python/sanic.tsx
index 632b287b39442a..0caab573f61115 100644
--- a/static/app/gettingStartedDocs/python/sanic.tsx
+++ b/static/app/gettingStartedDocs/python/sanic.tsx
@@ -6,9 +6,21 @@ import ListItem from 'sentry/components/list/listItem';
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {t, tct} from 'sentry/locale';
// Configuration Start
+
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
+
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
+
const introduction = (
<Fragment>
<p>
@@ -40,8 +52,10 @@ const introduction = (
);
export const steps = ({
- dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.INSTALL,
description: <p>{tct('Install [code:sentry-sdk] from PyPI:', {code: <code />})}</p>,
@@ -80,15 +94,7 @@ from sentry_sdk.integrations.sanic import SanicIntegration
from sanic import Sanic
sentry_sdk.init(
- dsn="${dsn}",
- integrations=[
- SanicIntegration(),
- ],
-
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
+${sentryInitContent}
)
app = Sanic(__name__)
@@ -99,8 +105,37 @@ app = Sanic(__name__)
];
// Configuration End
-export function GettingStartedWithSanic({dsn, ...props}: ModuleProps) {
- return <Layout steps={steps({dsn})} introduction={introduction} {...props} />;
+export function GettingStartedWithSanic({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [
+ ` dsn="${dsn}",`,
+ ` integrations=[SanicIntegration()],`,
+ ];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
+ return (
+ <Layout
+ introduction={introduction}
+ steps={steps({
+ sentryInitContent: sentryInitContent.join('\n'),
+ })}
+ {...props}
+ />
+ );
}
export default GettingStartedWithSanic;
diff --git a/static/app/gettingStartedDocs/python/serverless.spec.tsx b/static/app/gettingStartedDocs/python/serverless.spec.tsx
index ce863883be3dfe..aacca3d8c2109e 100644
--- a/static/app/gettingStartedDocs/python/serverless.spec.tsx
+++ b/static/app/gettingStartedDocs/python/serverless.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithServerless', function () {
const {container} = render(<GettingStartedWithServerless dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/serverless.tsx b/static/app/gettingStartedDocs/python/serverless.tsx
index e8ee834185a065..93a9088b547c01 100644
--- a/static/app/gettingStartedDocs/python/serverless.tsx
+++ b/static/app/gettingStartedDocs/python/serverless.tsx
@@ -4,17 +4,26 @@ import ExternalLink from 'sentry/components/links/externalLink';
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {t, tct} from 'sentry/locale';
// Configuration Start
-// It is recommended to use an integration for your particular serverless environment if available, as those are easier to use and capture more useful information.
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
-// If you use a serverless provider not directly supported by the SDK, you can use this generic integration.
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
export const steps = ({
- dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.INSTALL,
description: (
@@ -50,12 +59,7 @@ import sentry_sdk
from sentry_sdk.integrations.serverless import serverless_function
sentry_sdk.init(
- dsn="${dsn}",
-
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
+${sentryInitContent}
)
@serverless_function
@@ -67,8 +71,33 @@ def my_function(...): ...
];
// Configuration End
-export function GettingStartedWithServerless({dsn, ...props}: ModuleProps) {
- return <Layout steps={steps({dsn})} {...props} />;
+export function GettingStartedWithServerless({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [` dsn="${dsn}",`];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
+ return (
+ <Layout
+ steps={steps({
+ sentryInitContent: sentryInitContent.join('\n'),
+ })}
+ {...props}
+ />
+ );
}
export default GettingStartedWithServerless;
diff --git a/static/app/gettingStartedDocs/python/starlette.spec.tsx b/static/app/gettingStartedDocs/python/starlette.spec.tsx
index cb07fe3381e80f..8586e8d2a56e8a 100644
--- a/static/app/gettingStartedDocs/python/starlette.spec.tsx
+++ b/static/app/gettingStartedDocs/python/starlette.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithDjango', function () {
const {container} = render(<GettingStartedWithStarlette dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/starlette.tsx b/static/app/gettingStartedDocs/python/starlette.tsx
index fbcfc06f7cee78..495e8d530a595d 100644
--- a/static/app/gettingStartedDocs/python/starlette.tsx
+++ b/static/app/gettingStartedDocs/python/starlette.tsx
@@ -2,18 +2,33 @@ import ExternalLink from 'sentry/components/links/externalLink';
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {t, tct} from 'sentry/locale';
// Configuration Start
+
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
+
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
+
const introduction = tct(
'The Starlette integration adds support for the Starlette Framework.',
{
link: <ExternalLink href="https://www.starlette.io/" />,
}
);
+
export const steps = ({
- dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.INSTALL,
description: (
@@ -54,12 +69,7 @@ import sentry_sdk
sentry_sdk.init(
- dsn="${dsn}",
-
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
+${sentryInitContent}
)
app = Starlette(routes=[...])
@@ -91,10 +101,10 @@ from starlette.routing import Route
async def trigger_error(request):
- division_by_zero = 1 / 0
+ division_by_zero = 1 / 0
app = Starlette(routes=[
- Route("/sentry-debug", trigger_error),
+ Route("/sentry-debug", trigger_error),
])
`,
additionalInfo: t(
@@ -106,8 +116,34 @@ app = Starlette(routes=[
];
// Configuration End
-export function GettingStartedWithStarlette({dsn, ...props}: ModuleProps) {
- return <Layout steps={steps({dsn})} introduction={introduction} {...props} />;
+export function GettingStartedWithStarlette({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [` dsn="${dsn}",`];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
+ return (
+ <Layout
+ introduction={introduction}
+ steps={steps({
+ sentryInitContent: sentryInitContent.join('\n'),
+ })}
+ {...props}
+ />
+ );
}
export default GettingStartedWithStarlette;
diff --git a/static/app/gettingStartedDocs/python/tornado.spec.tsx b/static/app/gettingStartedDocs/python/tornado.spec.tsx
index 55c07396966c19..b0cf9ccd005179 100644
--- a/static/app/gettingStartedDocs/python/tornado.spec.tsx
+++ b/static/app/gettingStartedDocs/python/tornado.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithTornado', function () {
const {container} = render(<GettingStartedWithTornado dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/tornado.tsx b/static/app/gettingStartedDocs/python/tornado.tsx
index 3c8fa7779bce9d..2e056a3d36e4a7 100644
--- a/static/app/gettingStartedDocs/python/tornado.tsx
+++ b/static/app/gettingStartedDocs/python/tornado.tsx
@@ -2,9 +2,21 @@ import ExternalLink from 'sentry/components/links/externalLink';
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {t, tct} from 'sentry/locale';
// Configuration Start
+
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
+
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
+
const introduction = (
<p>
{tct(
@@ -17,8 +29,10 @@ const introduction = (
);
export const steps = ({
- dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.INSTALL,
description: <p>{tct('Install [code:sentry-sdk] from PyPI:', {code: <code />})}</p>,
@@ -54,15 +68,7 @@ import sentry_sdk
from sentry_sdk.integrations.tornado import TornadoIntegration
sentry_sdk.init(
- dsn="${dsn}",
- integrations=[
- TornadoIntegration(),
- ],
-
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
+${sentryInitContent}
)
# Your app code here, without changes
@@ -76,8 +82,37 @@ class MyHandler(...):
];
// Configuration End
-export function GettingStartedWithTornado({dsn, ...props}: ModuleProps) {
- return <Layout steps={steps({dsn})} introduction={introduction} {...props} />;
+export function GettingStartedWithTornado({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [
+ ` dsn="${dsn}",`,
+ ` integrations=[TornadoIntegration()],`,
+ ];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
+ return (
+ <Layout
+ introduction={introduction}
+ steps={steps({
+ sentryInitContent: sentryInitContent.join('\n'),
+ })}
+ {...props}
+ />
+ );
}
export default GettingStartedWithTornado;
diff --git a/static/app/gettingStartedDocs/python/tryton.spec.tsx b/static/app/gettingStartedDocs/python/tryton.spec.tsx
index a8274467ffcc9d..6c376929b18a95 100644
--- a/static/app/gettingStartedDocs/python/tryton.spec.tsx
+++ b/static/app/gettingStartedDocs/python/tryton.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithTryton', function () {
const {container} = render(<GettingStartedWithTryton dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/tryton.tsx b/static/app/gettingStartedDocs/python/tryton.tsx
index b090a14bdb4b86..ddcaef21fc7cc8 100644
--- a/static/app/gettingStartedDocs/python/tryton.tsx
+++ b/static/app/gettingStartedDocs/python/tryton.tsx
@@ -2,9 +2,21 @@ import ExternalLink from 'sentry/components/links/externalLink';
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {t, tct} from 'sentry/locale';
// Configuration Start
+
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
+
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
+
const introduction = (
<p>
{tct('The Tryton integration adds support for the [link:Tryton Framework Server].', {
@@ -14,8 +26,10 @@ const introduction = (
);
export const steps = ({
- dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.CONFIGURE,
description: (
@@ -37,15 +51,7 @@ import sentry_sdk
import sentry_sdk.integrations.trytond
sentry_sdk.init(
- dsn="${dsn}",
- integrations=[
- sentry_sdk.integrations.trytond.TrytondWSGIIntegration(),
- ],
-
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
+${sentryInitContent}
)
from trytond.application import app as application
@@ -67,12 +73,12 @@ from trytond.exceptions import UserError
@application.error_handler
def _(app, request, e):
- if isinstance(e, TrytonException):
- return
- else:
- event_id = sentry_sdk.last_event_id()
- data = UserError('Custom message', f'{event_id}{e}')
- return app.make_response(request, data)
+ if isinstance(e, TrytonException):
+ return
+ else:
+ event_id = sentry_sdk.last_event_id()
+ data = UserError('Custom message', f'{event_id}{e}')
+ return app.make_response(request, data)
`,
},
],
@@ -80,8 +86,39 @@ def _(app, request, e):
];
// Configuration End
-export function GettingStartedWithTryton({dsn, ...props}: ModuleProps) {
- return <Layout steps={steps({dsn})} introduction={introduction} {...props} />;
+export function GettingStartedWithTryton({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [
+ ` dsn="${dsn}",`,
+ ` integrations=[`,
+ ` sentry_sdk.integrations.trytond.TrytondWSGIIntegration(),`,
+ ` ],`,
+ ];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
+ return (
+ <Layout
+ introduction={introduction}
+ steps={steps({
+ sentryInitContent: sentryInitContent.join('\n'),
+ })}
+ {...props}
+ />
+ );
}
export default GettingStartedWithTryton;
diff --git a/static/app/gettingStartedDocs/python/wsgi.spec.tsx b/static/app/gettingStartedDocs/python/wsgi.spec.tsx
index c21523a9f12477..e2a8a3f2e09ada 100644
--- a/static/app/gettingStartedDocs/python/wsgi.spec.tsx
+++ b/static/app/gettingStartedDocs/python/wsgi.spec.tsx
@@ -9,7 +9,7 @@ describe('GettingStartedWithWSGI', function () {
const {container} = render(<GettingStartedWithWSGI dsn="test-dsn" />);
// Steps
- for (const step of steps()) {
+ for (const step of steps({sentryInitContent: 'test-init-content'})) {
expect(
screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]})
).toBeInTheDocument();
diff --git a/static/app/gettingStartedDocs/python/wsgi.tsx b/static/app/gettingStartedDocs/python/wsgi.tsx
index 7fe3b4a7f000c4..825413290180ba 100644
--- a/static/app/gettingStartedDocs/python/wsgi.tsx
+++ b/static/app/gettingStartedDocs/python/wsgi.tsx
@@ -4,12 +4,26 @@ import ExternalLink from 'sentry/components/links/externalLink';
import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
+import {ProductSolution} from 'sentry/components/onboarding/productSelection';
import {t, tct} from 'sentry/locale';
// Configuration Start
+
+const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100%
+ # of sampled transactions.
+ # We recommend adjusting this value in production.
+ profiles_sample_rate=1.0,`;
+
+const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100%
+ # of transactions for performance monitoring.
+ # We recommend adjusting this value in production.
+ traces_sample_rate=1.0,`;
+
export const steps = ({
- dsn,
-}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
+ sentryInitContent,
+}: {
+ sentryInitContent: string;
+}): LayoutProps['steps'] => [
{
type: StepType.INSTALL,
description: (
@@ -39,12 +53,7 @@ from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware
from myapp import wsgi_app
sentry_sdk.init(
- dsn="${dsn}",
-
- # Set traces_sample_rate to 1.0 to capture 100%
- # of transactions for performance monitoring.
- # We recommend adjusting this value in production,
- traces_sample_rate=1.0,
+${sentryInitContent}
)
wsgi_app = SentryWsgiMiddleware(wsgi_app)
@@ -55,8 +64,32 @@ wsgi_app = SentryWsgiMiddleware(wsgi_app)
];
// Configuration End
-export function GettingStartedWithWSGI({dsn, ...props}: ModuleProps) {
- return <Layout steps={steps({dsn})} {...props} />;
-}
+export function GettingStartedWithWSGI({
+ dsn,
+ activeProductSelection = [],
+ ...props
+}: ModuleProps) {
+ const otherConfigs: string[] = [];
+
+ let sentryInitContent: string[] = [` dsn="${dsn}",`];
+
+ if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) {
+ otherConfigs.push(performanceConfiguration);
+ }
+ if (activeProductSelection.includes(ProductSolution.PROFILING)) {
+ otherConfigs.push(profilingConfiguration);
+ }
+
+ sentryInitContent = sentryInitContent.concat(otherConfigs);
+
+ return (
+ <Layout
+ steps={steps({
+ sentryInitContent: sentryInitContent.join('\n'),
+ })}
+ {...props}
+ />
+ );
+}
export default GettingStartedWithWSGI;
|
49bc5498dbd6c0ea1a535274910811bc39a78300
|
2022-01-19 05:12:44
|
Evan Purkhiser
|
fix(ui-test): Missed one data-test-id="loading-indicator" (#31197)
| false
|
Missed one data-test-id="loading-indicator" (#31197)
|
fix
|
diff --git a/static/index.ejs b/static/index.ejs
index 09f5dafd02a4f8..5c8bfe61876f46 100644
--- a/static/index.ejs
+++ b/static/index.ejs
@@ -61,7 +61,7 @@
<div id="blk_router">
<div class="loading triangle">
<div class="loading-mask"></div>
- <div class="loading-indicator">
+ <div class="loading-indicator" data-test-id="loading-indicator">
<img src="<%=require('sentry-images/sentry-loader.svg')%>" />
</div>
<div class="loading-message">
|
f1c36f9083afce31721b09bd72e6ab3e8861d5a6
|
2023-02-13 17:30:01
|
Joris Bayer
|
test(grouping): Escape chars in fingerprint matcher (#44408)
| false
|
Escape chars in fingerprint matcher (#44408)
|
test
|
diff --git a/tests/sentry/grouping/fingerprint_inputs/fingerprint-escape-chars.json b/tests/sentry/grouping/fingerprint_inputs/fingerprint-escape-chars.json
new file mode 100644
index 00000000000000..c8ef055f8e8ccb
--- /dev/null
+++ b/tests/sentry/grouping/fingerprint_inputs/fingerprint-escape-chars.json
@@ -0,0 +1,19 @@
+{
+ "_fingerprinting_rules": [
+ {
+ "matchers": [
+ [
+ "message",
+ "\\{\\[\\*\\?\\]\\}"
+ ]
+ ],
+ "fingerprint": [
+ "escaped",
+ "{{ message }}"
+ ]
+ }
+ ],
+ "logentry": {
+ "formatted": "{[*?]}"
+ }
+}
diff --git a/tests/sentry/grouping/similarity/snapshots/test_features/test_similarity_extract_fingerprinting/fingerprint_escape_chars.pysnap b/tests/sentry/grouping/similarity/snapshots/test_features/test_similarity_extract_fingerprinting/fingerprint_escape_chars.pysnap
new file mode 100644
index 00000000000000..b23a5df7b9d390
--- /dev/null
+++ b/tests/sentry/grouping/similarity/snapshots/test_features/test_similarity_extract_fingerprinting/fingerprint_escape_chars.pysnap
@@ -0,0 +1,9 @@
+---
+created: '2023-02-10T15:02:32.115736Z'
+creator: sentry
+source: tests/sentry/grouping/similarity/test_features.py
+---
+similarity:2020-07-23:fingerprint:ident-shingle: "escaped"
+similarity:2020-07-23:fingerprint:ident-shingle: "{[*?]}"
+similarity:2020-07-23:message:character-5-shingle: "[*?]}"
+similarity:2020-07-23:message:character-5-shingle: "{[*?]"
diff --git a/tests/sentry/grouping/snapshots/test_fingerprinting/test_event_hash_variant/fingerprint_escape_chars.pysnap b/tests/sentry/grouping/snapshots/test_fingerprinting/test_event_hash_variant/fingerprint_escape_chars.pysnap
new file mode 100644
index 00000000000000..3fe05992f751d6
--- /dev/null
+++ b/tests/sentry/grouping/snapshots/test_fingerprinting/test_event_hash_variant/fingerprint_escape_chars.pysnap
@@ -0,0 +1,32 @@
+---
+created: '2023-02-10T13:31:47.690454Z'
+creator: sentry
+source: tests/sentry/grouping/test_fingerprinting.py
+---
+config:
+ rules:
+ - attributes: {}
+ fingerprint:
+ - escaped
+ - '{{ message }}'
+ matchers:
+ - - message
+ - \{\[\*\?\]\}
+ version: 1
+fingerprint:
+- escaped
+- '{{ message }}'
+title: '{[*?]}'
+variants:
+ custom-fingerprint:
+ matched_rule: message:"\{\[\*\?\]\}" -> "escaped{{ message }}"
+ type: custom-fingerprint
+ values:
+ - escaped
+ - '{[*?]}'
+ default:
+ component:
+ contributes: false
+ contributes_to_similarity: true
+ hint: custom fingerprint takes precedence
+ type: component
|
b36be1417251b310f09defa67346c0f31c58d9cd
|
2025-01-30 23:57:03
|
Snigdha Sharma
|
chore(metric-issues): Add project-level flag for metric issues (#84316)
| false
|
Add project-level flag for metric issues (#84316)
|
chore
|
diff --git a/src/sentry/features/temporary.py b/src/sentry/features/temporary.py
index 2e67a6e0af752d..b87fd35249b22f 100644
--- a/src/sentry/features/temporary.py
+++ b/src/sentry/features/temporary.py
@@ -165,6 +165,7 @@ def register_temporary_features(manager: FeatureManager):
manager.add("organizations:issue-stream-functional-refactor", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
manager.add("organizations:large-debug-files", OrganizationFeature, FeatureHandlerStrategy.INTERNAL, api_expose=False)
manager.add("organizations:metric-issue-poc", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
+ manager.add("projects:metric-issue-creation", ProjectFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=False)
manager.add("organizations:issue-open-periods", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=False)
manager.add("organizations:mep-rollout-flag", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
manager.add("organizations:mep-use-default-tags", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=False)
diff --git a/src/sentry/incidents/utils/metric_issue_poc.py b/src/sentry/incidents/utils/metric_issue_poc.py
index 262f092537a8a7..a0983b870925ff 100644
--- a/src/sentry/incidents/utils/metric_issue_poc.py
+++ b/src/sentry/incidents/utils/metric_issue_poc.py
@@ -3,6 +3,7 @@
from typing import Any
from uuid import uuid4
+from sentry import features
from sentry.incidents.models.incident import Incident, IncidentStatus
from sentry.integrations.metric_alerts import get_incident_status_text
from sentry.issues.grouptype import MetricIssuePOC
@@ -71,6 +72,11 @@ def create_or_update_metric_issue(
if not project:
return None
+ if not features.has("projects:metric-issue-creation", project):
+ # We've already checked for the feature flag at the organization level,
+ # but this flag helps us test with a smaller set of projects.
+ return None
+
# collect the data from the incident to treat as an event
event_data: dict[str, Any] = {
"event_id": uuid4().hex,
diff --git a/tests/sentry/incidents/test_subscription_processor.py b/tests/sentry/incidents/test_subscription_processor.py
index b245f2ccba4a6a..68d0998b61ea8c 100644
--- a/tests/sentry/incidents/test_subscription_processor.py
+++ b/tests/sentry/incidents/test_subscription_processor.py
@@ -2878,6 +2878,7 @@ def test_incident_made_after_ten_minutes(self):
self.assert_incident_is_latest_for_rule(new_incident)
@with_feature("organizations:metric-issue-poc")
+ @with_feature("projects:metric-issue-creation")
@mock.patch("sentry.incidents.utils.metric_issue_poc.produce_occurrence_to_kafka")
def test_alert_creates_metric_issue(self, mock_produce_occurrence_to_kafka):
rule = self.rule
@@ -2907,6 +2908,7 @@ def test_alert_creates_metric_issue(self, mock_produce_occurrence_to_kafka):
assert occurrence.evidence_data["metric_value"] == trigger.alert_threshold + 1
@with_feature("organizations:metric-issue-poc")
+ @with_feature("projects:metric-issue-creation")
@mock.patch("sentry.incidents.utils.metric_issue_poc.produce_occurrence_to_kafka")
def test_resolved_alert_updates_metric_issue(self, mock_produce_occurrence_to_kafka):
from sentry.models.group import GroupStatus
diff --git a/tests/sentry/incidents/utils/test_metric_issue_poc.py b/tests/sentry/incidents/utils/test_metric_issue_poc.py
index 0a3de5fe7cd268..e7ea54ef444281 100644
--- a/tests/sentry/incidents/utils/test_metric_issue_poc.py
+++ b/tests/sentry/incidents/utils/test_metric_issue_poc.py
@@ -11,6 +11,7 @@
@apply_feature_flag_on_cls("organizations:metric-issue-poc-ingest")
+@apply_feature_flag_on_cls("projects:metric-issue-creation")
class TestMetricIssuePOC(IssueOccurrenceTestBase, APITestCase):
def setUp(self):
self.organization = self.create_organization()
|
f2d3711e9d249796786fd0d9e0f6a3cac234c805
|
2024-02-21 20:11:03
|
Tony Xiao
|
perf(metrics): Move span examples query conditions around (#65467)
| false
|
Move span examples query conditions around (#65467)
|
perf
|
diff --git a/src/sentry/sentry_metrics/querying/samples_list.py b/src/sentry/sentry_metrics/querying/samples_list.py
index 918b8ff0ac78d9..c9194cc847ac6e 100644
--- a/src/sentry/sentry_metrics/querying/samples_list.py
+++ b/src/sentry/sentry_metrics/querying/samples_list.py
@@ -53,13 +53,12 @@ def get_spans_by_key(self, span_ids: list[tuple[str, str, str]]):
offset=0,
)
- # Using `IN` sometimes does not use the bloomfilter index
- # on the table. So we're explicitly writing the condition
- # using `OR`s.
+ # This are the additional conditions to better take advantage of the ORDER BY
+ # on the spans table. This creates a list of conditions to be `OR`ed together
+ # that can will be used by ClickHouse to narrow down the granules.
#
- # May not be necessary because it's also filtering on the
- # `span.group` as well which allows Clickhouse to filter
- # via the primary key but this is a precaution.
+ # The span ids are not in this condition because they are more effective when
+ # specified within the `PREWHERE` clause. So, it's in a separate condition.
conditions = [
And(
[
@@ -67,18 +66,30 @@ def get_spans_by_key(self, span_ids: list[tuple[str, str, str]]):
Condition(
builder.column("timestamp"), Op.EQ, datetime.fromisoformat(timestamp)
),
- Condition(builder.column("id"), Op.EQ, span_id),
]
)
- for (group, timestamp, span_id) in span_ids
+ for (group, timestamp, _) in span_ids
]
if len(conditions) == 1:
- span_condition = conditions[0]
+ order_by_condition = conditions[0]
else:
- span_condition = Or(conditions)
+ order_by_condition = Or(conditions)
- builder.add_conditions([span_condition])
+ # Using `IN` combined with putting the list in a SnQL "tuple" triggers an optimizer
+ # in snuba where it
+ # 1. moves the condition into the `PREWHERE` clause
+ # 2. maps the ids to the underlying UInt64 and uses the bloom filter index
+ #
+ # NOTE: the "tuple" here is critical as without it, snuba will not correctly
+ # rewrite the condition and keep it in the WHERE and as a hexidecimal.
+ span_id_condition = Condition(
+ builder.column("id"),
+ Op.IN,
+ Function("tuple", [span_id for _, _, span_id in span_ids]),
+ )
+
+ builder.add_conditions([order_by_condition, span_id_condition])
query_results = builder.run_query(self.referrer.value)
return builder.process_results(query_results)
|
3a4134ab1a8e1d44fc5126d5c3e8de8ae9bb255b
|
2022-05-20 23:55:23
|
anthony sottile
|
ref: fix deprecated django postgresql_psycopg2 imports (#34873)
| false
|
fix deprecated django postgresql_psycopg2 imports (#34873)
|
ref
|
diff --git a/src/bitfield/types.py b/src/bitfield/types.py
index 93c84e3cba4f60..d05686acd94ba9 100644
--- a/src/bitfield/types.py
+++ b/src/bitfield/types.py
@@ -246,7 +246,7 @@ def get_label(self, flag):
# We need to register adapters in Django 1.8 in order to prevent
# "ProgrammingError: can't adapt type"
try:
- from django.db.backends.postgresql_psycopg2.base import Database
+ from django.db.backends.postgresql.base import Database
Database.extensions.register_adapter(Bit, lambda x: Database.extensions.AsIs(int(x)))
Database.extensions.register_adapter(BitHandler, lambda x: Database.extensions.AsIs(int(x)))
diff --git a/src/sentry/db/postgres/base.py b/src/sentry/db/postgres/base.py
index b9d1b929499635..be734fab5af80a 100644
--- a/src/sentry/db/postgres/base.py
+++ b/src/sentry/db/postgres/base.py
@@ -2,7 +2,7 @@
# Some of these imports are unused, but they are inherited from other engines
# and should be available as part of the backend ``base.py`` namespace.
-from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper
+from django.db.backends.postgresql.base import DatabaseWrapper
from sentry.utils.strings import strip_lone_surrogates
diff --git a/src/sentry/db/postgres/operations.py b/src/sentry/db/postgres/operations.py
index 3aa4137e21dd81..22406d2ae9a346 100644
--- a/src/sentry/db/postgres/operations.py
+++ b/src/sentry/db/postgres/operations.py
@@ -1,4 +1,4 @@
-from django.db.backends.postgresql_psycopg2.base import DatabaseOperations
+from django.db.backends.postgresql.base import DatabaseOperations
class DatabaseOperations(DatabaseOperations):
|
8dc8d745fc68b0367113307936ef73dd381f15b8
|
2025-03-07 16:39:11
|
Jan Michael Auer
|
ref(spans): Allow grouping directly on span batches (#86516)
| false
|
Allow grouping directly on span batches (#86516)
|
ref
|
diff --git a/src/sentry/spans/consumers/process_segments/factory.py b/src/sentry/spans/consumers/process_segments/factory.py
index 1a464864b3198d..a89f8f192cad27 100644
--- a/src/sentry/spans/consumers/process_segments/factory.py
+++ b/src/sentry/spans/consumers/process_segments/factory.py
@@ -1,5 +1,6 @@
import logging
from collections.abc import Mapping
+from typing import cast
import orjson
from arroyo import Topic as ArroyoTopic
@@ -12,11 +13,11 @@
from arroyo.processing.strategies.unfold import Unfold
from arroyo.types import Commit, Message, Partition, Value
from sentry_kafka_schemas.codecs import Codec
-from sentry_kafka_schemas.schema_types.buffered_segments_v1 import BufferedSegment, SegmentSpan
+from sentry_kafka_schemas.schema_types.buffered_segments_v1 import BufferedSegment
from sentry import options
from sentry.conf.types.kafka_definition import Topic, get_topic_codec
-from sentry.spans.consumers.process_segments.message import process_segment
+from sentry.spans.consumers.process_segments.message import Span, process_segment
from sentry.utils.arroyo import MultiprocessingPool, run_task_with_multiprocessing
from sentry.utils.kafka_config import get_kafka_producer_cluster_options, get_topic_definition
@@ -25,17 +26,13 @@
logger = logging.getLogger(__name__)
-def _deserialize_segment(value: bytes) -> BufferedSegment:
- return BUFFERED_SEGMENT_SCHEMA.decode(value)
-
-
-def process_message(message: Message[KafkaPayload]) -> list[SegmentSpan]:
+def process_message(message: Message[KafkaPayload]) -> list[Span]:
value = message.payload.value
- segment = _deserialize_segment(value)
- return process_segment(segment["spans"])
+ segment = BUFFERED_SEGMENT_SCHEMA.decode(value)
+ return process_segment(cast(list[Span], segment["spans"]))
-def _process_message(message: Message[KafkaPayload]) -> list[SegmentSpan]:
+def _process_message(message: Message[KafkaPayload]) -> list[Span]:
if not options.get("standalone-spans.process-segments-consumer.enable"):
return []
@@ -49,7 +46,7 @@ def _process_message(message: Message[KafkaPayload]) -> list[SegmentSpan]:
# raise InvalidMessage(message.value.partition, message.value.offset)
-def explode_segment(message: tuple[list[SegmentSpan], Mapping[Partition, int]]):
+def explode_segment(message: tuple[list[Span], Mapping[Partition, int]]):
spans, committable = message
last = len(spans) - 1
for i, span in enumerate(spans):
diff --git a/src/sentry/spans/consumers/process_segments/message.py b/src/sentry/spans/consumers/process_segments/message.py
index 01ab819fa73a57..daf7e4293ea77b 100644
--- a/src/sentry/spans/consumers/process_segments/message.py
+++ b/src/sentry/spans/consumers/process_segments/message.py
@@ -5,13 +5,12 @@
from typing import Any, cast
from django.core.exceptions import ValidationError
-from sentry_kafka_schemas.schema_types.buffered_segments_v1 import SegmentSpan
+from sentry_kafka_schemas.schema_types.buffered_segments_v1 import SegmentSpan as SchemaSpan
from sentry import options
from sentry.event_manager import (
Job,
ProjectsMapping,
- _calculate_span_grouping,
_detect_performance_problems,
_pull_out_data,
_record_transaction_info,
@@ -24,12 +23,20 @@
from sentry.models.release import Release
from sentry.models.releaseenvironment import ReleaseEnvironment
from sentry.models.releaseprojectenvironment import ReleaseProjectEnvironment
+from sentry.spans.grouping.api import load_span_grouping_config
from sentry.utils import metrics
from sentry.utils.dates import to_datetime
logger = logging.getLogger(__name__)
+class Span(SchemaSpan, total=False):
+ start_timestamp_precise: float # Missing in schema
+ end_timestamp_precise: float # Missing in schema
+ op: str | None # Added in enrichment
+ hash: str | None # Added in enrichment
+
+
@metrics.wraps("save_event.send_occurrence_to_platform")
def _send_occurrence_to_platform(jobs: Sequence[Job], projects: ProjectsMapping) -> None:
for job in jobs:
@@ -105,9 +112,9 @@ def dfs(visited, flattened_spans, tree, span_id):
stack.append(child["span_id"])
-def flatten_tree(tree: dict[str, Any], root_span_id: str | None) -> list[SegmentSpan]:
+def flatten_tree(tree: dict[str, Any], root_span_id: str | None) -> list[Span]:
visited: Set[str] = set()
- flattened_spans: list[SegmentSpan] = []
+ flattened_spans: list[Span] = []
if root_span_id:
dfs(visited, flattened_spans, tree, root_span_id)
@@ -138,7 +145,7 @@ def _update_occurrence_group_type(jobs: Sequence[Job], projects: ProjectsMapping
job["performance_problems"] = updated_problems
-def _find_segment_span(spans: list[SegmentSpan]) -> SegmentSpan | None:
+def _find_segment_span(spans: list[Span]) -> Span | None:
"""
Finds the segment in the span in the list that has ``is_segment`` set to
``True``.
@@ -157,7 +164,20 @@ def _find_segment_span(spans: list[SegmentSpan]) -> SegmentSpan | None:
return None
-def _create_models(segment: SegmentSpan, project: Project) -> None:
+def _enrich_spans(segment: Span | None, spans: list[Span]) -> None:
+ for span in spans:
+ if (op := span.get("sentry_tags", {}).get("op")) is not None:
+ span["op"] = op
+
+ # TODO: Add Relay's enrichment here.
+
+ # Calculate grouping hashes for performance issue detection
+ config = load_span_grouping_config()
+ groupings = config.execute_strategy_standalone(spans)
+ groupings.write_to_spans(spans)
+
+
+def _create_models(segment: Span, project: Project) -> None:
"""
Creates the Environment and Release models, along with the necessary
relationships between them and the Project model.
@@ -168,7 +188,7 @@ def _create_models(segment: SegmentSpan, project: Project) -> None:
environment_name = sentry_tags.get("environment")
release_name = sentry_tags.get("release")
dist_name = sentry_tags.get("dist")
- date = to_datetime(segment["end_timestamp_precise"]) # type: ignore[typeddict-item]
+ date = to_datetime(segment["end_timestamp_precise"])
environment = Environment.get_or_create(project=project, name=environment_name)
@@ -193,9 +213,7 @@ def _create_models(segment: SegmentSpan, project: Project) -> None:
)
-def transform_spans_to_event_dict(
- segment_span: SegmentSpan, spans: list[SegmentSpan]
-) -> dict[str, Any]:
+def transform_spans_to_event_dict(segment_span: Span, spans: list[Span]) -> dict[str, Any]:
event_spans: list[dict[str, Any]] = []
sentry_tags = segment_span.get("sentry_tags", {})
@@ -215,6 +233,7 @@ def transform_spans_to_event_dict(
"type": "trace",
"op": sentry_tags.get("transaction.op"),
"span_id": segment_span["span_id"],
+ "hash": segment_span["hash"],
}
if (profile_id := segment_span.get("profile_id")) is not None:
@@ -222,13 +241,8 @@ def transform_spans_to_event_dict(
for span in spans:
event_span = cast(dict[str, Any], deepcopy(span))
-
- if (op := span.get("sentry_tags", {}).get("op")) is not None:
- event_span["op"] = op
-
event_span["start_timestamp"] = span["start_timestamp_ms"] / 1000
event_span["timestamp"] = (span["start_timestamp_ms"] + span["duration_ms"]) / 1000
-
event_spans.append(event_span)
# The performance detectors expect the span list to be ordered/flattened in the way they
@@ -256,7 +270,7 @@ def prepare_event_for_occurrence_consumer(event):
return event_light
-def process_segment(spans: list[SegmentSpan]) -> list[SegmentSpan]:
+def process_segment(spans: list[Span]) -> list[Span]:
segment_span = _find_segment_span(spans)
if segment_span is None:
# TODO: Handle segments without a defined segment span once all
@@ -270,12 +284,12 @@ def process_segment(spans: list[SegmentSpan]) -> list[SegmentSpan]:
# exact order, where only operations marked with X are relevant to the spans
# consumer:
#
- # - [ ] _pull_out_data
+ # - [X] _pull_out_data -> _enrich_spans
# - [X] _get_or_create_release_many -> _create_models
# - [ ] _get_event_user_many
# - [ ] _derive_plugin_tags_many
# - [ ] _derive_interface_tags_many
- # - [X] _calculate_span_grouping
+ # - [X] _calculate_span_grouping -> _enrich_spans
# - [ ] _materialize_metadata_many
# - [X] _get_or_create_environment_many -> _create_models
# - [X] _get_or_create_release_associated_models -> _create_models
@@ -288,6 +302,7 @@ def process_segment(spans: list[SegmentSpan]) -> list[SegmentSpan]:
# - [X] _send_occurrence_to_platform
# - [X] _record_transaction_info
+ _enrich_spans(segment_span, spans)
_create_models(segment_span, project)
# XXX: Below are old-style functions imported from EventManager that rely on
@@ -308,7 +323,6 @@ def process_segment(spans: list[SegmentSpan]) -> list[SegmentSpan]:
]
_pull_out_data(jobs, projects)
- _calculate_span_grouping(jobs, projects)
if options.get("standalone-spans.detect-performance-problems.enable"):
_detect_performance_problems(jobs, projects, is_standalone_spans=True)
diff --git a/src/sentry/spans/grouping/result.py b/src/sentry/spans/grouping/result.py
index 42c74fc176e033..572228d43fa33f 100644
--- a/src/sentry/spans/grouping/result.py
+++ b/src/sentry/spans/grouping/result.py
@@ -53,3 +53,9 @@ def write_to_event(self, event_data: Any) -> None:
trace_context["hash"] = span_hash
event_data["span_grouping_config"] = {"id": self.id}
+
+ def write_to_spans(self, spans: list[Any]) -> None:
+ for span in spans:
+ span_hash = self.results.get(span["span_id"])
+ if span_hash is not None:
+ span["hash"] = span_hash
diff --git a/src/sentry/spans/grouping/strategy/base.py b/src/sentry/spans/grouping/strategy/base.py
index 32a69a27d195e6..5ded6b1b97d06d 100644
--- a/src/sentry/spans/grouping/strategy/base.py
+++ b/src/sentry/spans/grouping/strategy/base.py
@@ -11,6 +11,7 @@ class Span(TypedDict):
trace_id: str
parent_span_id: str
span_id: str
+ is_segment: NotRequired[bool]
start_timestamp: float
timestamp: float
same_process_as_parent: bool
@@ -19,6 +20,7 @@ class Span(TypedDict):
fingerprint: Sequence[str] | None
tags: Any | None
data: Any | None
+ sentry_tags: NotRequired[dict[str, str]]
hash: NotRequired[str]
@@ -38,7 +40,7 @@ class SpanGroupingStrategy:
def execute(self, event_data: Any) -> dict[str, str]:
spans = event_data.get("spans", [])
- span_groups = {span["span_id"]: self.get_span_group(span) for span in spans}
+ span_groups = {span["span_id"]: self.get_embedded_span_group(span) for span in spans}
# make sure to get the group id for the transaction root span
span_id = event_data["contexts"]["trace"]["span_id"]
@@ -46,12 +48,27 @@ def execute(self, event_data: Any) -> dict[str, str]:
return span_groups
+ def execute_standalone(self, spans: list[Any]) -> dict[str, str]:
+ return {span["span_id"]: self.get_standalone_span_group(span) for span in spans}
+
+ def get_standalone_span_group(self, span: Span) -> str:
+ # Treat the segment span like get_transaction_span_group for backwards
+ # compatibility with transaction events, but fall back to default
+ # fingerprinting if the span doesn't have a transaction.
+ sentry_tags = span.get("sentry_tags") or {}
+ if span.get("is_segment") and sentry_tags.get("transaction") is not None:
+ result = Hash()
+ result.update(sentry_tags["transaction"])
+ return result.hexdigest()
+ else:
+ return self.get_embedded_span_group(span)
+
def get_transaction_span_group(self, event_data: Any) -> str:
result = Hash()
result.update(event_data["transaction"])
return result.hexdigest()
- def get_span_group(self, span: Span) -> str:
+ def get_embedded_span_group(self, span: Span) -> str:
fingerprints = span.get("fingerprint") or ["{{ default }}"]
result = Hash()
diff --git a/src/sentry/spans/grouping/strategy/config.py b/src/sentry/spans/grouping/strategy/config.py
index e106d747552a43..fe96a628ea63c2 100644
--- a/src/sentry/spans/grouping/strategy/config.py
+++ b/src/sentry/spans/grouping/strategy/config.py
@@ -30,6 +30,10 @@ def execute_strategy(self, event_data: Any) -> SpanGroupingResults:
results = self.strategy.execute(event_data)
return SpanGroupingResults(self.id, results)
+ def execute_strategy_standalone(self, spans: list[Any]) -> SpanGroupingResults:
+ results = self.strategy.execute_standalone(spans)
+ return SpanGroupingResults(self.id, results)
+
CONFIGURATIONS: dict[str, SpanGroupingConfig] = {}
diff --git a/src/sentry/testutils/performance_issues/span_builder.py b/src/sentry/testutils/performance_issues/span_builder.py
index 6ada22c3f24152..5e0ff051ad262f 100644
--- a/src/sentry/testutils/performance_issues/span_builder.py
+++ b/src/sentry/testutils/performance_issues/span_builder.py
@@ -8,6 +8,7 @@ def __init__(self) -> None:
self.trace_id = "a" * 32
self.parent_span_id = "a" * 16
self.span_id = "b" * 16
+ self.is_segment = False
self.start_timestamp: float = 0
self.timestamp: float = 1
self.same_process_as_parent = True
@@ -16,8 +17,13 @@ def __init__(self) -> None:
self.fingerprint: list[str] | None = None
self.tags: Any | None = None
self.data: Any | None = None
+ self.sentry_tags: dict[str, str] = {}
self.hash: str | None = None
+ def segment(self) -> "SpanBuilder":
+ self.is_segment = True
+ return self
+
def with_op(self, op: str) -> "SpanBuilder":
self.op = op
return self
@@ -42,11 +48,16 @@ def with_data(self, data: dict) -> "SpanBuilder":
self.data = data
return self
+ def with_sentry_tag(self, key: str, value: str) -> "SpanBuilder":
+ self.sentry_tags[key] = value
+ return self
+
def build(self) -> Span:
span: Span = {
"trace_id": self.trace_id,
"parent_span_id": self.parent_span_id,
"span_id": self.span_id,
+ "is_segment": self.is_segment,
"start_timestamp": self.start_timestamp,
"timestamp": self.timestamp,
"same_process_as_parent": self.same_process_as_parent,
@@ -56,6 +67,8 @@ def build(self) -> Span:
"tags": self.tags,
"data": self.data,
}
+ if self.sentry_tags:
+ span["sentry_tags"] = self.sentry_tags
if self.hash is not None:
span["hash"] = self.hash
return span
diff --git a/tests/sentry/spans/grouping/test_strategy.py b/tests/sentry/spans/grouping/test_strategy.py
index f2f515b1e4969a..b832f91445e491 100644
--- a/tests/sentry/spans/grouping/test_strategy.py
+++ b/tests/sentry/spans/grouping/test_strategy.py
@@ -14,6 +14,7 @@
)
from sentry.spans.grouping.strategy.config import (
CONFIGURATIONS,
+ DEFAULT_CONFIG_ID,
SpanGroupingConfig,
register_configuration,
)
@@ -584,3 +585,32 @@ def test_default_2022_10_27_strategy(spans: list[Span], expected: Mapping[str, l
key: hash_values(values)
for key, values in {**expected, "a" * 16: ["transaction name"]}.items()
}
+
+
+def test_standalone_spans_compat() -> None:
+ spans = [
+ SpanBuilder().with_span_id("b" * 16).with_description("b" * 16).build(),
+ SpanBuilder().with_span_id("c" * 16).with_description("c" * 16).build(),
+ SpanBuilder().with_span_id("d" * 16).with_description("d" * 16).build(),
+ ]
+
+ event = {
+ "transaction": "transaction name",
+ "contexts": {
+ "trace": {
+ "span_id": "a" * 16,
+ },
+ },
+ "spans": spans,
+ }
+
+ standalone_spans = spans + [
+ SpanBuilder()
+ .with_span_id("a" * 16)
+ .segment()
+ .with_sentry_tag("transaction", "transaction name")
+ .build()
+ ]
+
+ cfg = CONFIGURATIONS[DEFAULT_CONFIG_ID]
+ assert cfg.execute_strategy(event) == cfg.execute_strategy_standalone(standalone_spans)
|
37472b11db4ba5dbee32c94fafbe30b4e8ac4c15
|
2022-02-16 05:40:24
|
Scott Cooper
|
feat(teamStats): Filter team issues endpoints by environment (#31697)
| false
|
Filter team issues endpoints by environment (#31697)
|
feat
|
diff --git a/src/sentry/api/endpoints/team_groups_old.py b/src/sentry/api/endpoints/team_groups_old.py
index 5c0ce042d8d9f5..5d4b62f53ebbcd 100644
--- a/src/sentry/api/endpoints/team_groups_old.py
+++ b/src/sentry/api/endpoints/team_groups_old.py
@@ -1,10 +1,12 @@
from datetime import datetime, timedelta
+from django.db.models import Q
from rest_framework.request import Request
from rest_framework.response import Response
from sentry.api.base import EnvironmentMixin
from sentry.api.bases.team import TeamEndpoint
+from sentry.api.helpers.environments import get_environments
from sentry.api.serializers import GroupSerializer, serialize
from sentry.models import Group, GroupStatus
@@ -15,9 +17,15 @@ def get(self, request: Request, team) -> Response:
Return the oldest issues owned by a team
"""
limit = min(100, int(request.GET.get("limit", 10)))
+ environments = [e.id for e in get_environments(request, team.organization)]
+ group_environment_filter = (
+ Q(groupenvironment__environment_id=environments[0]) if environments else Q()
+ )
+
group_list = list(
Group.objects.filter_to_team(team)
.filter(
+ group_environment_filter,
status=GroupStatus.UNRESOLVED,
last_seen__gt=datetime.now() - timedelta(days=90),
)
diff --git a/src/sentry/api/endpoints/team_issue_breakdown.py b/src/sentry/api/endpoints/team_issue_breakdown.py
index 57ab44205d2a0d..89eb0e2a1ea001 100644
--- a/src/sentry/api/endpoints/team_issue_breakdown.py
+++ b/src/sentry/api/endpoints/team_issue_breakdown.py
@@ -2,7 +2,7 @@
from datetime import timedelta
from itertools import chain
-from django.db.models import Count, IntegerField, Value
+from django.db.models import Count, IntegerField, Q, Value
from django.db.models.functions import TruncDay
from rest_framework.request import Request
from rest_framework.response import Response
@@ -10,6 +10,7 @@
from sentry import features
from sentry.api.base import EnvironmentMixin
from sentry.api.bases.team import TeamEndpoint
+from sentry.api.helpers.environments import get_environments
from sentry.api.utils import get_date_range_from_params
from sentry.models import Group, GroupHistory, GroupHistoryStatus, Project, Team
from sentry.models.grouphistory import (
@@ -32,6 +33,7 @@ def get(self, request: Request, team: Team) -> Response:
start, end = get_date_range_from_params(request.GET)
end = end.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)
start = start.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)
+ environments = [e.id for e in get_environments(request, team.organization)]
if "statuses" in request.GET:
statuses = [
@@ -52,10 +54,13 @@ def get(self, request: Request, team: Team) -> Response:
base_day_format["reviewed"] = 0
if GroupHistoryStatus.NEW in statuses:
+ group_environment_filter = (
+ Q(groupenvironment__environment_id=environments[0]) if environments else Q()
+ )
statuses.remove(GroupHistoryStatus.NEW)
new_issues = list(
Group.objects.filter_to_team(team)
- .filter(first_seen__gte=start, first_seen__lte=end)
+ .filter(group_environment_filter, first_seen__gte=start, first_seen__lte=end)
.annotate(bucket=TruncDay("first_seen"))
.order_by("bucket")
.values("project", "bucket")
@@ -65,9 +70,13 @@ def get(self, request: Request, team: Team) -> Response:
)
)
+ group_history_enviornment_filter = (
+ Q(group__groupenvironment__environment_id=environments[0]) if environments else Q()
+ )
bucketed_issues = (
GroupHistory.objects.filter_to_team(team)
.filter(
+ group_history_enviornment_filter,
status__in=statuses,
date_added__gte=start,
date_added__lte=end,
diff --git a/src/sentry/api/endpoints/team_time_to_resolution.py b/src/sentry/api/endpoints/team_time_to_resolution.py
index 6443387c2e34ce..54021585b5fd81 100644
--- a/src/sentry/api/endpoints/team_time_to_resolution.py
+++ b/src/sentry/api/endpoints/team_time_to_resolution.py
@@ -1,7 +1,7 @@
from collections import defaultdict
from datetime import timedelta
-from django.db.models import Avg, F
+from django.db.models import Avg, F, Q
from django.db.models.functions import Coalesce, TruncDay
from rest_framework.request import Request
from rest_framework.response import Response
@@ -9,6 +9,7 @@
from sentry import features
from sentry.api.base import EnvironmentMixin
from sentry.api.bases.team import TeamEndpoint
+from sentry.api.helpers.environments import get_environments
from sentry.api.utils import get_date_range_from_params
from sentry.models import GroupHistory, GroupHistoryStatus
@@ -24,9 +25,15 @@ def get(self, request: Request, team) -> Response:
start, end = get_date_range_from_params(request.GET)
end = end.date() + timedelta(days=1)
start = start.date() + timedelta(days=1)
+ environments = [e.id for e in get_environments(request, team.organization)]
+ grouphistory_environment_filter = (
+ Q(group__groupenvironment__environment_id=environments[0]) if environments else Q()
+ )
+
history_list = (
GroupHistory.objects.filter_to_team(team)
.filter(
+ grouphistory_environment_filter,
status=GroupHistoryStatus.RESOLVED,
date_added__gte=start,
date_added__lte=end,
diff --git a/src/sentry/api/endpoints/team_unresolved_issue_age.py b/src/sentry/api/endpoints/team_unresolved_issue_age.py
index 70d818acb463e0..18d0d15b896d17 100644
--- a/src/sentry/api/endpoints/team_unresolved_issue_age.py
+++ b/src/sentry/api/endpoints/team_unresolved_issue_age.py
@@ -1,12 +1,14 @@
from datetime import datetime, timedelta
-from django.db.models import Case, Count, TextField, Value, When
+from django.db.models import Case, Count, Q, TextField, Value, When
from django.utils import timezone
from rest_framework.request import Request
from rest_framework.response import Response
from sentry import features
+from sentry.api.base import EnvironmentMixin
from sentry.api.bases.team import TeamEndpoint
+from sentry.api.helpers.environments import get_environments
from sentry.models import Group, GroupStatus, Team
buckets = (
@@ -22,7 +24,7 @@
OLDEST_LABEL = "> 1 year"
-class TeamUnresolvedIssueAgeEndpoint(TeamEndpoint): # type: ignore
+class TeamUnresolvedIssueAgeEndpoint(TeamEndpoint, EnvironmentMixin): # type: ignore
def get(self, request: Request, team: Team) -> Response:
"""
Return a time bucketed list of how old unresolved issues are.
@@ -30,10 +32,16 @@ def get(self, request: Request, team: Team) -> Response:
if not features.has("organizations:team-insights", team.organization, actor=request.user):
return Response({"detail": "You do not have the insights feature enabled"}, status=400)
+ environments = [e.id for e in get_environments(request, team.organization)]
+ group_environment_filter = (
+ Q(groupenvironment__environment_id=environments[0]) if environments else Q()
+ )
+
current_time = timezone.now()
unresolved_ages = list(
Group.objects.filter_to_team(team)
.filter(
+ group_environment_filter,
status=GroupStatus.UNRESOLVED,
last_seen__gt=datetime.now() - timedelta(days=90),
)
diff --git a/tests/sentry/api/endpoints/test_team_groups_old.py b/tests/sentry/api/endpoints/test_team_groups_old.py
index d4d52021aee995..75a83193b564b1 100644
--- a/tests/sentry/api/endpoints/test_team_groups_old.py
+++ b/tests/sentry/api/endpoints/test_team_groups_old.py
@@ -2,7 +2,7 @@
from django.utils import timezone
-from sentry.models import GroupAssignee, GroupStatus
+from sentry.models import GroupAssignee, GroupEnvironment, GroupStatus
from sentry.testutils import APITestCase
@@ -51,3 +51,26 @@ def test_simple(self):
self.login_as(user=self.user)
response = self.get_success_response(self.organization.slug, self.team.slug)
assert [group["id"] for group in response.data] == [str(group2.id), str(group1.id)]
+
+ def test_filter_by_environment(self):
+ project1 = self.create_project(teams=[self.team], slug="foo")
+ environment = self.create_environment(name="prod", project=project1)
+ self.create_environment(name="dev", project=project1)
+ group1 = self.create_group(
+ checksum="a" * 32,
+ project=project1,
+ first_seen=datetime(2018, 1, 12, 3, 8, 25, tzinfo=timezone.utc),
+ )
+ GroupAssignee.objects.assign(group1, self.user)
+ GroupEnvironment.objects.create(group_id=group1.id, environment_id=environment.id)
+
+ self.login_as(user=self.user)
+ response = self.get_success_response(
+ self.organization.slug, self.team.slug, environment="prod"
+ )
+ assert [group["id"] for group in response.data] == [str(group1.id)]
+
+ response = self.get_success_response(
+ self.organization.slug, self.team.slug, environment="dev"
+ )
+ assert [group["id"] for group in response.data] == []
diff --git a/tests/sentry/api/endpoints/test_team_issue_breakdown.py b/tests/sentry/api/endpoints/test_team_issue_breakdown.py
index 5f351168441f48..8a15e816b5a8e9 100644
--- a/tests/sentry/api/endpoints/test_team_issue_breakdown.py
+++ b/tests/sentry/api/endpoints/test_team_issue_breakdown.py
@@ -4,7 +4,7 @@
from django.utils.timezone import now
from freezegun import freeze_time
-from sentry.models import GroupAssignee, GroupHistoryStatus
+from sentry.models import GroupAssignee, GroupEnvironment, GroupHistoryStatus
from sentry.testutils import APITestCase
from sentry.testutils.helpers.datetime import before_now
@@ -100,6 +100,58 @@ def compare_response(statuses, data_for_day, **expected_status_counts):
compare_response(statuses, response.data[project2.id][yesterday])
compare_response(statuses, response.data[project2.id][two_days_ago])
+ def test_filter_by_environment(self):
+ project1 = self.create_project(teams=[self.team], slug="foo")
+ group1 = self.create_group(checksum="a" * 32, project=project1)
+ env1 = self.create_environment(name="prod", project=project1)
+ self.create_environment(name="dev", project=project1)
+ GroupAssignee.objects.assign(group1, self.user)
+ GroupEnvironment.objects.create(group_id=group1.id, environment_id=env1.id)
+
+ self.create_group_history(
+ group=group1, date_added=now(), status=GroupHistoryStatus.UNRESOLVED
+ )
+ self.create_group_history(
+ group=group1, date_added=now(), status=GroupHistoryStatus.RESOLVED
+ )
+ self.create_group_history(
+ group=group1, date_added=now(), status=GroupHistoryStatus.REGRESSED
+ )
+
+ today = str(
+ now()
+ .replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=timezone.utc)
+ .isoformat()
+ )
+ self.login_as(user=self.user)
+ statuses = ["regressed", "resolved"]
+ response = self.get_success_response(
+ self.team.organization.slug,
+ self.team.slug,
+ statsPeriod="7d",
+ statuses=statuses,
+ environment="prod",
+ )
+
+ def compare_response(statuses, data_for_day, **expected_status_counts):
+ result = {status: 0 for status in statuses}
+ result["total"] = 0
+ result.update(expected_status_counts)
+ assert result == data_for_day
+
+ compare_response(
+ statuses, response.data[project1.id][today], regressed=1, resolved=1, total=2
+ )
+
+ response = self.get_success_response(
+ self.team.organization.slug,
+ self.team.slug,
+ statsPeriod="7d",
+ statuses=statuses,
+ environment="dev",
+ )
+ compare_response(statuses, response.data[project1.id][today])
+
def test_old_format(self):
project1 = self.create_project(teams=[self.team], slug="foo")
project2 = self.create_project(teams=[self.team], slug="bar")
diff --git a/tests/sentry/api/endpoints/test_team_time_to_resolution.py b/tests/sentry/api/endpoints/test_team_time_to_resolution.py
index 376d598ec5936f..ebd3c64f8ee83f 100644
--- a/tests/sentry/api/endpoints/test_team_time_to_resolution.py
+++ b/tests/sentry/api/endpoints/test_team_time_to_resolution.py
@@ -3,7 +3,7 @@
from django.utils.timezone import now
from freezegun import freeze_time
-from sentry.models import GroupAssignee, GroupHistoryStatus
+from sentry.models import GroupAssignee, GroupEnvironment, GroupHistoryStatus
from sentry.testutils import APITestCase
from sentry.testutils.helpers.datetime import before_now
@@ -95,3 +95,46 @@ def test_simple(self):
assert response.data[today]["avg"] == timedelta(days=11, hours=16).total_seconds()
assert response.data[two_days_ago]["avg"] == timedelta(days=3).total_seconds()
assert response.data[yesterday]["avg"] == 0
+
+ def test_filter_by_environment(self):
+ project1 = self.create_project(teams=[self.team], slug="foo")
+ group1 = self.create_group(checksum="a" * 32, project=project1, times_seen=10)
+ env1 = self.create_environment(project=project1, name="prod")
+ self.create_environment(project=project1, name="dev")
+ GroupAssignee.objects.assign(group1, self.user)
+ GroupEnvironment.objects.create(group_id=group1.id, environment_id=env1.id)
+
+ gh1 = self.create_group_history(
+ group1,
+ GroupHistoryStatus.UNRESOLVED,
+ actor=self.user.actor,
+ date_added=before_now(days=5),
+ )
+
+ self.create_group_history(
+ group1,
+ GroupHistoryStatus.RESOLVED,
+ actor=self.user.actor,
+ prev_history=gh1,
+ date_added=before_now(days=2),
+ )
+
+ today = str(now().date())
+ yesterday = str((now() - timedelta(days=1)).date())
+ two_days_ago = str((now() - timedelta(days=2)).date())
+ self.login_as(user=self.user)
+ response = self.get_success_response(
+ self.team.organization.slug, self.team.slug, statsPeriod="14d", environment="prod"
+ )
+ assert len(response.data) == 14
+ assert response.data[today]["avg"] == 0
+ assert response.data[two_days_ago]["avg"] == timedelta(days=3).total_seconds()
+ assert response.data[yesterday]["avg"] == 0
+
+ response = self.get_success_response(
+ self.team.organization.slug, self.team.slug, environment="dev"
+ )
+ assert len(response.data) == 90
+ assert response.data[today]["avg"] == 0
+ assert response.data[two_days_ago]["avg"] == 0
+ assert response.data[yesterday]["avg"] == 0
diff --git a/tests/sentry/api/endpoints/test_team_unresolved_issue_age.py b/tests/sentry/api/endpoints/test_team_unresolved_issue_age.py
index 8783d4387b515b..7789671208d18b 100644
--- a/tests/sentry/api/endpoints/test_team_unresolved_issue_age.py
+++ b/tests/sentry/api/endpoints/test_team_unresolved_issue_age.py
@@ -1,6 +1,6 @@
from freezegun import freeze_time
-from sentry.models import GroupAssignee, GroupStatus
+from sentry.models import GroupAssignee, GroupEnvironment, GroupStatus
from sentry.testutils import APITestCase
from sentry.testutils.helpers.datetime import before_now
@@ -57,6 +57,45 @@ def test_simple(self):
"> 1 year": 2,
}
+ def test_environment_filter(self):
+ project1 = self.create_project(teams=[self.team], slug="foo")
+ env1 = self.create_environment(project=project1, name="prod")
+ self.create_environment(project=project1, name="dev")
+ group1 = self.create_group(project=project1)
+ GroupEnvironment.objects.create(group_id=group1.id, environment_id=env1.id)
+ GroupAssignee.objects.assign(group1, self.user)
+
+ self.login_as(user=self.user)
+ response = self.get_success_response(
+ self.team.organization.slug, self.team.slug, environment="prod"
+ )
+ assert response.data == {
+ "< 1 hour": 1,
+ "< 4 hour": 0,
+ "< 12 hour": 0,
+ "< 1 day": 0,
+ "< 1 week": 0,
+ "< 4 week": 0,
+ "< 24 week": 0,
+ "< 1 year": 0,
+ "> 1 year": 0,
+ }
+
+ response = self.get_success_response(
+ self.team.organization.slug, self.team.slug, environment="dev"
+ )
+ assert response.data == {
+ "< 1 hour": 0,
+ "< 4 hour": 0,
+ "< 12 hour": 0,
+ "< 1 day": 0,
+ "< 1 week": 0,
+ "< 4 week": 0,
+ "< 24 week": 0,
+ "< 1 year": 0,
+ "> 1 year": 0,
+ }
+
def test_empty(self):
self.login_as(user=self.user)
response = self.get_success_response(self.team.organization.slug, self.team.slug)
|
716750f4dd681eed03573e3bec88747093a78bec
|
2024-06-26 09:24:01
|
ArthurKnaus
|
feat(metrics): Limit query operators (#73271)
| false
|
Limit query operators (#73271)
|
feat
|
diff --git a/static/app/components/searchSyntax/parser.spec.tsx b/static/app/components/searchSyntax/parser.spec.tsx
index 250e1f743412ca..fb59ab8d2fb25a 100644
--- a/static/app/components/searchSyntax/parser.spec.tsx
+++ b/static/app/components/searchSyntax/parser.spec.tsx
@@ -208,6 +208,29 @@ describe('searchSyntax/parser', function () {
});
});
+ it('applies disallowNegation', () => {
+ const result = parseSearch('!foo:bar', {
+ disallowNegation: true,
+ invalidMessages: {
+ [InvalidReason.NEGATION_NOT_ALLOWED]: 'Custom message',
+ },
+ });
+
+ // check with error to satisfy type checker
+ if (result === null) {
+ throw new Error('Parsed result as null');
+ }
+ expect(result).toHaveLength(3);
+
+ const foo = result[1] as TokenResult<Token.FILTER>;
+
+ expect(foo.negated).toEqual(true);
+ expect(foo.invalid).toEqual({
+ type: InvalidReason.NEGATION_NOT_ALLOWED,
+ reason: 'Custom message',
+ });
+ });
+
describe('flattenParenGroups', () => {
it('tokenizes mismatched parens with flattenParenGroups=true', () => {
const result = parseSearch('foo(', {
diff --git a/static/app/components/searchSyntax/parser.tsx b/static/app/components/searchSyntax/parser.tsx
index 58408bbdcaad32..485d938417e733 100644
--- a/static/app/components/searchSyntax/parser.tsx
+++ b/static/app/components/searchSyntax/parser.tsx
@@ -259,6 +259,7 @@ export enum InvalidReason {
WILDCARD_NOT_ALLOWED = 'wildcard-not-allowed',
LOGICAL_OR_NOT_ALLOWED = 'logic-or-not-allowed',
LOGICAL_AND_NOT_ALLOWED = 'logic-and-not-allowed',
+ NEGATION_NOT_ALLOWED = 'negation-not-allowed',
MUST_BE_QUOTED = 'must-be-quoted',
FILTER_MUST_HAVE_VALUE = 'filter-must-have-value',
INVALID_BOOLEAN = 'invalid-boolean',
@@ -407,7 +408,7 @@ export class TokenConverter {
value,
negated,
operator: operator ?? TermOperator.DEFAULT,
- invalid: this.checkInvalidFilter(filter, key, value),
+ invalid: this.checkInvalidFilter(filter, key, value, negated),
warning: this.checkFilterWarning(key),
} as FilterResult;
@@ -756,7 +757,8 @@ export class TokenConverter {
checkInvalidFilter = <T extends FilterType>(
filter: T,
key: FilterMap[T]['key'],
- value: FilterMap[T]['value']
+ value: FilterMap[T]['value'],
+ negated: FilterMap[T]['negated']
) => {
// Text filter is the "fall through" filter that will match when other
// filter predicates fail.
@@ -771,6 +773,13 @@ export class TokenConverter {
};
}
+ if (this.config.disallowNegation && negated) {
+ return {
+ type: InvalidReason.NEGATION_NOT_ALLOWED,
+ reason: this.config.invalidMessages[InvalidReason.NEGATION_NOT_ALLOWED],
+ };
+ }
+
if (filter === FilterType.TEXT) {
return this.checkInvalidTextFilter(
key as TextFilter['key'],
@@ -1172,6 +1181,10 @@ export type SearchConfig = {
* Disallow free text search
*/
disallowFreeText: boolean;
+ /**
+ * Disallow negation for filters
+ */
+ disallowNegation: boolean;
/**
* Disallow wildcards in free text search AND in tag values
*/
@@ -1268,6 +1281,7 @@ export const defaultConfig: SearchConfig = {
disallowedLogicalOperators: new Set(),
disallowFreeText: false,
disallowWildcard: false,
+ disallowNegation: false,
invalidMessages: {
[InvalidReason.FREE_TEXT_NOT_ALLOWED]: t('Free text is not supported in this search'),
[InvalidReason.WILDCARD_NOT_ALLOWED]: t('Wildcards not supported in search'),
@@ -1278,6 +1292,7 @@ export const defaultConfig: SearchConfig = {
'The AND operator is not allowed in this search'
),
[InvalidReason.MUST_BE_QUOTED]: t('Quotes must enclose text or be escaped'),
+ [InvalidReason.NEGATION_NOT_ALLOWED]: t('Negation is not allowed in this search.'),
[InvalidReason.FILTER_MUST_HAVE_VALUE]: t('Filter must have a value'),
[InvalidReason.INVALID_BOOLEAN]: t('Invalid boolean. Expected true, 1, false, or 0.'),
[InvalidReason.INVALID_FILE_SIZE]: t(
diff --git a/static/app/components/smartSearchBar/index.tsx b/static/app/components/smartSearchBar/index.tsx
index 3cf96c82d18a82..32bf2349625909 100644
--- a/static/app/components/smartSearchBar/index.tsx
+++ b/static/app/components/smartSearchBar/index.tsx
@@ -140,6 +140,7 @@ const pickParserOptions = (props: Props) => {
disallowedLogicalOperators,
disallowWildcard,
disallowFreeText,
+ disallowNegation,
invalidMessages,
} = props;
@@ -157,6 +158,7 @@ const pickParserOptions = (props: Props) => {
disallowedLogicalOperators,
disallowWildcard,
disallowFreeText,
+ disallowNegation,
invalidMessages,
} satisfies Partial<SearchConfig>;
};
@@ -264,6 +266,10 @@ type Props = WithRouterProps &
* Disables free text searches
*/
disallowFreeText?: boolean;
+ /**
+ * Disables negation searches
+ */
+ disallowNegation?: boolean;
/**
* Disables wildcard searches (in freeText and in the value of key:value searches mode)
*/
@@ -1627,7 +1633,10 @@ class SmartSearchBar extends Component<DefaultProps & Props, State> {
// show operator group if at beginning of value
if (cursor === node.location.start.offset) {
- const opGroup = generateOpAutocompleteGroup(getValidOps(cursorToken), tagName);
+ const opGroup = generateOpAutocompleteGroup(
+ getValidOps(cursorToken, !!this.props.disallowNegation),
+ tagName
+ );
if (valueGroup?.type !== ItemType.INVALID_TAG && !isDate) {
autocompleteGroups.unshift(opGroup);
}
@@ -1645,7 +1654,10 @@ class SmartSearchBar extends Component<DefaultProps & Props, State> {
const autocompleteGroups = [await this.generateTagAutocompleteGroup(tagName)];
// show operator group if at end of key
if (cursor === node.location.end.offset) {
- const opGroup = generateOpAutocompleteGroup(getValidOps(cursorToken), tagName);
+ const opGroup = generateOpAutocompleteGroup(
+ getValidOps(cursorToken, !!this.props.disallowNegation),
+ tagName
+ );
autocompleteGroups.unshift(opGroup);
}
@@ -1660,7 +1672,10 @@ class SmartSearchBar extends Component<DefaultProps & Props, State> {
}
// show operator autocomplete group
- const opGroup = generateOpAutocompleteGroup(getValidOps(cursorToken), tagName);
+ const opGroup = generateOpAutocompleteGroup(
+ getValidOps(cursorToken, !!this.props.disallowNegation),
+ tagName
+ );
this.updateAutoCompleteStateMultiHeader([opGroup]);
return;
}
diff --git a/static/app/components/smartSearchBar/utils.tsx b/static/app/components/smartSearchBar/utils.tsx
index f7cca26da715f8..ea3d900aa6e1b2 100644
--- a/static/app/components/smartSearchBar/utils.tsx
+++ b/static/app/components/smartSearchBar/utils.tsx
@@ -318,7 +318,8 @@ export function generateOperatorEntryMap(tag: string) {
}
export function getValidOps(
- filterToken: TokenResult<Token.FILTER>
+ filterToken: TokenResult<Token.FILTER>,
+ disallowNegation: boolean
): readonly TermOperator[] {
// If the token is invalid we want to use the possible expected types as our filter type
const validTypes = filterToken.invalid?.expectedType ?? [filterToken.filter];
@@ -336,6 +337,10 @@ export function getValidOps(
allValidTypes.flatMap(type => filterTypeConfig[type].validOps)
);
+ if (disallowNegation) {
+ validOps.delete(TermOperator.NOT_EQUAL);
+ }
+
return [...validOps];
}
diff --git a/static/app/views/settings/projectMetrics/metricsExtractionRuleForm.tsx b/static/app/views/settings/projectMetrics/metricsExtractionRuleForm.tsx
index 7f43d1b2116f4b..7218745e27a104 100644
--- a/static/app/views/settings/projectMetrics/metricsExtractionRuleForm.tsx
+++ b/static/app/views/settings/projectMetrics/metricsExtractionRuleForm.tsx
@@ -68,6 +68,20 @@ const TYPE_OPTIONS = [
},
];
+const EMPTY_SET = new Set<never>();
+const SPAN_SEARCH_CONFIG = {
+ booleanKeys: EMPTY_SET,
+ dateKeys: EMPTY_SET,
+ durationKeys: EMPTY_SET,
+ numericKeys: EMPTY_SET,
+ percentageKeys: EMPTY_SET,
+ sizeKeys: EMPTY_SET,
+ textOperatorKeys: EMPTY_SET,
+ disallowFreeText: true,
+ disallowWildcard: true,
+ disallowNegation: true,
+};
+
export function MetricsExtractionRuleForm({isEdit, project, onSubmit, ...props}: Props) {
const [customAttributes, setCustomeAttributes] = useState<string[]>(() => {
const {spanAttribute, tags} = props.initialData;
@@ -188,6 +202,7 @@ export function MetricsExtractionRuleForm({isEdit, project, onSubmit, ...props}:
<SearchWrapper hasPrefix={index !== 0}>
{index !== 0 && <ConditionLetter>{t('or')}</ConditionLetter>}
<SearchBar
+ {...SPAN_SEARCH_CONFIG}
searchSource="metrics-extraction"
query={query}
onSearch={(queryString: string) =>
|
f461c596fa0fbf2d6cc253069bf48abc69ca78eb
|
2023-12-11 22:36:57
|
Ryan Albrecht
|
test: Replace TestStubs.routerContext calls with RouterContextFixture imports (#61508)
| false
|
Replace TestStubs.routerContext calls with RouterContextFixture imports (#61508)
|
test
|
diff --git a/static/app/components/acl/access.spec.tsx b/static/app/components/acl/access.spec.tsx
index 5767a410536290..721d9caca4df40 100644
--- a/static/app/components/acl/access.spec.tsx
+++ b/static/app/components/acl/access.spec.tsx
@@ -1,4 +1,5 @@
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {Team} from 'sentry-fixture/team';
import {render, screen} from 'sentry-test/reactTestingLibrary';
@@ -10,7 +11,7 @@ describe('Access', function () {
const organization = Organization({
access: ['project:write', 'project:read'],
});
- const routerContext = TestStubs.routerContext([{organization}]);
+ const routerContext = RouterContextFixture([{organization}]);
describe('as render prop', function () {
const childrenMock = jest.fn().mockReturnValue(null);
@@ -45,7 +46,7 @@ describe('Access', function () {
it('read access from team', function () {
const org = Organization({access: []});
- const nextRouterContext = TestStubs.routerContext([{organization: org}]);
+ const nextRouterContext = RouterContextFixture([{organization: org}]);
const team1 = Team({access: []});
render(
@@ -82,7 +83,7 @@ describe('Access', function () {
it('read access from project', function () {
const org = Organization({access: []});
- const nextRouterContext = TestStubs.routerContext([{organization: org}]);
+ const nextRouterContext = RouterContextFixture([{organization: org}]);
const proj1 = TestStubs.Project({access: []});
render(
diff --git a/static/app/components/acl/feature.spec.tsx b/static/app/components/acl/feature.spec.tsx
index 21698696b3c8b1..d9e41e6dbe8ed2 100644
--- a/static/app/components/acl/feature.spec.tsx
+++ b/static/app/components/acl/feature.spec.tsx
@@ -1,4 +1,5 @@
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen} from 'sentry-test/reactTestingLibrary';
@@ -13,7 +14,7 @@ describe('Feature', function () {
const project = TestStubs.Project({
features: ['project-foo', 'project-bar'],
});
- const routerContext = TestStubs.routerContext([
+ const routerContext = RouterContextFixture([
{
organization,
project,
diff --git a/static/app/components/acl/role.spec.tsx b/static/app/components/acl/role.spec.tsx
index 12fe52001c72ab..515f3eabc74694 100644
--- a/static/app/components/acl/role.spec.tsx
+++ b/static/app/components/acl/role.spec.tsx
@@ -1,5 +1,6 @@
import Cookies from 'js-cookie';
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen} from 'sentry-test/reactTestingLibrary';
@@ -36,7 +37,7 @@ describe('Role', function () {
},
],
});
- const routerContext = TestStubs.routerContext([
+ const routerContext = RouterContextFixture([
{
organization,
},
diff --git a/static/app/components/assigneeSelector.spec.tsx b/static/app/components/assigneeSelector.spec.tsx
index 92cd476b30e6d8..51ee06b1de71bf 100644
--- a/static/app/components/assigneeSelector.spec.tsx
+++ b/static/app/components/assigneeSelector.spec.tsx
@@ -1,3 +1,4 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {Team} from 'sentry-fixture/team';
import {act, render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
@@ -286,7 +287,7 @@ describe('AssigneeSelector', () => {
it('shows invite member button', async () => {
MemberListStore.loadInitialData([USER_1, USER_2]);
render(<AssigneeSelectorComponent id={GROUP_1.id} />, {
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
});
jest.spyOn(ConfigStore, 'get').mockImplementation(() => true);
diff --git a/static/app/components/breadcrumbs.spec.tsx b/static/app/components/breadcrumbs.spec.tsx
index 40b8801c5aca44..1608a591119986 100644
--- a/static/app/components/breadcrumbs.spec.tsx
+++ b/static/app/components/breadcrumbs.spec.tsx
@@ -1,9 +1,11 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
+
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
import Breadcrumbs from 'sentry/components/breadcrumbs';
describe('Breadcrumbs', () => {
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
afterEach(() => {
jest.resetAllMocks();
diff --git a/static/app/components/commitRow.spec.tsx b/static/app/components/commitRow.spec.tsx
index b9c17b7d393cdb..710edb89756144 100644
--- a/static/app/components/commitRow.spec.tsx
+++ b/static/app/components/commitRow.spec.tsx
@@ -1,3 +1,5 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
+
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
import {textWithMarkupMatcher} from 'sentry-test/utils';
@@ -58,7 +60,7 @@ describe('commitRow', () => {
},
} as Commit;
- render(<CommitRow commit={commit} />, {context: TestStubs.routerContext()});
+ render(<CommitRow commit={commit} />, {context: RouterContextFixture()});
expect(
screen.getByText(
textWithMarkupMatcher(
diff --git a/static/app/components/createAlertButton.spec.tsx b/static/app/components/createAlertButton.spec.tsx
index 4b02c847aed367..96b7605848216c 100644
--- a/static/app/components/createAlertButton.spec.tsx
+++ b/static/app/components/createAlertButton.spec.tsx
@@ -1,4 +1,5 @@
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
@@ -22,7 +23,7 @@ describe('CreateAlertFromViewButton', () => {
});
it('should trigger onClick callback', async () => {
- const context = TestStubs.routerContext();
+ const context = RouterContextFixture();
const eventView = EventView.fromSavedQuery({
...DEFAULT_EVENT_VIEW,
@@ -63,7 +64,7 @@ describe('CreateAlertFromViewButton', () => {
onClick={onClickMock}
/>,
{
- context: TestStubs.routerContext([{organization: noAccessOrg}]),
+ context: RouterContextFixture([{organization: noAccessOrg}]),
organization: noAccessOrg,
}
);
@@ -88,7 +89,7 @@ describe('CreateAlertFromViewButton', () => {
onClick={onClickMock}
/>,
{
- context: TestStubs.routerContext([{organization}]),
+ context: RouterContextFixture([{organization}]),
organization,
}
);
@@ -127,7 +128,7 @@ describe('CreateAlertFromViewButton', () => {
onClick={onClickMock}
/>,
{
- context: TestStubs.routerContext([{organization: noAccessOrg}]),
+ context: RouterContextFixture([{organization: noAccessOrg}]),
organization: noAccessOrg,
}
);
@@ -188,7 +189,7 @@ describe('CreateAlertFromViewButton', () => {
});
it('removes a duplicate project filter', async () => {
- const context = TestStubs.routerContext();
+ const context = RouterContextFixture();
const eventView = EventView.fromSavedQuery({
...DEFAULT_EVENT_VIEW,
diff --git a/static/app/components/dataExport.spec.tsx b/static/app/components/dataExport.spec.tsx
index 35763bf1985db3..a374d623a9569e 100644
--- a/static/app/components/dataExport.spec.tsx
+++ b/static/app/components/dataExport.spec.tsx
@@ -1,4 +1,5 @@
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
@@ -22,7 +23,7 @@ const mockPayload = {
};
const mockRouterContext = (mockOrganization: TOrganization) =>
- TestStubs.routerContext([
+ RouterContextFixture([
{
organization: mockOrganization,
},
diff --git a/static/app/components/deployBadge.spec.tsx b/static/app/components/deployBadge.spec.tsx
index 92389b8ec39cee..0eec75ac24e3ad 100644
--- a/static/app/components/deployBadge.spec.tsx
+++ b/static/app/components/deployBadge.spec.tsx
@@ -1,3 +1,5 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
+
import {render, screen} from 'sentry-test/reactTestingLibrary';
import DeployBadge from 'sentry/components/deployBadge';
@@ -31,7 +33,7 @@ describe('DeployBadge', () => {
version="1.2.3"
projectId={projectId}
/>,
- {context: TestStubs.routerContext()}
+ {context: RouterContextFixture()}
);
expect(screen.queryByRole('link')).toHaveAttribute(
diff --git a/static/app/components/discover/transactionsList.spec.tsx b/static/app/components/discover/transactionsList.spec.tsx
index 1dc75f98e096ce..23f706aac7ef1d 100644
--- a/static/app/components/discover/transactionsList.spec.tsx
+++ b/static/app/components/discover/transactionsList.spec.tsx
@@ -1,3 +1,5 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
+
import {initializeOrg} from 'sentry-test/initializeOrg';
import {
render,
@@ -53,7 +55,7 @@ describe('TransactionsList', function () {
let generateLink, routerContext;
beforeEach(function () {
- routerContext = TestStubs.routerContext([{organization}]);
+ routerContext = RouterContextFixture([{organization}]);
initialize();
eventView = EventView.fromSavedQuery({
id: '',
diff --git a/static/app/components/errorRobot.spec.tsx b/static/app/components/errorRobot.spec.tsx
index f90378799e61ff..eba8e843331f6e 100644
--- a/static/app/components/errorRobot.spec.tsx
+++ b/static/app/components/errorRobot.spec.tsx
@@ -1,4 +1,5 @@
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
@@ -9,7 +10,7 @@ describe('ErrorRobot', function () {
let routerContext;
beforeEach(function () {
- routerContext = TestStubs.routerContext();
+ routerContext = RouterContextFixture();
getIssues = MockApiClient.addMockResponse({
url: '/projects/org-slug/project-slug/issues/',
method: 'GET',
diff --git a/static/app/components/eventOrGroupTitle.spec.tsx b/static/app/components/eventOrGroupTitle.spec.tsx
index 7600f301be105f..0cdc485dfd1629 100644
--- a/static/app/components/eventOrGroupTitle.spec.tsx
+++ b/static/app/components/eventOrGroupTitle.spec.tsx
@@ -1,4 +1,5 @@
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen} from 'sentry-test/reactTestingLibrary';
@@ -63,7 +64,7 @@ describe('EventOrGroupTitle', function () {
});
it('renders with title override', function () {
- const routerContext = TestStubs.routerContext([{organization: Organization()}]);
+ const routerContext = RouterContextFixture([{organization: Organization()}]);
render(
<EventOrGroupTitle
@@ -140,7 +141,7 @@ describe('EventOrGroupTitle', function () {
} as BaseGroup;
it('should correctly render title', () => {
- const routerContext = TestStubs.routerContext([{organization: Organization()}]);
+ const routerContext = RouterContextFixture([{organization: Organization()}]);
render(<EventOrGroupTitle data={perfData} />, {context: routerContext});
diff --git a/static/app/components/events/interfaces/frame/context.spec.tsx b/static/app/components/events/interfaces/frame/context.spec.tsx
index 822f2647680efc..83f7f1fae36ce2 100644
--- a/static/app/components/events/interfaces/frame/context.spec.tsx
+++ b/static/app/components/events/interfaces/frame/context.spec.tsx
@@ -2,6 +2,7 @@ import {Event as EventFixture} from 'sentry-fixture/event';
import {Organization} from 'sentry-fixture/organization';
import {Repository} from 'sentry-fixture/repository';
import {RepositoryProjectPathConfig} from 'sentry-fixture/repositoryProjectPathConfig';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render} from 'sentry-test/reactTestingLibrary';
@@ -64,7 +65,7 @@ describe('Frame - Context', function () {
components={[]}
/>,
{
- context: TestStubs.routerContext([{organization: org}]),
+ context: RouterContextFixture([{organization: org}]),
organization: org,
project,
}
diff --git a/static/app/components/events/interfaces/frame/stacktraceLink.spec.tsx b/static/app/components/events/interfaces/frame/stacktraceLink.spec.tsx
index 493830acd82d50..2b7080f0c46fe2 100644
--- a/static/app/components/events/interfaces/frame/stacktraceLink.spec.tsx
+++ b/static/app/components/events/interfaces/frame/stacktraceLink.spec.tsx
@@ -3,6 +3,7 @@ import {Event as EventFixture} from 'sentry-fixture/event';
import {Organization} from 'sentry-fixture/organization';
import {Repository} from 'sentry-fixture/repository';
import {RepositoryProjectPathConfig} from 'sentry-fixture/repositoryProjectPathConfig';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
@@ -49,7 +50,7 @@ describe('StacktraceLink', function () {
body: {config: null, sourceUrl: null, integrations: []},
});
render(<StacktraceLink frame={frame} event={event} line="" />, {
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
});
expect(
await screen.findByText(
@@ -92,7 +93,7 @@ describe('StacktraceLink', function () {
body: {},
});
const {container} = render(<StacktraceLink frame={frame} event={event} line="" />, {
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
});
expect(
await screen.findByText(
@@ -125,7 +126,7 @@ describe('StacktraceLink', function () {
body: {config: null, sourceUrl: null, integrations: [integration]},
});
render(<StacktraceLink frame={frame} event={event} line="foo()" />, {
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
});
expect(
await screen.findByText('Tell us where your source code is')
@@ -138,7 +139,7 @@ describe('StacktraceLink', function () {
body: {config, sourceUrl: 'https://something.io', integrations: [integration]},
});
render(<StacktraceLink frame={frame} event={event} line="foo()" />, {
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
});
expect(await screen.findByRole('link')).toHaveAttribute(
'href',
@@ -157,7 +158,7 @@ describe('StacktraceLink', function () {
},
});
render(<StacktraceLink frame={frame} event={event} line="foo()" />, {
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
});
expect(
await screen.findByRole('button', {
@@ -181,7 +182,7 @@ describe('StacktraceLink', function () {
event={{...event, platform: 'javascript'}}
line="{snip} somethingInsane=e.IsNotFound {snip}"
/>,
- {context: TestStubs.routerContext()}
+ {context: RouterContextFixture()}
);
await waitFor(() => {
expect(container).toBeEmptyDOMElement();
@@ -199,7 +200,7 @@ describe('StacktraceLink', function () {
});
const {container} = render(
<StacktraceLink frame={frame} event={{...event, platform: 'unreal'}} line="" />,
- {context: TestStubs.routerContext()}
+ {context: RouterContextFixture()}
);
await waitFor(() => {
expect(container).toBeEmptyDOMElement();
@@ -225,7 +226,7 @@ describe('StacktraceLink', function () {
},
});
render(<StacktraceLink frame={frame} event={event} line="foo()" />, {
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
organization,
});
@@ -256,7 +257,7 @@ describe('StacktraceLink', function () {
},
});
render(<StacktraceLink frame={frame} event={event} line="foo()" />, {
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
organization,
});
expect(await screen.findByText('Code Coverage not found')).toBeInTheDocument();
@@ -284,7 +285,7 @@ describe('StacktraceLink', function () {
},
});
render(<StacktraceLink frame={frame} event={event} line="foo()" />, {
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
organization,
});
expect(await screen.findByTestId('codecov-link')).toBeInTheDocument();
@@ -309,7 +310,7 @@ describe('StacktraceLink', function () {
line="foo()"
/>,
{
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
}
);
expect(await screen.findByRole('link')).toHaveAttribute(
@@ -339,7 +340,7 @@ describe('StacktraceLink', function () {
line="foo()"
/>,
{
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
}
);
expect(await screen.findByRole('link')).toHaveAttribute(
@@ -359,7 +360,7 @@ describe('StacktraceLink', function () {
});
const {container} = render(
<StacktraceLink frame={frame} event={{...event, platform: 'csharp'}} line="" />,
- {context: TestStubs.routerContext()}
+ {context: RouterContextFixture()}
);
await waitFor(() => {
expect(container).toBeEmptyDOMElement();
diff --git a/static/app/components/events/interfaces/frame/stacktraceLinkModal.spec.tsx b/static/app/components/events/interfaces/frame/stacktraceLinkModal.spec.tsx
index b3fbf12caf1fad..15e440b0b913fa 100644
--- a/static/app/components/events/interfaces/frame/stacktraceLinkModal.spec.tsx
+++ b/static/app/components/events/interfaces/frame/stacktraceLinkModal.spec.tsx
@@ -1,6 +1,7 @@
import {Organization} from 'sentry-fixture/organization';
import {Repository} from 'sentry-fixture/repository';
import {RepositoryProjectPathConfig} from 'sentry-fixture/repositoryProjectPathConfig';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {
act,
@@ -121,7 +122,7 @@ describe('StacktraceLinkModal', () => {
statusCode: 400,
});
- renderGlobalModal({context: TestStubs.routerContext()});
+ renderGlobalModal({context: RouterContextFixture()});
act(() =>
openModal(modalProps => (
<StacktraceLinkModal
diff --git a/static/app/components/events/interfaces/message.spec.tsx b/static/app/components/events/interfaces/message.spec.tsx
index 2393abd27a8a4f..aaf0339abd229c 100644
--- a/static/app/components/events/interfaces/message.spec.tsx
+++ b/static/app/components/events/interfaces/message.spec.tsx
@@ -1,5 +1,6 @@
import {DataScrubbingRelayPiiConfig} from 'sentry-fixture/dataScrubbingRelayPiiConfig';
import {Event as EventFixture} from 'sentry-fixture/event';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
import {textWithMarkupMatcher} from 'sentry-test/utils';
@@ -7,7 +8,7 @@ import {textWithMarkupMatcher} from 'sentry-test/utils';
import {Message} from 'sentry/components/events/interfaces/message';
describe('Message entry', function () {
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
it('display redacted data', async function () {
const event = EventFixture({
entries: [
diff --git a/static/app/components/events/searchBar.spec.tsx b/static/app/components/events/searchBar.spec.tsx
index 7d2fc192fc344b..da7b18783cfef7 100644
--- a/static/app/components/events/searchBar.spec.tsx
+++ b/static/app/components/events/searchBar.spec.tsx
@@ -1,4 +1,5 @@
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {initializeOrg} from 'sentry-test/initializeOrg';
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
@@ -46,7 +47,7 @@ describe('Events > SearchBar', function () {
{totalValues: 0, key: 'browser', name: 'Browser'},
]);
- options = TestStubs.routerContext();
+ options = RouterContextFixture();
MockApiClient.addMockResponse({
url: '/organizations/org-slug/recent-searches/',
diff --git a/static/app/components/globalSelectionLink.spec.tsx b/static/app/components/globalSelectionLink.spec.tsx
index 317854165bdef6..7332a1395c2c17 100644
--- a/static/app/components/globalSelectionLink.spec.tsx
+++ b/static/app/components/globalSelectionLink.spec.tsx
@@ -1,3 +1,5 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
+
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
import GlobalSelectionLink from 'sentry/components/globalSelectionLink';
@@ -6,7 +8,7 @@ const path = 'http://some.url/';
describe('GlobalSelectionLink', function () {
const getContext = (query?: {environment: string; project: string[]}) =>
- TestStubs.routerContext([
+ RouterContextFixture([
{
router: TestStubs.router({
location: {query},
diff --git a/static/app/components/idBadge/memberBadge.spec.tsx b/static/app/components/idBadge/memberBadge.spec.tsx
index 5b52104bfaad8f..7f251ee1635a19 100644
--- a/static/app/components/idBadge/memberBadge.spec.tsx
+++ b/static/app/components/idBadge/memberBadge.spec.tsx
@@ -1,10 +1,12 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
+
import {render, screen} from 'sentry-test/reactTestingLibrary';
import MemberBadge from 'sentry/components/idBadge/memberBadge';
describe('MemberBadge', function () {
let member;
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
beforeEach(() => {
member = TestStubs.Member();
});
diff --git a/static/app/components/idBadge/projectBadge.spec.tsx b/static/app/components/idBadge/projectBadge.spec.tsx
index e3922c019c7609..29e5f487840afd 100644
--- a/static/app/components/idBadge/projectBadge.spec.tsx
+++ b/static/app/components/idBadge/projectBadge.spec.tsx
@@ -1,10 +1,12 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
+
import {render, screen} from 'sentry-test/reactTestingLibrary';
import ProjectBadge from 'sentry/components/idBadge/projectBadge';
describe('ProjectBadge', function () {
it('renders with Avatar and team name', function () {
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
render(<ProjectBadge project={TestStubs.Project()} />, {context: routerContext});
expect(screen.getByRole('img')).toBeInTheDocument();
diff --git a/static/app/components/modals/commandPalette.spec.tsx b/static/app/components/modals/commandPalette.spec.tsx
index fa252c725ecc71..8d4002b4652863 100644
--- a/static/app/components/modals/commandPalette.spec.tsx
+++ b/static/app/components/modals/commandPalette.spec.tsx
@@ -1,5 +1,6 @@
import {Members} from 'sentry-fixture/members';
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {Team} from 'sentry-fixture/team';
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
@@ -93,7 +94,7 @@ describe('Command Palette Modal', function () {
Footer={ModalFooter}
/>,
{
- context: TestStubs.routerContext([
+ context: RouterContextFixture([
{
router: TestStubs.router({
params: {orgId: 'org-slug'},
diff --git a/static/app/components/modals/emailVerificationModal.spec.tsx b/static/app/components/modals/emailVerificationModal.spec.tsx
index e0e52e4b3dd033..cdb72362b4362d 100644
--- a/static/app/components/modals/emailVerificationModal.spec.tsx
+++ b/static/app/components/modals/emailVerificationModal.spec.tsx
@@ -1,9 +1,11 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
+
import {render, screen} from 'sentry-test/reactTestingLibrary';
import EmailVerificationModal from 'sentry/components/modals/emailVerificationModal';
describe('Email Verification Modal', function () {
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
it('renders', function () {
MockApiClient.addMockResponse({
url: '/users/me/emails/',
diff --git a/static/app/components/modals/recoveryOptionsModal.spec.tsx b/static/app/components/modals/recoveryOptionsModal.spec.tsx
index 5c445dd33a8f8e..527c1bbc056c29 100644
--- a/static/app/components/modals/recoveryOptionsModal.spec.tsx
+++ b/static/app/components/modals/recoveryOptionsModal.spec.tsx
@@ -1,5 +1,6 @@
import styled from '@emotion/styled';
import {AllAuthenticators, Authenticators} from 'sentry-fixture/authenticators';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
@@ -9,7 +10,7 @@ import RecoveryOptionsModal from 'sentry/components/modals/recoveryOptionsModal'
describe('RecoveryOptionsModal', function () {
const closeModal = jest.fn();
const mockId = Authenticators().Recovery().authId;
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
beforeEach(function () {
MockApiClient.clearMockResponses();
diff --git a/static/app/components/quickTrace/index.spec.tsx b/static/app/components/quickTrace/index.spec.tsx
index 24f22b3579d1e2..314c2190e44067 100644
--- a/static/app/components/quickTrace/index.spec.tsx
+++ b/static/app/components/quickTrace/index.spec.tsx
@@ -1,3 +1,5 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
+
import {initializeOrg} from 'sentry-test/initializeOrg';
import {render, screen} from 'sentry-test/reactTestingLibrary';
@@ -383,7 +385,7 @@ describe('Quick Trace', function () {
describe('Event Node Clicks', function () {
it('renders single event targets', async function () {
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
render(
<QuickTrace
event={makeTransactionEvent(3) as Event}
diff --git a/static/app/components/replays/replayTagsTableRow.spec.tsx b/static/app/components/replays/replayTagsTableRow.spec.tsx
index 7276b5e78c861f..7098bb24966938 100644
--- a/static/app/components/replays/replayTagsTableRow.spec.tsx
+++ b/static/app/components/replays/replayTagsTableRow.spec.tsx
@@ -1,3 +1,5 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
+
import {render, screen} from 'sentry-test/reactTestingLibrary';
import ReplayTagsTableRow from './replayTagsTableRow';
@@ -26,7 +28,7 @@ describe('ReplayTagsTableRow', () => {
values={['bar', 'baz']}
generateUrl={(name, value) => ({pathname: '/home', query: {[name]: value}})}
/>,
- {context: TestStubs.routerContext()}
+ {context: RouterContextFixture()}
);
expect(screen.getByText('bar').closest('a')).toHaveAttribute('href', '/home?foo=bar');
@@ -40,7 +42,7 @@ describe('ReplayTagsTableRow', () => {
values={['biz baz']}
generateUrl={(name, value) => ({pathname: '/home', query: {[name]: value}})}
/>,
- {context: TestStubs.routerContext()}
+ {context: RouterContextFixture()}
);
expect(screen.getByText('foo bar')).toBeInTheDocument();
diff --git a/static/app/components/search/index.spec.tsx b/static/app/components/search/index.spec.tsx
index fdc6b022ecfcf1..970a1981c10fb2 100644
--- a/static/app/components/search/index.spec.tsx
+++ b/static/app/components/search/index.spec.tsx
@@ -1,4 +1,5 @@
import Fuse from 'fuse.js';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
import {textWithMarkupMatcher} from 'sentry-test/utils';
@@ -73,7 +74,7 @@ describe('Search', () => {
it('renders search results from source', async () => {
jest.useFakeTimers();
render(<Search {...makeSearchProps()} />, {
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
});
await userEvent.click(screen.getByPlaceholderText('Search Input'), {delay: null});
@@ -108,7 +109,7 @@ describe('Search', () => {
})}
/>,
{
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
}
);
@@ -147,7 +148,7 @@ describe('Search', () => {
})}
/>,
{
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
}
);
@@ -184,7 +185,7 @@ describe('Search', () => {
})}
/>,
{
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
}
);
@@ -207,7 +208,7 @@ describe('Search', () => {
})}
/>,
{
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
}
);
diff --git a/static/app/components/sidebar/sidebarDropdown/index.spec.tsx b/static/app/components/sidebar/sidebarDropdown/index.spec.tsx
index 12360f191be310..739716f90e1d05 100644
--- a/static/app/components/sidebar/sidebarDropdown/index.spec.tsx
+++ b/static/app/components/sidebar/sidebarDropdown/index.spec.tsx
@@ -1,4 +1,5 @@
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
@@ -9,7 +10,7 @@ function renderDropdown(props: any = {}) {
const user = TestStubs.User();
const config = TestStubs.Config();
const organization = Organization({orgRole: 'member'});
- const routerContext = TestStubs.routerContext([
+ const routerContext = RouterContextFixture([
{
organization,
},
diff --git a/static/app/components/sidebar/sidebarDropdown/switchOrganization.spec.tsx b/static/app/components/sidebar/sidebarDropdown/switchOrganization.spec.tsx
index 27b88cb8919626..0a19110640b452 100644
--- a/static/app/components/sidebar/sidebarDropdown/switchOrganization.spec.tsx
+++ b/static/app/components/sidebar/sidebarDropdown/switchOrganization.spec.tsx
@@ -1,11 +1,12 @@
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {act, render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
import {SwitchOrganization} from 'sentry/components/sidebar/sidebarDropdown/switchOrganization';
describe('SwitchOrganization', function () {
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
it('can list organizations', async function () {
jest.useFakeTimers();
render(
@@ -16,7 +17,7 @@ describe('SwitchOrganization', function () {
Organization({name: 'Organization 2', slug: 'org2'}),
]}
/>,
- {context: TestStubs.routerContext()}
+ {context: RouterContextFixture()}
);
await userEvent.hover(screen.getByTestId('sidebar-switch-org'), {delay: null});
diff --git a/static/app/components/stream/processingIssueHint.spec.tsx b/static/app/components/stream/processingIssueHint.spec.tsx
index 5dbcb4da655031..02a9d07cb44d7e 100644
--- a/static/app/components/stream/processingIssueHint.spec.tsx
+++ b/static/app/components/stream/processingIssueHint.spec.tsx
@@ -1,3 +1,5 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
+
import {render, screen} from 'sentry-test/reactTestingLibrary';
import ProcessingIssueHint from 'sentry/components/stream/processingIssueHint';
@@ -27,7 +29,7 @@ describe('ProcessingIssueHint', function () {
projectId={projectId}
showProject={showProject}
/>,
- {context: TestStubs.routerContext()}
+ {context: RouterContextFixture()}
);
container = result.container;
}
diff --git a/static/app/components/tabs/index.spec.tsx b/static/app/components/tabs/index.spec.tsx
index 4c0bb95cf3e86b..de36656135d05b 100644
--- a/static/app/components/tabs/index.spec.tsx
+++ b/static/app/components/tabs/index.spec.tsx
@@ -1,3 +1,5 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
+
import {render, screen, userEvent, within} from 'sentry-test/reactTestingLibrary';
import {TabList, TabPanels, Tabs} from 'sentry/components/tabs';
@@ -202,7 +204,7 @@ describe('Tabs', () => {
});
it('renders tab links', async () => {
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
render(
<Tabs>
<TabList>
diff --git a/static/app/components/tag.spec.tsx b/static/app/components/tag.spec.tsx
index a96ff4129aabe6..3d8bd3ff5435ec 100644
--- a/static/app/components/tag.spec.tsx
+++ b/static/app/components/tag.spec.tsx
@@ -1,10 +1,12 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
+
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
import Tag from 'sentry/components/tag';
import {IconFire} from 'sentry/icons';
describe('Tag', () => {
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
it('basic', () => {
render(<Tag>Text</Tag>);
expect(screen.getByText('Text')).toBeInTheDocument();
diff --git a/static/app/components/version.spec.tsx b/static/app/components/version.spec.tsx
index 8a271168969875..a7d01910e8197c 100644
--- a/static/app/components/version.spec.tsx
+++ b/static/app/components/version.spec.tsx
@@ -1,3 +1,5 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
+
import {act, render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
import Version from 'sentry/components/version';
@@ -5,7 +7,7 @@ import Version from 'sentry/components/version';
const VERSION = '[email protected]+20200101';
describe('Version', () => {
- const context = TestStubs.routerContext();
+ const context = RouterContextFixture();
afterEach(() => {
jest.resetAllMocks();
});
diff --git a/static/app/views/alerts/index.spec.tsx b/static/app/views/alerts/index.spec.tsx
index 815fa8e4ba363a..6ce45f32be82d9 100644
--- a/static/app/views/alerts/index.spec.tsx
+++ b/static/app/views/alerts/index.spec.tsx
@@ -1,4 +1,5 @@
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen} from 'sentry-test/reactTestingLibrary';
@@ -18,7 +19,7 @@ describe('AlertsContainer', function () {
<SubView />
</AlertsContainer>,
{
- context: TestStubs.routerContext([{organization}]),
+ context: RouterContextFixture([{organization}]),
organization,
}
);
@@ -35,7 +36,7 @@ describe('AlertsContainer', function () {
<SubView />
</AlertsContainer>,
{
- context: TestStubs.routerContext([{organization}]),
+ context: RouterContextFixture([{organization}]),
organization,
}
);
diff --git a/static/app/views/discover/index.spec.tsx b/static/app/views/discover/index.spec.tsx
index e28f1450b3c04f..c145d31e640f6c 100644
--- a/static/app/views/discover/index.spec.tsx
+++ b/static/app/views/discover/index.spec.tsx
@@ -1,5 +1,6 @@
import selectEvent from 'react-select-event';
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen} from 'sentry-test/reactTestingLibrary';
@@ -110,7 +111,7 @@ describe('Discover > Landing', function () {
const org = Organization({features});
render(<DiscoverLanding organization={org} {...TestStubs.routeComponentProps()} />, {
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
});
expect(screen.getByText('Discover')).toHaveAttribute(
diff --git a/static/app/views/issueDetails/groupEventDetails/groupEventDetails.spec.tsx b/static/app/views/issueDetails/groupEventDetails/groupEventDetails.spec.tsx
index 3b6402d68a1e26..b9e7a0d94e8dc3 100644
--- a/static/app/views/issueDetails/groupEventDetails/groupEventDetails.spec.tsx
+++ b/static/app/views/issueDetails/groupEventDetails/groupEventDetails.spec.tsx
@@ -3,6 +3,7 @@ import {Location} from 'history';
import {Commit} from 'sentry-fixture/commit';
import {CommitAuthor} from 'sentry-fixture/commitAuthor';
import {Event as EventFixture} from 'sentry-fixture/event';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {SentryApp} from 'sentry-fixture/sentryApp';
import {SentryAppComponent} from 'sentry-fixture/sentryAppComponent';
@@ -381,7 +382,7 @@ describe('groupEventDetails', () => {
})
);
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
render(<TestComponent group={group} event={transaction} />, {
organization: props.organization,
context: routerContext,
@@ -431,7 +432,7 @@ describe('groupEventDetails', () => {
})
);
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
render(<TestComponent group={group} event={transaction} />, {
organization: props.organization,
context: routerContext,
@@ -582,7 +583,7 @@ describe('Platform Integrations', () => {
props.event,
mockedTrace(props.project)
);
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
render(<TestComponent group={props.group} event={props.event} />, {
organization: props.organization,
@@ -608,7 +609,7 @@ describe('Platform Integrations', () => {
...trace,
performance_issues: [],
});
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
render(<TestComponent group={props.group} event={props.event} />, {
organization: props.organization,
diff --git a/static/app/views/issueDetails/groupSimilarIssues/index.spec.tsx b/static/app/views/issueDetails/groupSimilarIssues/index.spec.tsx
index 9a66cd7ad0c0b0..5c4e964ee94b30 100644
--- a/static/app/views/issueDetails/groupSimilarIssues/index.spec.tsx
+++ b/static/app/views/issueDetails/groupSimilarIssues/index.spec.tsx
@@ -1,4 +1,5 @@
import {Groups} from 'sentry-fixture/groups';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {
render,
@@ -22,7 +23,7 @@ describe('Issues Similar View', function () {
features: ['similarity-view'],
});
- const routerContext = TestStubs.routerContext([
+ const routerContext = RouterContextFixture([
{
router: {
...TestStubs.router(),
diff --git a/static/app/views/organizationStats/teamInsights/health.spec.tsx b/static/app/views/organizationStats/teamInsights/health.spec.tsx
index e46fe93293e5fb..caf5900f317b3e 100644
--- a/static/app/views/organizationStats/teamInsights/health.spec.tsx
+++ b/static/app/views/organizationStats/teamInsights/health.spec.tsx
@@ -1,4 +1,5 @@
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {Team} from 'sentry-fixture/team';
import {TeamAlertsTriggered} from 'sentry-fixture/teamAlertsTriggered';
import {TeamResolutionTime} from 'sentry-fixture/teamResolutionTime';
@@ -173,7 +174,7 @@ describe('TeamStatsHealth', () => {
teams,
projects,
});
- const context = TestStubs.routerContext([{organization}]);
+ const context = RouterContextFixture([{organization}]);
TeamStore.loadInitialData(teams, false, null);
MockApiClient.addMockResponse({
diff --git a/static/app/views/organizationStats/teamInsights/index.spec.tsx b/static/app/views/organizationStats/teamInsights/index.spec.tsx
index de6b4ef83a2e41..424c35384039fe 100644
--- a/static/app/views/organizationStats/teamInsights/index.spec.tsx
+++ b/static/app/views/organizationStats/teamInsights/index.spec.tsx
@@ -1,4 +1,5 @@
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen} from 'sentry-test/reactTestingLibrary';
@@ -12,7 +13,7 @@ describe('TeamInsightsContainer', () => {
it('blocks access if org is missing flag', () => {
const organization = Organization();
- const context = TestStubs.routerContext([{organization}]);
+ const context = RouterContextFixture([{organization}]);
render(
<TeamInsightsContainer organization={organization}>
<div>test</div>
@@ -25,7 +26,7 @@ describe('TeamInsightsContainer', () => {
it('allows access for orgs with flag', () => {
ProjectsStore.loadInitialData([TestStubs.Project()]);
const organization = Organization({features: ['team-insights']});
- const context = TestStubs.routerContext([{organization}]);
+ const context = RouterContextFixture([{organization}]);
render(
<TeamInsightsContainer organization={organization}>
<div>test</div>
@@ -38,7 +39,7 @@ describe('TeamInsightsContainer', () => {
it('shows message for users with no teams', () => {
ProjectsStore.loadInitialData([]);
const organization = Organization({features: ['team-insights']});
- const context = TestStubs.routerContext([{organization}]);
+ const context = RouterContextFixture([{organization}]);
render(<TeamInsightsContainer organization={organization} />, {context});
expect(
diff --git a/static/app/views/organizationStats/teamInsights/issues.spec.tsx b/static/app/views/organizationStats/teamInsights/issues.spec.tsx
index e051030b6336e3..23159cd3bae46d 100644
--- a/static/app/views/organizationStats/teamInsights/issues.spec.tsx
+++ b/static/app/views/organizationStats/teamInsights/issues.spec.tsx
@@ -1,4 +1,5 @@
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {Team} from 'sentry-fixture/team';
import {TeamIssuesBreakdown} from 'sentry-fixture/teamIssuesBreakdown';
import {TeamResolutionTime} from 'sentry-fixture/teamResolutionTime';
@@ -141,7 +142,7 @@ describe('TeamStatsIssues', () => {
teams,
projects,
});
- const context = TestStubs.routerContext([{organization}]);
+ const context = RouterContextFixture([{organization}]);
TeamStore.loadInitialData(teams, false, null);
return render(<TeamStatsIssues {...routerProps} />, {
diff --git a/static/app/views/performance/transactionDetails/eventMetas.spec.tsx b/static/app/views/performance/transactionDetails/eventMetas.spec.tsx
index 172aa1e2005815..2ee98789f2d03e 100644
--- a/static/app/views/performance/transactionDetails/eventMetas.spec.tsx
+++ b/static/app/views/performance/transactionDetails/eventMetas.spec.tsx
@@ -1,5 +1,6 @@
import {Event as EventFixture} from 'sentry-fixture/event';
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
@@ -11,7 +12,7 @@ describe('EventMetas', () => {
dateReceived: '2017-05-21T18:01:48.762Z',
dateCreated: '2017-05-21T18:02:48.762Z',
});
- const routerContext = TestStubs.routerContext([]);
+ const routerContext = RouterContextFixture([]);
const organization = Organization({});
MockApiClient.addMockResponse({
url: '/organizations/org-slug/projects/',
diff --git a/static/app/views/performance/transactionDetails/quickTraceMeta.spec.tsx b/static/app/views/performance/transactionDetails/quickTraceMeta.spec.tsx
index 1d986e73bdc005..fe3fc5136cd7d7 100644
--- a/static/app/views/performance/transactionDetails/quickTraceMeta.spec.tsx
+++ b/static/app/views/performance/transactionDetails/quickTraceMeta.spec.tsx
@@ -1,4 +1,5 @@
import {Event as EventFixture} from 'sentry-fixture/event';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen, userEvent, within} from 'sentry-test/reactTestingLibrary';
@@ -10,7 +11,7 @@ import {
import QuickTraceMeta from 'sentry/views/performance/transactionDetails/quickTraceMeta';
describe('QuickTraceMeta', function () {
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
const location = routerContext.context.location;
const project = TestStubs.Project({platform: 'javascript'});
const event = EventFixture({contexts: {trace: {trace_id: 'a'.repeat(32)}}});
diff --git a/static/app/views/performance/transactionSummary/transactionOverview/content.spec.tsx b/static/app/views/performance/transactionSummary/transactionOverview/content.spec.tsx
index c4fccb5c9de33a..4aa811cfc69abe 100644
--- a/static/app/views/performance/transactionSummary/transactionOverview/content.spec.tsx
+++ b/static/app/views/performance/transactionSummary/transactionOverview/content.spec.tsx
@@ -1,5 +1,6 @@
import {InjectedRouter} from 'react-router';
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {initializeOrg} from 'sentry-test/initializeOrg';
import {render, screen} from 'sentry-test/reactTestingLibrary';
@@ -148,7 +149,7 @@ describe('Transaction Summary Content', function () {
transactionName,
router,
} = initialize(project, {});
- const routerContext = TestStubs.routerContext([{organization}]);
+ const routerContext = RouterContextFixture([{organization}]);
render(
<WrappedComponent
diff --git a/static/app/views/performance/vitalDetail/index.spec.tsx b/static/app/views/performance/vitalDetail/index.spec.tsx
index db2cb9ed544aeb..2faeb4c5a19b13 100644
--- a/static/app/views/performance/vitalDetail/index.spec.tsx
+++ b/static/app/views/performance/vitalDetail/index.spec.tsx
@@ -1,6 +1,7 @@
import {browserHistory, InjectedRouter} from 'react-router';
import {MetricsField} from 'sentry-fixture/metrics';
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {initializeOrg} from 'sentry-test/initializeOrg';
import {render, screen, userEvent, within} from 'sentry-test/reactTestingLibrary';
@@ -277,7 +278,7 @@ describe('Performance > VitalDetail', function () {
},
};
- const context = TestStubs.routerContext([
+ const context = RouterContextFixture([
{
organization,
project,
@@ -331,7 +332,7 @@ describe('Performance > VitalDetail', function () {
},
};
- const context = TestStubs.routerContext([
+ const context = RouterContextFixture([
{
organization,
project,
@@ -386,7 +387,7 @@ describe('Performance > VitalDetail', function () {
},
};
- const context = TestStubs.routerContext([
+ const context = RouterContextFixture([
{
organization,
project,
diff --git a/static/app/views/profiling/profileSummary/profileSummaryPage.spec.tsx b/static/app/views/profiling/profileSummary/profileSummaryPage.spec.tsx
index 1a372b52a26b4e..b0e447f60c42dc 100644
--- a/static/app/views/profiling/profileSummary/profileSummaryPage.spec.tsx
+++ b/static/app/views/profiling/profileSummary/profileSummaryPage.spec.tsx
@@ -1,6 +1,7 @@
import {Location} from 'history';
import {GlobalSelection} from 'sentry-fixture/globalSelection';
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen} from 'sentry-test/reactTestingLibrary';
@@ -95,7 +96,7 @@ describe('ProfileSummaryPage', () => {
organization: Organization({
features: ['profiling-summary-redesign'],
}),
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
}
);
diff --git a/static/app/views/projectDetail/projectFilters.spec.tsx b/static/app/views/projectDetail/projectFilters.spec.tsx
index df319dd5665092..db32c332202cf6 100644
--- a/static/app/views/projectDetail/projectFilters.spec.tsx
+++ b/static/app/views/projectDetail/projectFilters.spec.tsx
@@ -1,3 +1,5 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
+
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
import ProjectFilters from 'sentry/views/projectDetail/projectFilters';
@@ -28,7 +30,7 @@ describe('ProjectDetail > ProjectFilters', () => {
tagValueLoader={tagValueLoader}
relativeDateOptions={{}}
/>,
- {context: TestStubs.routerContext()}
+ {context: RouterContextFixture()}
);
await userEvent.click(
diff --git a/static/app/views/projectInstall/createProject.spec.tsx b/static/app/views/projectInstall/createProject.spec.tsx
index 54d7aa8b8a7fbd..175ed5757217fe 100644
--- a/static/app/views/projectInstall/createProject.spec.tsx
+++ b/static/app/views/projectInstall/createProject.spec.tsx
@@ -1,4 +1,5 @@
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {MOCK_RESP_VERBOSE} from 'sentry-fixture/ruleConditions';
import {Team} from 'sentry-fixture/team';
@@ -92,7 +93,7 @@ describe('CreateProject', function () {
it('should block if you have access to no teams without team-roles', function () {
render(<CreateProject />, {
- context: TestStubs.routerContext([
+ context: RouterContextFixture([
{
organization: {
id: '1',
@@ -117,7 +118,7 @@ describe('CreateProject', function () {
TeamStore.loadUserTeams([Team({id: '2', slug: 'team-two', access: []})]);
render(<CreateProject />, {
- context: TestStubs.routerContext([
+ context: RouterContextFixture([
{
organization: {
id: '1',
@@ -152,7 +153,7 @@ describe('CreateProject', function () {
Team({id: '3', slug: 'team-three', access: ['team:admin']}),
]);
render(<CreateProject />, {
- context: TestStubs.routerContext([{organization}]),
+ context: RouterContextFixture([{organization}]),
organization,
});
@@ -170,7 +171,7 @@ describe('CreateProject', function () {
});
render(<CreateProject />, {
- context: TestStubs.routerContext([
+ context: RouterContextFixture([
{
organization: {
id: '1',
@@ -282,7 +283,7 @@ describe('CreateProject', function () {
teamSlug: teamNoAccess.slug,
});
render(<CreateProject />, {
- context: TestStubs.routerContext([
+ context: RouterContextFixture([
{
organization: {
id: '1',
diff --git a/static/app/views/releases/detail/header/releaseActions.spec.tsx b/static/app/views/releases/detail/header/releaseActions.spec.tsx
index 9ee8091db9bf6d..2d752b47b00b7e 100644
--- a/static/app/views/releases/detail/header/releaseActions.spec.tsx
+++ b/static/app/views/releases/detail/header/releaseActions.spec.tsx
@@ -1,6 +1,7 @@
import {browserHistory} from 'react-router';
import {Location} from 'history';
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {
render,
@@ -130,7 +131,7 @@ describe('ReleaseActions', function () {
});
it('navigates to a next/prev release', function () {
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
const {rerender} = render(
<ReleaseActions
organization={organization}
diff --git a/static/app/views/replays/list/listContent.spec.tsx b/static/app/views/replays/list/listContent.spec.tsx
index 88a4d5bf8ef34f..d2a11e0a57cf25 100644
--- a/static/app/views/replays/list/listContent.spec.tsx
+++ b/static/app/views/replays/list/listContent.spec.tsx
@@ -1,4 +1,5 @@
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen, waitFor} from 'sentry-test/reactTestingLibrary';
@@ -58,7 +59,7 @@ function getMockOrganization({features}: {features: string[]}) {
}
function getMockContext(mockOrg: TOrganization) {
- return TestStubs.routerContext([{organization: mockOrg}]);
+ return RouterContextFixture([{organization: mockOrg}]);
}
describe('ReplayList', () => {
diff --git a/static/app/views/settings/account/accountAuthorizations.spec.tsx b/static/app/views/settings/account/accountAuthorizations.spec.tsx
index 6be96fc589fba0..83e34d1acfed50 100644
--- a/static/app/views/settings/account/accountAuthorizations.spec.tsx
+++ b/static/app/views/settings/account/accountAuthorizations.spec.tsx
@@ -1,3 +1,5 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
+
import {render} from 'sentry-test/reactTestingLibrary';
import AccountAuthorizations from 'sentry/views/settings/account/accountAuthorizations';
@@ -25,7 +27,7 @@ describe('AccountAuthorizations', function () {
router={router}
/>,
{
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
}
);
});
diff --git a/static/app/views/settings/account/accountSecurity/accountSecurityEnroll.spec.tsx b/static/app/views/settings/account/accountSecurity/accountSecurityEnroll.spec.tsx
index 1ab7e69f30d822..4535ea0f5bf639 100644
--- a/static/app/views/settings/account/accountSecurity/accountSecurityEnroll.spec.tsx
+++ b/static/app/views/settings/account/accountSecurity/accountSecurityEnroll.spec.tsx
@@ -1,4 +1,5 @@
import {Authenticators} from 'sentry-fixture/authenticators';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
@@ -21,7 +22,7 @@ describe('AccountSecurityEnroll', function () {
],
});
- const routerContext = TestStubs.routerContext([
+ const routerContext = RouterContextFixture([
{
router: {
...TestStubs.router(),
@@ -82,7 +83,7 @@ describe('AccountSecurityEnroll', function () {
});
const pushMock = jest.fn();
- const routerContextWithMock = TestStubs.routerContext([
+ const routerContextWithMock = RouterContextFixture([
{
router: {
...TestStubs.router({push: pushMock}),
diff --git a/static/app/views/settings/account/accountSecurity/index.spec.tsx b/static/app/views/settings/account/accountSecurity/index.spec.tsx
index d78a9a4daba876..b2f6b281fdb820 100644
--- a/static/app/views/settings/account/accountSecurity/index.spec.tsx
+++ b/static/app/views/settings/account/accountSecurity/index.spec.tsx
@@ -1,6 +1,7 @@
import {AccountEmails} from 'sentry-fixture/accountEmails';
import {Authenticators} from 'sentry-fixture/authenticators';
import {Organizations} from 'sentry-fixture/organizations';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {
render,
@@ -65,7 +66,7 @@ describe('AccountSecurity', function () {
params={{...router.params, authId: '15'}}
/>
</AccountSecurityWrapper>,
- {context: TestStubs.routerContext()}
+ {context: RouterContextFixture()}
);
}
diff --git a/static/app/views/settings/account/accountSecurity/sessionHistory/index.spec.tsx b/static/app/views/settings/account/accountSecurity/sessionHistory/index.spec.tsx
index 9e484b9e358299..3ca59e86e8aa8e 100644
--- a/static/app/views/settings/account/accountSecurity/sessionHistory/index.spec.tsx
+++ b/static/app/views/settings/account/accountSecurity/sessionHistory/index.spec.tsx
@@ -1,3 +1,5 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
+
import {initializeOrg} from 'sentry-test/initializeOrg';
import {render, screen} from 'sentry-test/reactTestingLibrary';
@@ -35,7 +37,7 @@ describe('AccountSecuritySessionHistory', function () {
],
});
- render(<SessionHistory {...routerProps} />, {context: TestStubs.routerContext()});
+ render(<SessionHistory {...routerProps} />, {context: RouterContextFixture()});
expect(screen.getByText('127.0.0.1')).toBeInTheDocument();
expect(screen.getByText('192.168.0.1')).toBeInTheDocument();
diff --git a/static/app/views/settings/account/accountSubscriptions.spec.tsx b/static/app/views/settings/account/accountSubscriptions.spec.tsx
index 31a34898104712..7f07c4de66de49 100644
--- a/static/app/views/settings/account/accountSubscriptions.spec.tsx
+++ b/static/app/views/settings/account/accountSubscriptions.spec.tsx
@@ -1,3 +1,4 @@
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {Subscriptions} from 'sentry-fixture/subscriptions';
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
@@ -17,7 +18,7 @@ describe('AccountSubscriptions', function () {
body: [],
});
render(<AccountSubscriptions />, {
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
});
});
diff --git a/static/app/views/settings/account/apiNewToken.spec.tsx b/static/app/views/settings/account/apiNewToken.spec.tsx
index 01f941be497e41..ac4dace523bf97 100644
--- a/static/app/views/settings/account/apiNewToken.spec.tsx
+++ b/static/app/views/settings/account/apiNewToken.spec.tsx
@@ -1,4 +1,5 @@
import selectEvent from 'react-select-event';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
@@ -7,13 +8,13 @@ import ApiNewToken from 'sentry/views/settings/account/apiNewToken';
describe('ApiNewToken', function () {
it('renders', function () {
render(<ApiNewToken />, {
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
});
});
it('renders with disabled "Create Token" button', async function () {
render(<ApiNewToken />, {
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
});
expect(await screen.getByRole('button', {name: 'Create Token'})).toBeDisabled();
@@ -27,7 +28,7 @@ describe('ApiNewToken', function () {
});
render(<ApiNewToken />, {
- context: TestStubs.routerContext(),
+ context: RouterContextFixture(),
});
const createButton = await screen.getByRole('button', {name: 'Create Token'});
diff --git a/static/app/views/settings/components/settingsSearch/index.spec.tsx b/static/app/views/settings/components/settingsSearch/index.spec.tsx
index 1afb36c49160bd..1a7d3b2964ad55 100644
--- a/static/app/views/settings/components/settingsSearch/index.spec.tsx
+++ b/static/app/views/settings/components/settingsSearch/index.spec.tsx
@@ -1,5 +1,6 @@
import {Members} from 'sentry-fixture/members';
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {Team} from 'sentry-fixture/team';
import {fireEvent, render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
@@ -14,7 +15,7 @@ jest.mock('sentry/actionCreators/navigation');
describe('SettingsSearch', function () {
let orgsMock: jest.Mock;
- const routerContext = TestStubs.routerContext([
+ const routerContext = RouterContextFixture([
{
router: TestStubs.router({
params: {},
diff --git a/static/app/views/settings/organizationAuth/organizationAuthList.spec.tsx b/static/app/views/settings/organizationAuth/organizationAuthList.spec.tsx
index 4aa2a6d5ced509..59cf18b4f133cd 100644
--- a/static/app/views/settings/organizationAuth/organizationAuthList.spec.tsx
+++ b/static/app/views/settings/organizationAuth/organizationAuthList.spec.tsx
@@ -1,5 +1,6 @@
import {AuthProviders} from 'sentry-fixture/authProviders';
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen} from 'sentry-test/reactTestingLibrary';
@@ -28,7 +29,7 @@ describe('OrganizationAuthList', function () {
});
it('renders for members', function () {
- const context = TestStubs.routerContext([
+ const context = RouterContextFixture([
{organization: Organization({access: ['org:read']})},
]);
@@ -51,7 +52,7 @@ describe('OrganizationAuthList', function () {
it('renders', function () {
const organization = Organization({...require2fa, ...withSSO});
- const context = TestStubs.routerContext([{organization}]);
+ const context = RouterContextFixture([{organization}]);
render(
<OrganizationAuthList
@@ -68,7 +69,7 @@ describe('OrganizationAuthList', function () {
it('renders with saml available', function () {
const organization = Organization({...require2fa, ...withSAML});
- const context = TestStubs.routerContext([{organization}]);
+ const context = RouterContextFixture([{organization}]);
render(
<OrganizationAuthList
@@ -85,7 +86,7 @@ describe('OrganizationAuthList', function () {
it('does not render without sso available', function () {
const organization = Organization({...require2fa});
- const context = TestStubs.routerContext([{organization}]);
+ const context = RouterContextFixture([{organization}]);
render(
<OrganizationAuthList
@@ -102,7 +103,7 @@ describe('OrganizationAuthList', function () {
it('does not render with sso and require 2fa disabled', function () {
const organization = Organization({...withSSO});
- const context = TestStubs.routerContext([{organization}]);
+ const context = RouterContextFixture([{organization}]);
render(
<OrganizationAuthList
@@ -119,7 +120,7 @@ describe('OrganizationAuthList', function () {
it('does not render with saml and require 2fa disabled', function () {
const organization = Organization({...withSAML});
- const context = TestStubs.routerContext([{organization}]);
+ const context = RouterContextFixture([{organization}]);
render(
<OrganizationAuthList
diff --git a/static/app/views/settings/organizationAuth/providerItem.spec.tsx b/static/app/views/settings/organizationAuth/providerItem.spec.tsx
index 7ccc972e5378a0..9e4c2ed529ac2e 100644
--- a/static/app/views/settings/organizationAuth/providerItem.spec.tsx
+++ b/static/app/views/settings/organizationAuth/providerItem.spec.tsx
@@ -1,5 +1,6 @@
import {AuthProviders} from 'sentry-fixture/authProviders';
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
@@ -11,7 +12,7 @@ describe('ProviderItem', function () {
const org = Organization({
features: [descopeFeatureName(provider.requiredFeature)],
});
- const routerContext = TestStubs.routerContext([{organization: org}]);
+ const routerContext = RouterContextFixture([{organization: org}]);
it('renders', function () {
render(<ProviderItem active={false} provider={provider} onConfigure={() => {}} />, {
@@ -34,7 +35,7 @@ describe('ProviderItem', function () {
});
it('renders a disabled Tag when disabled', function () {
- const noFeatureRouterContext = TestStubs.routerContext();
+ const noFeatureRouterContext = RouterContextFixture();
render(<ProviderItem active={false} provider={provider} onConfigure={() => {}} />, {
context: noFeatureRouterContext,
});
diff --git a/static/app/views/settings/organizationDeveloperSettings/sentryApplicationDetails.spec.tsx b/static/app/views/settings/organizationDeveloperSettings/sentryApplicationDetails.spec.tsx
index 9fa3440b5b41cf..cae9bd7fd915c4 100644
--- a/static/app/views/settings/organizationDeveloperSettings/sentryApplicationDetails.spec.tsx
+++ b/static/app/views/settings/organizationDeveloperSettings/sentryApplicationDetails.spec.tsx
@@ -1,5 +1,6 @@
import selectEvent from 'react-select-event';
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {SentryApp} from 'sentry-fixture/sentryApp';
import {SentryAppToken} from 'sentry-fixture/sentryAppToken';
@@ -35,7 +36,7 @@ describe('Sentry Application Details', function () {
route={{path: 'new-public/'}}
params={{}}
/>,
- {context: TestStubs.routerContext([{organization: org}])}
+ {context: RouterContextFixture([{organization: org}])}
);
}
@@ -146,7 +147,7 @@ describe('Sentry Application Details', function () {
route={{path: 'new-internal/'}}
params={{}}
/>,
- {context: TestStubs.routerContext([{organization: org}])}
+ {context: RouterContextFixture([{organization: org}])}
);
}
@@ -182,7 +183,7 @@ describe('Sentry Application Details', function () {
params={{appSlug: sentryApp.slug}}
/>,
{
- context: TestStubs.routerContext([{organization: org}]),
+ context: RouterContextFixture([{organization: org}]),
}
);
}
@@ -246,7 +247,7 @@ describe('Sentry Application Details', function () {
params={{appSlug: sentryApp.slug}}
/>,
{
- context: TestStubs.routerContext([{organization: org}]),
+ context: RouterContextFixture([{organization: org}]),
}
);
}
@@ -317,7 +318,7 @@ describe('Sentry Application Details', function () {
params={{appSlug: sentryApp.slug}}
/>,
{
- context: TestStubs.routerContext([{organization: org}]),
+ context: RouterContextFixture([{organization: org}]),
}
);
}
@@ -366,7 +367,7 @@ describe('Sentry Application Details', function () {
params={{appSlug: sentryApp.slug}}
/>,
{
- context: TestStubs.routerContext([{organization: org}]),
+ context: RouterContextFixture([{organization: org}]),
}
);
}
@@ -443,7 +444,7 @@ describe('Sentry Application Details', function () {
params={{appSlug: sentryApp.slug}}
/>,
{
- context: TestStubs.routerContext([{organization: org}]),
+ context: RouterContextFixture([{organization: org}]),
}
);
}
@@ -537,7 +538,7 @@ describe('Sentry Application Details', function () {
params={{appSlug: sentryApp.slug}}
/>,
{
- context: TestStubs.routerContext([{organization: org}]),
+ context: RouterContextFixture([{organization: org}]),
}
);
}
diff --git a/static/app/views/settings/organizationMembers/organizationMembersList.spec.tsx b/static/app/views/settings/organizationMembers/organizationMembersList.spec.tsx
index c1bc3a21d552e3..b69927a258a450 100644
--- a/static/app/views/settings/organizationMembers/organizationMembersList.spec.tsx
+++ b/static/app/views/settings/organizationMembers/organizationMembersList.spec.tsx
@@ -3,6 +3,7 @@ import selectEvent from 'react-select-event';
import {AuthProvider} from 'sentry-fixture/authProvider';
import {Members} from 'sentry-fixture/members';
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {Team} from 'sentry-fixture/team';
import {
@@ -182,7 +183,7 @@ describe('OrganizationMembersList', function () {
});
render(<OrganizationMembersList {...defaultProps} />, {
- context: TestStubs.routerContext([{organization}]),
+ context: RouterContextFixture([{organization}]),
});
await userEvent.click(screen.getAllByRole('button', {name: 'Remove'})[0]);
@@ -205,7 +206,7 @@ describe('OrganizationMembersList', function () {
});
render(<OrganizationMembersList {...defaultProps} />, {
- context: TestStubs.routerContext([{organization}]),
+ context: RouterContextFixture([{organization}]),
});
await userEvent.click(screen.getAllByRole('button', {name: 'Remove'})[0]);
@@ -227,7 +228,7 @@ describe('OrganizationMembersList', function () {
});
render(<OrganizationMembersList {...defaultProps} />, {
- context: TestStubs.routerContext([{organization}]),
+ context: RouterContextFixture([{organization}]),
});
await userEvent.click(screen.getAllByRole('button', {name: 'Leave'})[0]);
@@ -257,7 +258,7 @@ describe('OrganizationMembersList', function () {
OrganizationsStore.addOrReplace(secondOrg);
render(<OrganizationMembersList {...defaultProps} />, {
- context: TestStubs.routerContext([{organization}]),
+ context: RouterContextFixture([{organization}]),
});
await userEvent.click(screen.getAllByRole('button', {name: 'Leave'})[0]);
@@ -283,7 +284,7 @@ describe('OrganizationMembersList', function () {
});
render(<OrganizationMembersList {...defaultProps} />, {
- context: TestStubs.routerContext([{organization}]),
+ context: RouterContextFixture([{organization}]),
});
await userEvent.click(screen.getAllByRole('button', {name: 'Leave'})[0]);
@@ -308,7 +309,7 @@ describe('OrganizationMembersList', function () {
});
render(<OrganizationMembersList {...defaultProps} />, {
- context: TestStubs.routerContext([{organization}]),
+ context: RouterContextFixture([{organization}]),
});
expect(inviteMock).not.toHaveBeenCalled();
@@ -327,7 +328,7 @@ describe('OrganizationMembersList', function () {
});
render(<OrganizationMembersList {...defaultProps} />, {
- context: TestStubs.routerContext([{organization}]),
+ context: RouterContextFixture([{organization}]),
});
expect(inviteMock).not.toHaveBeenCalled();
@@ -342,7 +343,7 @@ describe('OrganizationMembersList', function () {
body: [],
});
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
render(<OrganizationMembersList {...defaultProps} />, {
context: routerContext,
@@ -370,7 +371,7 @@ describe('OrganizationMembersList', function () {
url: '/organizations/org-slug/members/',
body: [],
});
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
render(<OrganizationMembersList {...defaultProps} />, {
context: routerContext,
});
@@ -431,7 +432,7 @@ describe('OrganizationMembersList', function () {
});
it('can filter members with org roles from team membership', async function () {
- const routerContext = TestStubs.routerContext();
+ const routerContext = RouterContextFixture();
render(<OrganizationMembersList {...defaultProps} />, {
context: routerContext,
});
@@ -480,7 +481,7 @@ describe('OrganizationMembersList', function () {
});
render(<OrganizationMembersList {...defaultProps} organization={org} />, {
- context: TestStubs.routerContext([{organization: org}]),
+ context: RouterContextFixture([{organization: org}]),
});
expect(screen.getByText('Pending Members')).toBeInTheDocument();
@@ -506,7 +507,7 @@ describe('OrganizationMembersList', function () {
});
render(<OrganizationMembersList {...defaultProps} />, {
- context: TestStubs.routerContext([{organization: org}]),
+ context: RouterContextFixture([{organization: org}]),
});
expect(screen.getByText('Pending Members')).toBeInTheDocument();
@@ -544,7 +545,7 @@ describe('OrganizationMembersList', function () {
});
render(<OrganizationMembersList {...defaultProps} />, {
- context: TestStubs.routerContext([{organization: org}]),
+ context: RouterContextFixture([{organization: org}]),
});
expect(screen.getByText('Pending Members')).toBeInTheDocument();
@@ -580,7 +581,7 @@ describe('OrganizationMembersList', function () {
});
render(<OrganizationMembersList {...defaultProps} />, {
- context: TestStubs.routerContext([{organization: org}]),
+ context: RouterContextFixture([{organization: org}]),
});
await selectEvent.select(screen.getAllByRole('textbox')[1], ['Admin']);
diff --git a/static/app/views/settings/project/projectOwnership/index.spec.tsx b/static/app/views/settings/project/projectOwnership/index.spec.tsx
index f8630453193d86..33b9c37c38b39b 100644
--- a/static/app/views/settings/project/projectOwnership/index.spec.tsx
+++ b/static/app/views/settings/project/projectOwnership/index.spec.tsx
@@ -1,5 +1,6 @@
import {GitHubIntegrationConfig} from 'sentry-fixture/integrationListDirectory';
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {initializeOrg} from 'sentry-test/initializeOrg';
import {render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
@@ -90,7 +91,7 @@ describe('Project Ownership', () => {
organization={org}
project={project}
/>,
- {context: TestStubs.routerContext([{organization: org}])}
+ {context: RouterContextFixture([{organization: org}])}
);
// Renders button
diff --git a/static/app/views/settings/projectGeneralSettings/index.spec.tsx b/static/app/views/settings/projectGeneralSettings/index.spec.tsx
index fd865a42d49b9f..f67c5709cc24b3 100644
--- a/static/app/views/settings/projectGeneralSettings/index.spec.tsx
+++ b/static/app/views/settings/projectGeneralSettings/index.spec.tsx
@@ -2,6 +2,7 @@ import {browserHistory} from 'react-router';
import selectEvent from 'react-select-event';
import {GroupingConfigs} from 'sentry-fixture/groupingConfigs';
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {
act,
@@ -52,7 +53,7 @@ describe('projectGeneralSettings', function () {
beforeEach(function () {
jest.spyOn(window.location, 'assign');
- routerContext = TestStubs.routerContext([
+ routerContext = RouterContextFixture([
{
router: TestStubs.router({
params: {
diff --git a/static/app/views/settings/projectPlugins/projectPluginRow.spec.tsx b/static/app/views/settings/projectPlugins/projectPluginRow.spec.tsx
index 8c2abc0f5adef1..91977a75289655 100644
--- a/static/app/views/settings/projectPlugins/projectPluginRow.spec.tsx
+++ b/static/app/views/settings/projectPlugins/projectPluginRow.spec.tsx
@@ -1,4 +1,5 @@
import {Organization} from 'sentry-fixture/organization';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
@@ -9,7 +10,7 @@ describe('ProjectPluginRow', function () {
const org = Organization({access: ['project:write']});
const project = TestStubs.Project();
const params = {orgId: org.slug, projectId: project.slug};
- const routerContext = TestStubs.routerContext([{organization: org, project}]);
+ const routerContext = RouterContextFixture([{organization: org, project}]);
it('renders', function () {
render(<ProjectPluginRow {...params} {...plugin} project={project} />, {
diff --git a/tests/js/sentry-test/initializeOrg.tsx b/tests/js/sentry-test/initializeOrg.tsx
index 6de0a54ea876a5..eb86f689357401 100644
--- a/tests/js/sentry-test/initializeOrg.tsx
+++ b/tests/js/sentry-test/initializeOrg.tsx
@@ -2,6 +2,7 @@ import type {RouteComponent, RouteComponentProps} from 'react-router';
import type {Location} from 'history';
import {Organization} from 'sentry-fixture/organization';
import {OrgRoleList, TeamRoleList} from 'sentry-fixture/roleList';
+import RouterContextFixture from 'sentry-fixture/routerContextFixture';
import type {Organization as TOrganization, Project} from 'sentry/types';
@@ -60,7 +61,7 @@ export function initializeOrg<RouterParams = {orgId: string; projectId: string}>
},
});
- const routerContext: any = TestStubs.routerContext([
+ const routerContext: any = RouterContextFixture([
{
organization,
project,
|
be45b9754c5de06e044dc11d46e9d94ea55ba9db
|
2022-10-05 23:11:55
|
Vu Luong
|
ref(tabs): Add `hideBorder` prop (#39682)
| false
|
Add `hideBorder` prop (#39682)
|
ref
|
diff --git a/static/app/components/tabs/tabList.tsx b/static/app/components/tabs/tabList.tsx
index 9b5d455499479b..e35ca516c8501f 100644
--- a/static/app/components/tabs/tabList.tsx
+++ b/static/app/components/tabs/tabList.tsx
@@ -67,9 +67,10 @@ function useOverflowTabs({
interface TabListProps extends TabListStateProps<any>, AriaTabListProps<any> {
className?: string;
+ hideBorder?: boolean;
}
-function BaseTabList({className, ...props}: TabListProps) {
+function BaseTabList({hideBorder = false, className, ...props}: TabListProps) {
const tabListRef = useRef<HTMLUListElement>(null);
const {rootProps, setTabListState} = useContext(TabsContext);
const {value, defaultValue, onChange, orientation, disabled, ...otherRootProps} =
@@ -116,6 +117,7 @@ function BaseTabList({className, ...props}: TabListProps) {
<TabListWrap
{...tabListProps}
orientation={orientation}
+ hideBorder={hideBorder}
className={className}
ref={tabListRef}
>
@@ -202,6 +204,7 @@ const TabListOuterWrap = styled('div')`
`;
const TabListWrap = styled('ul', {shouldForwardProp: tabsShouldForwardProp})<{
+ hideBorder: boolean;
orientation: Orientation;
}>`
position: relative;
@@ -217,15 +220,15 @@ const TabListWrap = styled('ul', {shouldForwardProp: tabsShouldForwardProp})<{
grid-auto-flow: column;
justify-content: start;
gap: ${space(2)};
- border-bottom: solid 1px ${p.theme.border};
+ ${!p.hideBorder && `border-bottom: solid 1px ${p.theme.border};`}
`
: `
+ height: 100%;
grid-auto-flow: row;
align-content: start;
gap: 1px;
padding-right: ${space(2)};
- border-right: solid 1px ${p.theme.border};
- height: 100%;
+ ${!p.hideBorder && `border-right: solid 1px ${p.theme.border};`}
`};
`;
diff --git a/static/app/views/organizationGroupDetails/header.tsx b/static/app/views/organizationGroupDetails/header.tsx
index b47b978c3a7d0e..5dd7c8d32dfdbd 100644
--- a/static/app/views/organizationGroupDetails/header.tsx
+++ b/static/app/views/organizationGroupDetails/header.tsx
@@ -168,6 +168,7 @@ function GroupHeader({
return (
<StyledTabList
+ hideBorder
onSelectionChange={key => {
trackAdvancedAnalyticsEvent('issue_group_details.tab.clicked', {
organization,
@@ -492,6 +493,5 @@ const IconBadge = styled(Badge)`
`;
const StyledTabList = styled(TabList)`
- border-bottom: none;
margin-top: ${space(2)};
`;
|
bee5ea5a1f2be5c53aee7c618579e7fcf30d2b4e
|
2024-10-22 18:53:26
|
Priscila Oliveira
|
ref(onboarding): Remove long time GA 'onboarding-sdk-selection' feature flag (#79403)
| false
|
Remove long time GA 'onboarding-sdk-selection' feature flag (#79403)
|
ref
|
diff --git a/src/sentry/apidocs/examples/project_examples.py b/src/sentry/apidocs/examples/project_examples.py
index 2bc590d2c8c30d..d46b805b9dc825 100644
--- a/src/sentry/apidocs/examples/project_examples.py
+++ b/src/sentry/apidocs/examples/project_examples.py
@@ -248,7 +248,6 @@
"invite-members-rate-limits",
"transaction-name-normalize",
"performance-file-io-main-thread-visible",
- "onboarding-sdk-selection",
"performance-span-histogram-view",
"performance-file-io-main-thread-ingest",
"metrics-extraction",
diff --git a/src/sentry/features/temporary.py b/src/sentry/features/temporary.py
index bf9083e95271bb..93446a70921390 100644
--- a/src/sentry/features/temporary.py
+++ b/src/sentry/features/temporary.py
@@ -235,8 +235,6 @@ def register_temporary_features(manager: FeatureManager):
manager.add("organizations:on-demand-metrics-ui-widgets", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
# Only enabled in sentry.io to enable onboarding flows.
manager.add("organizations:onboarding", OrganizationFeature, FeatureHandlerStrategy.INTERNAL, api_expose=True)
- # Enable the SDK selection feature in the onboarding
- manager.add("organizations:onboarding-sdk-selection", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
# Enable large ownership rule file size limit
manager.add("organizations:ownership-size-limit-large", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=False)
# Enable xlarge ownership rule file size limit
|
d0c6ef4998024391598014f4364d91e816e01e08
|
2023-03-30 22:36:05
|
Jodi Jang
|
fix(targeting-context): Remove deleted owners from project owner rules get response (#46568)
| false
|
Remove deleted owners from project owner rules get response (#46568)
|
fix
|
diff --git a/src/sentry/api/endpoints/codeowners/__init__.py b/src/sentry/api/endpoints/codeowners/__init__.py
index 5d1048abd2166e..85112cb4970e93 100644
--- a/src/sentry/api/endpoints/codeowners/__init__.py
+++ b/src/sentry/api/endpoints/codeowners/__init__.py
@@ -71,12 +71,20 @@ def validate(self, attrs: Mapping[str, Any]) -> Mapping[str, Any]:
)
# Convert IssueOwner syntax into schema syntax
+ has_targeting_context = features.has(
+ "organizations:streamline-targeting-context", self.context["project"].organization
+ )
try:
- validated_data = create_schema_from_issue_owners(
- issue_owners=issue_owner_rules,
- project_id=self.context["project"].id,
- add_owner_ids=True,
- )
+ if has_targeting_context:
+ validated_data = create_schema_from_issue_owners(
+ issue_owners=issue_owner_rules,
+ project_id=self.context["project"].id,
+ add_owner_ids=True,
+ )
+ else:
+ validated_data = create_schema_from_issue_owners(
+ issue_owners=issue_owner_rules, project_id=self.context["project"].id
+ )
return {
**attrs,
"schema": validated_data,
diff --git a/src/sentry/api/endpoints/codeowners/index.py b/src/sentry/api/endpoints/codeowners/index.py
index a033535727ef16..07bc8247b5ce4b 100644
--- a/src/sentry/api/endpoints/codeowners/index.py
+++ b/src/sentry/api/endpoints/codeowners/index.py
@@ -31,7 +31,9 @@ def add_owner_id_to_schema(self, codeowner: ProjectCodeOwners, project: Project)
associations,
codeowner.repository_project_path_config,
)
- codeowner.schema = create_schema_from_issue_owners(codeowner.raw, project.id, True)
+ codeowner.schema = create_schema_from_issue_owners(
+ codeowner.raw, project.id, add_owner_ids=True, remove_deleted_owners=True
+ )
# Convert raw back to codeowner type to be saved
codeowner.raw = raw
diff --git a/src/sentry/api/endpoints/project_ownership.py b/src/sentry/api/endpoints/project_ownership.py
index 9192ba51428a18..b1d58705a93012 100644
--- a/src/sentry/api/endpoints/project_ownership.py
+++ b/src/sentry/api/endpoints/project_ownership.py
@@ -170,7 +170,9 @@ def add_owner_id_to_schema(self, ownership: ProjectOwnership, project: Project)
and ownership.schema.get("rules")
and "id" not in ownership.schema["rules"][0]["owners"][0].keys()
):
- ownership.schema = create_schema_from_issue_owners(ownership.raw, project.id, True)
+ ownership.schema = create_schema_from_issue_owners(
+ ownership.raw, project.id, add_owner_ids=True, remove_deleted_owners=True
+ )
ownership.save()
def rename_schema_identifier_for_parsing(self, ownership: ProjectOwnership) -> None:
diff --git a/src/sentry/ownership/grammar.py b/src/sentry/ownership/grammar.py
index 0c8fe179e75250..10e68e2e188b85 100644
--- a/src/sentry/ownership/grammar.py
+++ b/src/sentry/ownership/grammar.py
@@ -581,6 +581,26 @@ def resolve_actors(owners: Iterable[Owner], project_id: int) -> Mapping[Owner, A
return {o: actors.get((o.type, o.identifier.lower())) for o in owners}
+def remove_deleted_owners_from_schema(
+ rules: List[Dict[str, Any]], owners_id: Dict[str, int]
+) -> None:
+ valid_rules = rules
+
+ for rule in rules:
+ valid_owners = rule["owners"]
+ for rule_owner in rule["owners"]:
+
+ if rule_owner["identifier"] not in owners_id.keys():
+ valid_owners.remove(rule_owner)
+ if not valid_owners:
+ valid_rules.remove(rule)
+ break
+
+ rule["owners"] = valid_owners
+
+ rules = valid_rules
+
+
def add_owner_ids_to_schema(rules: List[Dict[str, Any]], owners_id: Dict[str, int]) -> None:
for rule in rules:
for rule_owner in rule["owners"]:
@@ -589,7 +609,10 @@ def add_owner_ids_to_schema(rules: List[Dict[str, Any]], owners_id: Dict[str, in
def create_schema_from_issue_owners(
- issue_owners: str, project_id: int, add_owner_ids: bool = False
+ issue_owners: str,
+ project_id: int,
+ add_owner_ids: bool = False,
+ remove_deleted_owners: bool = False,
) -> Mapping[str, Any]:
try:
rules = parse_rules(issue_owners)
@@ -614,7 +637,9 @@ def create_schema_from_issue_owners(
elif add_owner_ids:
owners_id[owner.identifier] = actor[0]
- if bad_actors:
+ if bad_actors and remove_deleted_owners:
+ remove_deleted_owners_from_schema(schema["rules"], owners_id)
+ elif bad_actors:
bad_actors.sort()
raise ValidationError({"raw": "Invalid rule owners: {}".format(", ".join(bad_actors))})
diff --git a/tests/sentry/api/endpoints/test_project_codeowners.py b/tests/sentry/api/endpoints/test_project_codeowners.py
index d3f504e3987f7e..751407edc3b04e 100644
--- a/tests/sentry/api/endpoints/test_project_codeowners.py
+++ b/tests/sentry/api/endpoints/test_project_codeowners.py
@@ -256,8 +256,8 @@ def test_schema_is_correct(self, get_codeowner_mock_file):
{
"matcher": {"pattern": "docs/*", "type": "codeowners"},
"owners": [
- {"identifier": self.user.email, "type": "user", "id": self.user.id},
- {"identifier": self.team.slug, "type": "team", "id": self.team.id},
+ {"identifier": self.user.email, "type": "user"},
+ {"identifier": self.team.slug, "type": "team"},
],
}
],
@@ -280,8 +280,8 @@ def test_schema_preserves_comments(self, get_codeowner_mock_file):
{
"matcher": {"pattern": "docs/*", "type": "codeowners"},
"owners": [
- {"identifier": self.user.email, "type": "user", "id": self.user.id},
- {"identifier": self.team.slug, "type": "team", "id": self.team.id},
+ {"identifier": self.user.email, "type": "user"},
+ {"identifier": self.team.slug, "type": "team"},
],
}
],
@@ -304,8 +304,8 @@ def test_raw_email_correct_schema(self, get_codeowner_mock_file):
{
"matcher": {"pattern": "docs/*", "type": "codeowners"},
"owners": [
- {"identifier": self.user.email, "type": "user", "id": self.user.id},
- {"identifier": self.team.slug, "type": "team", "id": self.team.id},
+ {"identifier": self.user.email, "type": "user"},
+ {"identifier": self.team.slug, "type": "team"},
],
}
],
@@ -451,3 +451,125 @@ def test_get(self, get_codeowner_mock_file):
],
}
]
+
+ @patch(
+ "sentry.integrations.mixins.repositories.RepositoryMixin.get_codeowner_file",
+ return_value={"html_url": "https://github.com/test/CODEOWNERS"},
+ )
+ def test_get_rule_one_deleted_owner_with_streamline_targeting(self, get_codeowner_mock_file):
+ self.member_user_delete = self.create_user("member_delete@localhost", is_superuser=False)
+ self.create_member(
+ user=self.member_user_delete,
+ organization=self.organization,
+ role="member",
+ teams=[self.team],
+ )
+ self.external_delete_user = self.create_external_user(
+ user=self.member_user_delete, external_name="@delete", integration=self.integration
+ )
+ self.data["raw"] = "docs/* @delete @getsentry/ecosystem"
+
+ # Post without the streamline-targeting-context flag
+ with self.feature({"organizations:integrations-codeowners": True}):
+ self.client.post(self.url, self.data)
+
+ # Test get after with the streamline-targeting-context flag
+ with self.feature({"organizations:streamline-targeting-context": True}):
+ self.external_delete_user.delete()
+ response = self.client.get(self.url)
+ assert response.data[0]["schema"] == {
+ "$version": 1,
+ "rules": [
+ {
+ "matcher": {"type": "codeowners", "pattern": "docs/*"},
+ "owners": [{"type": "team", "name": "tiger-team", "id": self.team.id}],
+ }
+ ],
+ }
+
+ @patch(
+ "sentry.integrations.mixins.repositories.RepositoryMixin.get_codeowner_file",
+ return_value={"html_url": "https://github.com/test/CODEOWNERS"},
+ )
+ def test_get_no_rule_deleted_owner_with_streamline_targeting(self, get_codeowner_mock_file):
+ self.member_user_delete = self.create_user("member_delete@localhost", is_superuser=False)
+ self.create_member(
+ user=self.member_user_delete,
+ organization=self.organization,
+ role="member",
+ teams=[self.team],
+ )
+ self.external_delete_user = self.create_external_user(
+ user=self.member_user_delete, external_name="@delete", integration=self.integration
+ )
+ self.data["raw"] = "docs/* @delete"
+
+ # Post without the streamline-targeting-context flag
+ with self.feature({"organizations:integrations-codeowners": True}):
+ self.client.post(self.url, self.data)
+
+ # Test get after with the streamline-targeting-context flag
+ with self.feature({"organizations:streamline-targeting-context": True}):
+ self.external_delete_user.delete()
+ response = self.client.get(self.url)
+ assert response.data[0]["schema"] == {"$version": 1, "rules": []}
+
+ @patch(
+ "sentry.integrations.mixins.repositories.RepositoryMixin.get_codeowner_file",
+ return_value={"html_url": "https://github.com/test/CODEOWNERS"},
+ )
+ def test_get_multiple_rules_deleted_owners_with_streamline_targeting(
+ self, get_codeowner_mock_file
+ ):
+ self.member_user_delete = self.create_user("member_delete@localhost", is_superuser=False)
+ self.create_member(
+ user=self.member_user_delete,
+ organization=self.organization,
+ role="member",
+ teams=[self.team],
+ )
+ self.external_delete_user = self.create_external_user(
+ user=self.member_user_delete, external_name="@delete", integration=self.integration
+ )
+ self.member_user_delete2 = self.create_user("member_delete2@localhost", is_superuser=False)
+ self.create_member(
+ user=self.member_user_delete2,
+ organization=self.organization,
+ role="member",
+ teams=[self.team],
+ )
+ self.external_delete_user2 = self.create_external_user(
+ user=self.member_user_delete, external_name="@delete2", integration=self.integration
+ )
+ self.data[
+ "raw"
+ ] = "docs/* @delete\n*.py @getsentry/ecosystem @delete\n*.css @delete2\n*.rb @NisanthanNanthakumar"
+
+ # Post without the streamline-targeting-context flag
+ with self.feature({"organizations:integrations-codeowners": True}):
+ self.client.post(self.url, self.data)
+
+ # Test get after with the streamline-targeting-context flag
+ with self.feature({"organizations:streamline-targeting-context": True}):
+ self.external_delete_user.delete()
+ self.external_delete_user2.delete()
+ response = self.client.get(self.url)
+ assert response.data[0]["schema"] == {
+ "$version": 1,
+ "rules": [
+ {
+ "matcher": {"type": "codeowners", "pattern": "*.py"},
+ "owners": [{"type": "team", "name": "tiger-team", "id": self.team.id}],
+ },
+ {
+ "matcher": {"type": "codeowners", "pattern": "*.rb"},
+ "owners": [
+ {
+ "type": "user",
+ "name": "[email protected]",
+ "id": self.user.id,
+ }
+ ],
+ },
+ ],
+ }
diff --git a/tests/sentry/api/endpoints/test_project_ownership.py b/tests/sentry/api/endpoints/test_project_ownership.py
index 4d7a4f48969498..69f15e6158ebd2 100644
--- a/tests/sentry/api/endpoints/test_project_ownership.py
+++ b/tests/sentry/api/endpoints/test_project_ownership.py
@@ -192,6 +192,92 @@ def test_get_empty_with_streamline_targeting(self):
"schema": None,
}
+ def test_get_rule_deleted_owner_with_streamline_targeting(self):
+ self.member_user_delete = self.create_user("member_delete@localhost", is_superuser=False)
+ self.create_member(
+ user=self.member_user_delete,
+ organization=self.organization,
+ role="member",
+ teams=[self.team],
+ )
+ # Put without the streamline-targeting-context flag
+ self.client.put(self.path, {"raw": "*.js member_delete@localhost #tiger-team"})
+
+ # Get after with the streamline-targeting-context flag
+ with self.feature({"organizations:streamline-targeting-context": True}):
+ self.member_user_delete.delete()
+ resp = self.client.get(self.path)
+ assert resp.data["schema"] == {
+ "$version": 1,
+ "rules": [
+ {
+ "matcher": {"type": "path", "pattern": "*.js"},
+ "owners": [{"type": "team", "name": "tiger-team", "id": self.team.id}],
+ }
+ ],
+ }
+
+ def test_get_no_rule_deleted_owner_with_streamline_targeting(self):
+ self.member_user_delete = self.create_user("member_delete@localhost", is_superuser=False)
+ self.create_member(
+ user=self.member_user_delete,
+ organization=self.organization,
+ role="member",
+ teams=[self.team],
+ )
+ # Put without the streamline-targeting-context flag
+ self.client.put(self.path, {"raw": "*.js member_delete@localhost"})
+
+ # Get after with the streamline-targeting-context flag
+ with self.feature({"organizations:streamline-targeting-context": True}):
+ self.member_user_delete.delete()
+ resp = self.client.get(self.path)
+ assert resp.data["schema"] == {"$version": 1, "rules": []}
+
+ def test_get_multiple_rules_deleted_owners_with_streamline_targeting(self):
+ self.member_user_delete = self.create_user("member_delete@localhost", is_superuser=False)
+ self.create_member(
+ user=self.member_user_delete,
+ organization=self.organization,
+ role="member",
+ teams=[self.team],
+ )
+ self.member_user_delete2 = self.create_user("member_delete2@localhost", is_superuser=False)
+ self.create_member(
+ user=self.member_user_delete2,
+ organization=self.organization,
+ role="member",
+ teams=[self.team],
+ )
+ # Put without the streamline-targeting-context flag
+ self.client.put(
+ self.path,
+ {
+ "raw": "*.js member_delete@localhost\n*.py #tiger-team\n*.css member_delete2@localhost\n*.rb member@localhost"
+ },
+ )
+
+ # Get after with the streamline-targeting-context flag
+ with self.feature({"organizations:streamline-targeting-context": True}):
+ self.member_user_delete.delete()
+ self.member_user_delete2.delete()
+ resp = self.client.get(self.path)
+ assert resp.data["schema"] == {
+ "$version": 1,
+ "rules": [
+ {
+ "matcher": {"pattern": "*.py", "type": "path"},
+ "owners": [{"id": self.team.id, "name": "tiger-team", "type": "team"}],
+ },
+ {
+ "matcher": {"pattern": "*.rb", "type": "path"},
+ "owners": [
+ {"id": self.member_user.id, "name": "member@localhost", "type": "user"}
+ ],
+ },
+ ],
+ }
+
def test_invalid_email(self):
resp = self.client.put(self.path, {"raw": "*.js [email protected] #tiger-team"})
assert resp.status_code == 400
|
7c2f5179ca07b29a691c6d01221b3e714d80a312
|
2023-06-30 04:02:40
|
Evan Purkhiser
|
ref(ts): Convert AdminQueue.spec to tsx (#51935)
| false
|
Convert AdminQueue.spec to tsx (#51935)
|
ref
|
diff --git a/static/app/views/admin/adminQueue.spec.jsx b/static/app/views/admin/adminQueue.spec.tsx
similarity index 94%
rename from static/app/views/admin/adminQueue.spec.jsx
rename to static/app/views/admin/adminQueue.spec.tsx
index f86e1aef6eb519..709532be18ce38 100644
--- a/static/app/views/admin/adminQueue.spec.jsx
+++ b/static/app/views/admin/adminQueue.spec.tsx
@@ -1,6 +1,5 @@
import {render} from 'sentry-test/reactTestingLibrary';
-import {Client} from 'sentry/api';
import AdminQueue from 'sentry/views/admin/adminQueue';
// TODO(dcramer): this doesnt really test anything as we need to
@@ -8,7 +7,7 @@ import AdminQueue from 'sentry/views/admin/adminQueue';
describe('AdminQueue', function () {
describe('render()', function () {
beforeEach(() => {
- Client.addMockResponse({
+ MockApiClient.addMockResponse({
url: '/internal/queue/tasks/',
body: [
'celery.backend_cleanup',
@@ -54,7 +53,7 @@ describe('AdminQueue', function () {
body: [],
});
- const wrapper = render(<AdminQueue params={{}} />);
+ const wrapper = render(<AdminQueue />);
expect(wrapper.container).toSnapshot();
});
});
|
48d2dc47eb603b4e949548e7239fdea56c58e974
|
2022-09-12 23:59:56
|
Aniket Das
|
feat(hybrid-cloud): Introduce Region info and sentry region config (#38655)
| false
|
Introduce Region info and sentry region config (#38655)
|
feat
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index 395fa57048f8e3..9525ff8c24339b 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -10,9 +10,11 @@
import sys
import tempfile
from datetime import datetime, timedelta
+from typing import Mapping
from urllib.parse import urlparse
import sentry
+from sentry.types.region import Region
from sentry.utils.celery import crontab_with_minute_jitter
from sentry.utils.types import type_from_value
@@ -2798,3 +2800,5 @@ def build_cdc_postgres_init_db_volume(settings):
DISALLOWED_CUSTOMER_DOMAINS = []
SENTRY_PERFORMANCE_ISSUES_RATE_LIMITER_OPTIONS = {}
+
+SENTRY_REGION_CONFIG: Mapping[str, Region] = {}
diff --git a/src/sentry/types/region.py b/src/sentry/types/region.py
new file mode 100644
index 00000000000000..555449b5fd3baf
--- /dev/null
+++ b/src/sentry/types/region.py
@@ -0,0 +1,8 @@
+from dataclasses import dataclass
+
+
+@dataclass
+class Region:
+ name: str
+ subdomain: str
+ is_private: bool = False
|
ada02124280d25a1e3acac7267ec2685a95d602f
|
2023-12-07 01:14:18
|
Stephen Cefali
|
ref(notifications): stop using NotificationSettingOptionValues (#61278)
| false
|
stop using NotificationSettingOptionValues (#61278)
|
ref
|
diff --git a/src/sentry/notifications/types.py b/src/sentry/notifications/types.py
index 87c776191507a6..b33e1155f41b26 100644
--- a/src/sentry/notifications/types.py
+++ b/src/sentry/notifications/types.py
@@ -108,30 +108,6 @@ class NotificationSettingEnum(ValueEqualityEnum):
}
-class NotificationSettingOptionValues(ValueEqualityEnum):
- """
- An empty row in the DB should be represented as
- NotificationSettingOptionValues.DEFAULT.
- """
-
- # Defer to a setting one level up.
- DEFAULT = 0
-
- # Mute this kind of notification.
- NEVER = 10
-
- # Un-mute this kind of notification.
- ALWAYS = 20
-
- # Workflow only. Only send notifications about Issues that the target has
- # explicitly or implicitly opted-into.
- SUBSCRIBE_ONLY = 30
-
- # Deploy only. Only send notifications when the set of changes in the deploy
- # included a commit authored by the target.
- COMMITTED_ONLY = 40
-
-
class NotificationSettingsOptionEnum(ValueEqualityEnum):
DEFAULT = "default"
NEVER = "never"
@@ -140,15 +116,6 @@ class NotificationSettingsOptionEnum(ValueEqualityEnum):
COMMITTED_ONLY = "committed_only"
-# TODO(Steve): clean up after we finish migrating to settings 2.0
-NOTIFICATION_SETTING_OPTION_VALUES = {
- NotificationSettingOptionValues.DEFAULT: NotificationSettingsOptionEnum.DEFAULT.value,
- NotificationSettingOptionValues.NEVER: NotificationSettingsOptionEnum.NEVER.value,
- NotificationSettingOptionValues.ALWAYS: NotificationSettingsOptionEnum.ALWAYS.value,
- NotificationSettingOptionValues.SUBSCRIBE_ONLY: NotificationSettingsOptionEnum.SUBSCRIBE_ONLY.value,
- NotificationSettingOptionValues.COMMITTED_ONLY: NotificationSettingsOptionEnum.COMMITTED_ONLY.value,
-}
-
# default is not a choice anymore, we just delete the row if we want to the default
NOTIFICATION_SETTING_CHOICES = [
NotificationSettingsOptionEnum.ALWAYS.value,
diff --git a/src/sentry/notifications/utils/participants.py b/src/sentry/notifications/utils/participants.py
index 2b74853eecdc10..5fc375fb87c795 100644
--- a/src/sentry/notifications/utils/participants.py
+++ b/src/sentry/notifications/utils/participants.py
@@ -38,7 +38,6 @@
FallthroughChoiceType,
GroupSubscriptionReason,
NotificationSettingEnum,
- NotificationSettingOptionValues,
NotificationSettingsOptionEnum,
)
from sentry.services.hybrid_cloud.actor import ActorType, RpcActor
@@ -161,22 +160,15 @@ def get_participants_for_group(group: Group, user_id: int | None = None) -> Part
def get_reason(
user: Union[User, RpcActor],
- value: NotificationSettingOptionValues | NotificationSettingsOptionEnum,
+ value: NotificationSettingsOptionEnum,
user_ids: set[int],
) -> int | None:
# Members who opt into all deploy emails.
- if value in [NotificationSettingOptionValues.ALWAYS, NotificationSettingsOptionEnum.ALWAYS]:
+ if value == NotificationSettingsOptionEnum.ALWAYS:
return GroupSubscriptionReason.deploy_setting
# Members which have been seen in the commit log.
- elif (
- value
- in [
- NotificationSettingOptionValues.COMMITTED_ONLY,
- NotificationSettingsOptionEnum.COMMITTED_ONLY,
- ]
- and user.id in user_ids
- ):
+ elif value == NotificationSettingsOptionEnum.COMMITTED_ONLY and user.id in user_ids:
return GroupSubscriptionReason.committed
return None
|
efe9e2e5da47d1463308d8ac15cfa26184988ee9
|
2022-01-25 03:25:10
|
Marcos Gaeta
|
fix(notifications): Fix `get_user_subscriptions_for_groups()` (#31223)
| false
|
Fix `get_user_subscriptions_for_groups()` (#31223)
|
fix
|
diff --git a/src/sentry/notifications/helpers.py b/src/sentry/notifications/helpers.py
index b938ca2e22a942..35ff359f2d7a42 100644
--- a/src/sentry/notifications/helpers.py
+++ b/src/sentry/notifications/helpers.py
@@ -41,6 +41,15 @@ def _get_notification_setting_default(
return NOTIFICATION_SETTING_DEFAULTS[provider][type]
+def _get_default_value_by_provider(
+ type: NotificationSettingTypes,
+) -> Mapping[ExternalProviders, NotificationSettingOptionValues]:
+ return {
+ provider: _get_notification_setting_default(provider, type)
+ for provider in NOTIFICATION_SETTING_DEFAULTS.keys()
+ }
+
+
def _get_setting_mapping_from_mapping(
notification_settings_by_recipient: Mapping[
Team | User,
@@ -53,19 +62,17 @@ def _get_setting_mapping_from_mapping(
XXX(CEO): may not respect granularity of a setting for Slack a setting for
email but we'll worry about that later since we don't have a FE for it yet.
"""
- from sentry.notifications.notify import notification_providers
-
- # Fill in with the fallback values.
- notification_setting_option = {
- provider: _get_notification_setting_default(provider, type)
- for provider in notification_providers()
- }
-
- notification_settings_mapping = notification_settings_by_recipient.get(recipient, {})
- for scope in [NotificationScopeType.USER, NotificationScopeType.TEAM, get_scope_type(type)]:
- notification_setting_option.update(notification_settings_mapping.get(scope, {}))
-
- return notification_setting_option
+ return merge_notification_settings_up(
+ _get_default_value_by_provider(type),
+ *(
+ notification_settings_by_recipient.get(recipient, {}).get(scope, {})
+ for scope in (
+ NotificationScopeType.USER,
+ NotificationScopeType.TEAM,
+ get_scope_type(type),
+ )
+ ),
+ )
def where_should_recipient_be_notified(
@@ -343,30 +350,49 @@ def get_user_subscriptions_for_groups(
subscriptions_by_group_id: Mapping[int, GroupSubscription],
user: User,
) -> Mapping[int, tuple[bool, bool, GroupSubscription | None]]:
- """Takes collected data and returns a mapping of group IDs to a three-tuple of values."""
+ """
+ For each group, use the combination of GroupSubscription and
+ NotificationSetting rows to determine if the user is explicitly or
+ implicitly subscribed (or if they can subscribe at all.)
+ """
results = {}
for project, groups in groups_by_project.items():
- value = get_most_specific_notification_setting_value(
+ notification_settings_by_provider = get_values_by_provider(
notification_settings_by_scope,
recipient=user,
parent_id=project.id,
type=NotificationSettingTypes.WORKFLOW,
)
for group in groups:
- subscription = subscriptions_by_group_id.get(group.id)
-
- is_disabled = False
- if subscription:
- is_active = subscription.is_active
- elif value == NotificationSettingOptionValues.NEVER:
- is_active = False
- is_disabled = True
- else:
- is_active = value == NotificationSettingOptionValues.ALWAYS
+ results[group.id] = _get_subscription_values(
+ group,
+ subscriptions_by_group_id,
+ notification_settings_by_provider,
+ )
+ return results
- results[group.id] = (is_disabled, is_active, subscription)
- return results
+def _get_subscription_values(
+ group: Group,
+ subscriptions_by_group_id: Mapping[int, GroupSubscription],
+ notification_settings_by_provider: Mapping[ExternalProviders, NotificationSettingOptionValues],
+) -> tuple[bool, bool, GroupSubscription | None]:
+ is_disabled = False
+ subscription = subscriptions_by_group_id.get(group.id)
+ if subscription:
+ # Having a GroupSubscription overrides NotificationSettings.
+ is_active = subscription.is_active
+ else:
+ value = get_highest_notification_setting_value(notification_settings_by_provider)
+ if value == NotificationSettingOptionValues.NEVER:
+ # The user has disabled notifications in all cases.
+ is_disabled = True
+ is_active = False
+ else:
+ # Since there is no subscription, it is only active if the value is ALWAYS.
+ is_active = value == NotificationSettingOptionValues.ALWAYS
+
+ return is_disabled, is_active, subscription
def get_settings_by_provider(
@@ -456,6 +482,39 @@ def get_highest_notification_setting_value(
return max(notification_settings_by_provider.values(), key=lambda v: v.value)
+def get_value_for_parent(
+ notification_settings_by_scope: Mapping[
+ NotificationScopeType,
+ Mapping[int, Mapping[ExternalProviders, NotificationSettingOptionValues]],
+ ],
+ parent_id: int,
+ type: NotificationSettingTypes,
+) -> Mapping[ExternalProviders, NotificationSettingOptionValues]:
+ """
+ Given notification settings by scope, an organization or project, and a
+ notification type, get the notification settings by provider.
+ """
+ return notification_settings_by_scope.get(get_scope_type(type), {}).get(parent_id, {})
+
+
+def get_value_for_actor(
+ notification_settings_by_scope: Mapping[
+ NotificationScopeType,
+ Mapping[int, Mapping[ExternalProviders, NotificationSettingOptionValues]],
+ ],
+ recipient: Team | User,
+) -> Mapping[ExternalProviders, NotificationSettingOptionValues]:
+ """
+ Instead of checking the DB to see if `recipient` is a Team or User, just
+ `get()` both since only one of them can have a value.
+ """
+ return (
+ notification_settings_by_scope.get(NotificationScopeType.USER)
+ or notification_settings_by_scope.get(NotificationScopeType.TEAM)
+ or {}
+ ).get(recipient.id, {})
+
+
def get_most_specific_notification_setting_value(
notification_settings_by_scope: Mapping[
NotificationScopeType,
@@ -471,14 +530,44 @@ def get_most_specific_notification_setting_value(
"""
return (
get_highest_notification_setting_value(
- notification_settings_by_scope.get(get_scope_type(type), {}).get(parent_id, {})
+ get_value_for_parent(notification_settings_by_scope, parent_id, type)
)
or get_highest_notification_setting_value(
- (
- notification_settings_by_scope.get(NotificationScopeType.USER)
- or notification_settings_by_scope.get(NotificationScopeType.TEAM)
- or {}
- ).get(recipient.id, {})
+ get_value_for_actor(notification_settings_by_scope, recipient)
)
or _get_notification_setting_default(ExternalProviders.EMAIL, type)
)
+
+
+def merge_notification_settings_up(
+ *settings_mappings: Mapping[ExternalProviders, NotificationSettingOptionValues],
+) -> Mapping[ExternalProviders, NotificationSettingOptionValues]:
+ """
+ Given a list of notification settings by provider ordered by increasing
+ specificity, get the most specific value by provider.
+ """
+ value_by_provider: MutableMapping[ExternalProviders, NotificationSettingOptionValues] = {}
+ for notification_settings_by_provider in settings_mappings:
+ value_by_provider.update(notification_settings_by_provider)
+ return value_by_provider
+
+
+def get_values_by_provider(
+ notification_settings_by_scope: Mapping[
+ NotificationScopeType,
+ Mapping[int, Mapping[ExternalProviders, NotificationSettingOptionValues]],
+ ],
+ recipient: Team | User,
+ parent_id: int,
+ type: NotificationSettingTypes,
+) -> Mapping[ExternalProviders, NotificationSettingOptionValues]:
+ """
+ Given notification settings by scope, an organization or project, a
+ recipient, and a notification type, what is the non-never notification
+ setting by provider?
+ """
+ return merge_notification_settings_up(
+ _get_default_value_by_provider(type),
+ get_value_for_actor(notification_settings_by_scope, recipient),
+ get_value_for_parent(notification_settings_by_scope, parent_id, type),
+ )
diff --git a/src/sentry/notifications/notify.py b/src/sentry/notifications/notify.py
index 448e1210b461ba..9316520a6260d0 100644
--- a/src/sentry/notifications/notify.py
+++ b/src/sentry/notifications/notify.py
@@ -1,11 +1,13 @@
from __future__ import annotations
-from typing import Any, Callable, Iterable, Mapping, MutableMapping, Optional, Union
+from typing import TYPE_CHECKING, Any, Callable, Iterable, Mapping, MutableMapping, Optional, Union
-from sentry.models import Team, User
from sentry.notifications.notifications.base import BaseNotification
from sentry.types.integrations import ExternalProviders
+if TYPE_CHECKING:
+ from sentry.models import Team, User
+
# Shortcut so that types don't explode.
Notifiable = Callable[
[
diff --git a/src/sentry/shared_integrations/response/base.py b/src/sentry/shared_integrations/response/base.py
index cc43119030c56f..e8739c8ea6b5f4 100644
--- a/src/sentry/shared_integrations/response/base.py
+++ b/src/sentry/shared_integrations/response/base.py
@@ -23,8 +23,10 @@ def __init__(
self.status_code = status_code
def __repr__(self) -> str:
+ name = type(self).__name__
+ code = self.status_code
content_type = (self.headers or {}).get("Content-Type", "")
- return f"<{type(self).__name__}: code={self.status_code}, content_type={content_type}>"
+ return f"<{name}: code={code}, content_type={content_type}>"
@property
def json(self) -> Any:
diff --git a/tests/sentry/notifications/utils/test_get_most_specific.py b/tests/sentry/notifications/utils/test_get_most_specific.py
index 398b7aa40036ee..20a278fff1a3b1 100644
--- a/tests/sentry/notifications/utils/test_get_most_specific.py
+++ b/tests/sentry/notifications/utils/test_get_most_specific.py
@@ -1,3 +1,5 @@
+from unittest import TestCase
+
from sentry.models import User
from sentry.notifications.helpers import (
get_highest_notification_setting_value,
@@ -8,13 +10,12 @@
NotificationSettingOptionValues,
NotificationSettingTypes,
)
-from sentry.testutils import TestCase
from sentry.types.integrations import ExternalProviders
class GetMostSpecificNotificationSettingValueTestCase(TestCase):
def setUp(self) -> None:
- super().setUp()
+ self.user = User(id=1)
def test_get_most_specific_notification_setting_value_empty_workflow(self):
value = get_most_specific_notification_setting_value(
diff --git a/tests/sentry/notifications/utils/test_get_user_subscriptions_for_groups.py b/tests/sentry/notifications/utils/test_get_user_subscriptions_for_groups.py
index 09eecc36edefb2..325b63ecf2c37d 100644
--- a/tests/sentry/notifications/utils/test_get_user_subscriptions_for_groups.py
+++ b/tests/sentry/notifications/utils/test_get_user_subscriptions_for_groups.py
@@ -1,13 +1,17 @@
-from sentry.models import GroupSubscription
+from unittest import TestCase
+
+from sentry.models import Group, GroupSubscription, Project, User
from sentry.notifications.helpers import get_user_subscriptions_for_groups
from sentry.notifications.types import NotificationScopeType, NotificationSettingOptionValues
-from sentry.testutils import TestCase
from sentry.types.integrations import ExternalProviders
class GetUserSubscriptionsForGroupsTestCase(TestCase):
def setUp(self) -> None:
self.group_subscription = GroupSubscription(is_active=True)
+ self.user = User(id=1)
+ self.project = Project(id=1)
+ self.group = Group(id=1)
def test_get_user_subscriptions_for_groups_empty(self):
groups_by_project = {self.project: {self.group}}
|
507e9d46fd1b3100b54c299bf8355033b9b4d160
|
2023-01-20 22:34:06
|
Snigdha Sharma
|
fix(codecov): stacktrack integration UI fixes (#43496)
| false
|
stacktrack integration UI fixes (#43496)
|
fix
|
diff --git a/static/app/components/events/interfaces/frame/context.spec.tsx b/static/app/components/events/interfaces/frame/context.spec.tsx
index 73c1ca9cdf1f09..78363a6d562f44 100644
--- a/static/app/components/events/interfaces/frame/context.spec.tsx
+++ b/static/app/components/events/interfaces/frame/context.spec.tsx
@@ -28,10 +28,10 @@ describe('Frame - Context', function () {
];
const lineCoverage: LineCoverage[] = [
- {lineNo: 230, coverage: Coverage.PARTIAL},
- {lineNo: 231, coverage: Coverage.PARTIAL},
- {lineNo: 232, coverage: Coverage.COVERED},
- {lineNo: 234, coverage: Coverage.NOT_COVERED},
+ [230, Coverage.PARTIAL],
+ [231, Coverage.PARTIAL],
+ [232, Coverage.COVERED],
+ [234, Coverage.NOT_COVERED],
];
it('converts coverage data to the right colors', function () {
diff --git a/static/app/components/events/interfaces/frame/context.tsx b/static/app/components/events/interfaces/frame/context.tsx
index fec5ff917e31a2..898d02a1beed17 100644
--- a/static/app/components/events/interfaces/frame/context.tsx
+++ b/static/app/components/events/interfaces/frame/context.tsx
@@ -56,10 +56,10 @@ export function getCoverageColors(
lines: [number, string][],
lineCov: LineCoverage[]
): Array<Color | 'transparent'> {
- const lineCoverage = keyBy(lineCov, 'lineNo');
- return lines.map(line => {
- const coverage = lineCoverage[line[0]]
- ? lineCoverage[line[0]].coverage
+ const lineCoverage = keyBy(lineCov, 0);
+ return lines.map(([lineNo]) => {
+ const coverage = lineCoverage[lineNo]
+ ? lineCoverage[lineNo][1]
: Coverage.NOT_APPLICABLE;
switch (coverage) {
case Coverage.COVERED:
diff --git a/static/app/components/events/interfaces/frame/line.tsx b/static/app/components/events/interfaces/frame/line.tsx
index f8fa1fc550c1f4..6ccb2892e7c3b9 100644
--- a/static/app/components/events/interfaces/frame/line.tsx
+++ b/static/app/components/events/interfaces/frame/line.tsx
@@ -19,7 +19,6 @@ import DebugImage from '../debugMeta/debugImage';
import {combineStatus} from '../debugMeta/utils';
import {SymbolicatorStatus} from '../types';
-import {CodecovLegend} from './codecovLegend';
import Context from './context';
import DefaultTitle from './defaultTitle';
import PackageLink from './packageLink';
@@ -372,20 +371,8 @@ export class Line extends Component<Props, State> {
});
const props = {className};
- const shouldShowCodecovLegend =
- this.props.organization?.features.includes('codecov-stacktrace-integration') &&
- this.props.organization?.codecovAccess &&
- !this.props.nextFrame;
-
return (
<StyledLi data-test-id="line" {...props}>
- {shouldShowCodecovLegend && (
- <CodecovLegend
- event={this.props.event}
- frame={this.props.data}
- organization={this.props.organization}
- />
- )}
{this.renderLine()}
<Context
frame={data}
diff --git a/static/app/components/events/interfaces/frame/lineV2/index.tsx b/static/app/components/events/interfaces/frame/lineV2/index.tsx
index b700af455208f9..3026ebcdcfd853 100644
--- a/static/app/components/events/interfaces/frame/lineV2/index.tsx
+++ b/static/app/components/events/interfaces/frame/lineV2/index.tsx
@@ -2,10 +2,12 @@ import {useState} from 'react';
import styled from '@emotion/styled';
import classNames from 'classnames';
+import {CodecovLegend} from 'sentry/components/events/interfaces/frame/codecovLegend';
import ListItem from 'sentry/components/list/listItem';
import StrictClick from 'sentry/components/strictClick';
import {PlatformType, SentryAppComponent} from 'sentry/types';
import {Event} from 'sentry/types/event';
+import useOrganization from 'sentry/utils/useOrganization';
import withSentryAppComponents from 'sentry/utils/withSentryAppComponents';
import Context from '../context';
@@ -75,6 +77,7 @@ function Line({
of the stack trace / exception */
const platform = getPlatform(frame.platform, props.platform ?? 'other') as PlatformType;
const leadsToApp = !frame.inApp && ((nextFrame && nextFrame.inApp) || !nextFrame);
+ const organization = useOrganization();
const expandable =
!leadsToApp || includeSystemFrames
@@ -169,8 +172,16 @@ function Line({
'leads-to-app': leadsToApp,
});
+ const shouldShowCodecovLegend =
+ organization.features.includes('codecov-stacktrace-integration') &&
+ organization.codecovAccess &&
+ !nextFrame;
+
return (
<StyleListItem className={className} data-test-id="stack-trace-frame">
+ {shouldShowCodecovLegend && (
+ <CodecovLegend event={event} frame={frame} organization={organization} />
+ )}
<StrictClick onClick={expandable ? toggleContext : undefined}>
{renderLine()}
</StrictClick>
diff --git a/static/app/types/integrations.tsx b/static/app/types/integrations.tsx
index 095eb2453374da..feb5b084c38992 100644
--- a/static/app/types/integrations.tsx
+++ b/static/app/types/integrations.tsx
@@ -150,6 +150,7 @@ export enum Coverage {
COVERED = 1,
PARTIAL = 2,
}
+export type LineCoverage = [lineNo: number, coverage: Coverage];
export enum CodecovStatusCode {
COVERAGE_EXISTS = 200,
@@ -157,11 +158,6 @@ export enum CodecovStatusCode {
NO_COVERAGE_DATA = 400,
}
-export type LineCoverage = {
- coverage: Coverage;
- lineNo: number;
-};
-
export type StacktraceLinkResult = {
integrations: Integration[];
attemptedUrl?: string;
|
ea2c51bae3a6eed10daa9f67d8a8eff7c9dee3fb
|
2022-09-12 20:00:59
|
Jonas
|
ref(profiling): check index access (#38665)
| false
|
check index access (#38665)
|
ref
|
diff --git a/static/app/components/profiling/ProfilingOnboarding/profilingOnboardingModal.spec.tsx b/static/app/components/profiling/ProfilingOnboarding/profilingOnboardingModal.spec.tsx
index 00928e73df8675..4eca1167fde77d 100644
--- a/static/app/components/profiling/ProfilingOnboarding/profilingOnboardingModal.spec.tsx
+++ b/static/app/components/profiling/ProfilingOnboarding/profilingOnboardingModal.spec.tsx
@@ -19,7 +19,7 @@ function selectProject(project: Project) {
throw new Error(`Selected project requires a name, received ${project.name}`);
}
- userEvent.click(screen.getAllByRole('textbox')[0]);
+ userEvent.click(screen.getAllByRole('textbox')[0]!);
userEvent.click(screen.getByText(project.name));
}
@@ -41,13 +41,13 @@ describe('ProfilingOnboarding', function () {
render(<ProfilingOnboardingModal {...MockRenderModalProps} />);
selectProject(TestStubs.Project({name: 'iOS Project'}));
act(() => {
- userEvent.click(screen.getAllByText('Next')[0]);
+ userEvent.click(screen.getAllByText('Next')[0]!);
});
expect(screen.getByText(/Step 2 of 2/i)).toBeInTheDocument();
// Previous step
act(() => {
- userEvent.click(screen.getAllByText('Back')[0]);
+ userEvent.click(screen.getAllByText('Back')[0]!);
});
expect(screen.getByText(/Select a Project/i)).toBeInTheDocument();
});
@@ -60,7 +60,7 @@ describe('ProfilingOnboarding', function () {
render(<ProfilingOnboardingModal {...MockRenderModalProps} />);
selectProject(TestStubs.Project({name: 'javascript'}));
act(() => {
- userEvent.click(screen.getAllByText('Next')[0]);
+ userEvent.click(screen.getAllByText('Next')[0]!);
});
expect(screen.getByRole('button', {name: /Next/i})).toBeDisabled();
});
diff --git a/static/app/components/profiling/arrayLinks.tsx b/static/app/components/profiling/arrayLinks.tsx
index f0abc9392eb7e2..b08aa4b6685a6a 100644
--- a/static/app/components/profiling/arrayLinks.tsx
+++ b/static/app/components/profiling/arrayLinks.tsx
@@ -17,10 +17,11 @@ interface ArrayLinksProps {
function ArrayLinks({items}: ArrayLinksProps) {
const [expanded, setExpanded] = useState(false);
+ const firstItem = items[0];
return (
<ArrayContainer expanded={expanded}>
- {items.length > 0 && <LinkedItem item={items[0]} />}
+ {firstItem && <LinkedItem item={firstItem} />}
{items.length > 1 &&
expanded &&
items
diff --git a/static/app/components/profiling/flamegraphSearch.tsx b/static/app/components/profiling/flamegraphSearch.tsx
index ea86dc090d6669..268e60baedc2ba 100644
--- a/static/app/components/profiling/flamegraphSearch.tsx
+++ b/static/app/components/profiling/flamegraphSearch.tsx
@@ -38,10 +38,10 @@ function findBestMatchFromFuseMatches(
let bestMatchStart = -1;
for (let i = 0; i < matches.length; i++) {
- const match = matches[i];
+ const match = matches[i]!; // iterating over a non empty array
for (let j = 0; j < match.indices.length; j++) {
- const index = match.indices[j];
+ const index = match.indices[j]!; // iterating over a non empty array
const matchLength = index[1] - index[0];
if (matchLength < 0) {
@@ -74,7 +74,12 @@ function findBestMatchFromRegexpMatchArray(
let bestMatchStart = -1;
for (let i = 0; i < matches.length; i++) {
- const index = matches[i].index;
+ const match = matches[i]; // iterating over a non empty array
+ if (match === undefined) {
+ continue;
+ }
+
+ const index = match.index;
if (index === undefined) {
continue;
}
@@ -82,11 +87,11 @@ function findBestMatchFromRegexpMatchArray(
// We only override the match if the match is longer than the current best match
// or if the matches are the same length, but the start is earlier in the string
if (
- matches[i].length > bestMatchLength ||
- (matches[i].length === bestMatchLength && index[0] > bestMatchStart)
+ match.length > bestMatchLength ||
+ (match.length === bestMatchLength && index[0] > bestMatchStart)
) {
- bestMatch = [index, index + matches[i].length];
- bestMatchLength = matches[i].length;
+ bestMatch = [index, index + match.length];
+ bestMatchLength = match.length;
bestMatchStart = index;
}
}
@@ -105,7 +110,6 @@ function frameSearch(
if (isRegExpString(query)) {
const [_, lookup, flags] = parseRegExp(query) ?? [];
-
let matches = 0;
try {
@@ -114,7 +118,7 @@ function frameSearch(
}
for (let i = 0; i < frames.length; i++) {
- const frame = frames[i];
+ const frame = frames[i]!; // iterating over a non empty array
const re = new RegExp(lookup, flags ?? 'g');
const reMatches = Array.from(frame.frame.name.trim().matchAll(re));
@@ -148,7 +152,7 @@ function frameSearch(
}
for (let i = 0; i < fuseResults.length; i++) {
- const fuseFrameResult = fuseResults[i];
+ const fuseFrameResult = fuseResults[i]!; // iterating over a non empty array
const frame = fuseFrameResult.item;
const frameId = getFlamegraphFrameSearchId(frame);
const match = findBestMatchFromFuseMatches(fuseFrameResult.matches ?? []);
@@ -229,8 +233,9 @@ function FlamegraphSearch({
}
const frames = memoizedSortFrameResults(search.results);
- if (frames[search.index]) {
- onZoomIntoFrame(frames[search.index]);
+ const frame = frames[search.index];
+ if (frame) {
+ onZoomIntoFrame(frame);
}
}, [search.results, search.index, onZoomIntoFrame]);
diff --git a/static/app/utils/profiling/colors/utils.spec.tsx b/static/app/utils/profiling/colors/utils.spec.tsx
index e1fa5f9d6fea96..3d7f9fc0ce5409 100644
--- a/static/app/utils/profiling/colors/utils.spec.tsx
+++ b/static/app/utils/profiling/colors/utils.spec.tsx
@@ -150,8 +150,8 @@ describe('makeColorMap', () => {
// Reverse order to ensure we actually sort
const frames = [f(0, 'aaa'), f(1, 'aaa'), f(2, 'aaa'), f(3, 'c')];
- frames[1].node.setRecursiveThroughNode(frames[0].node);
- frames[2].node.setRecursiveThroughNode(frames[1].node);
+ frames[1]!.node.setRecursiveThroughNode(frames[0]!.node);
+ frames[2]!.node.setRecursiveThroughNode(frames[1]!.node);
const map = makeColorMapByRecursion(frames, makeColorBucketTheme(LCH_LIGHT));
diff --git a/static/app/utils/profiling/colors/utils.tsx b/static/app/utils/profiling/colors/utils.tsx
index b8ca96b6464115..b5038173175ca4 100644
--- a/static/app/utils/profiling/colors/utils.tsx
+++ b/static/app/utils/profiling/colors/utils.tsx
@@ -60,8 +60,19 @@ export const makeStackToColor = (
const colorBuffer: number[] = new Array(length * 4 * 6);
for (let index = 0; index < length; index++) {
- const c = colors.get(frames[index].key);
- const colorWithAlpha = c ? c.concat(1) : fallback;
+ const frame = frames[index];
+
+ if (!frame) {
+ continue;
+ }
+
+ const c = colors.get(frame.key);
+ const colorWithAlpha: [number, number, number, number] =
+ c && c.length === 3
+ ? (c.concat(1) as [number, number, number, number])
+ : c
+ ? c
+ : fallback;
for (let i = 0; i < 6; i++) {
const offset = index * 6 * 4 + i * 4;
@@ -142,7 +153,7 @@ export const makeColorMap = (
const colorsByName = new Map<FlamegraphFrame['frame']['key'], ColorChannels>();
for (let i = 0; i < sortedFrames.length; i++) {
- const frame = sortedFrames[i];
+ const frame = sortedFrames[i]!;
const nameKey = frame.frame.name + frame.frame.image ?? '';
if (!colorsByName.has(nameKey)) {
@@ -172,7 +183,7 @@ export const makeColorMapByRecursion = (
const colorsByName = new Map<FlamegraphFrame['frame']['key'], ColorChannels>();
for (let i = 0; i < sortedFrames.length; i++) {
- const frame = sortedFrames[i];
+ const frame = sortedFrames[i]!;
const nameKey = frame.frame.name + frame.frame.image ?? '';
if (!colorsByName.has(nameKey)) {
@@ -204,25 +215,27 @@ export const makeColorMapByImage = (
);
for (let i = 0; i < frames.length; i++) {
- const frame = frames[i];
+ const frame = frames[i]!;
const key = frame.frame.image ?? '';
if (!reverseFrameToImageIndex[key]) {
reverseFrameToImageIndex[key] = [];
}
- reverseFrameToImageIndex[key].push(frame);
+ // we initialize an empty array above, so this is safe
+ reverseFrameToImageIndex[key]!.push(frame);
}
for (let i = 0; i < sortedFrames.length; i++) {
const imageFrames = reverseFrameToImageIndex[sortedFrames[i]?.frame?.image ?? ''];
+ if (!imageFrames) {
+ continue;
+ }
for (let j = 0; j < imageFrames.length; j++) {
+ const frame = imageFrames[j]!;
colors.set(
- imageFrames[j].key,
- colorBucket(
- Math.floor((255 * i) / sortedFrames.length) / 256,
- imageFrames[j].frame
- )
+ frame.key,
+ colorBucket(Math.floor((255 * i) / sortedFrames.length) / 256, frame.frame)
);
}
}
@@ -237,7 +250,7 @@ export const makeColorMapBySystemVsApplication = (
const colors = new Map<FlamegraphFrame['key'], ColorChannels>();
for (let i = 0; i < frames.length; i++) {
- const frame = frames[i];
+ const frame = frames[i]!; // iterating over non empty array
if (frame.frame.is_application) {
colors.set(frame.key, colorBucket(0.7, frame.frame));
@@ -260,7 +273,7 @@ export const makeColorMapByFrequency = (
const colors = new Map<FlamegraphFrame['key'], ColorChannels>();
for (let i = 0; i < frames.length; i++) {
- const frame = frames[i];
+ const frame = frames[i]!; // iterating over non empty array
const key = frame.frame.name + frame.frame.image;
if (!countMap.has(key)) {
@@ -274,12 +287,13 @@ export const makeColorMapByFrequency = (
}
for (let i = 0; i < frames.length; i++) {
- const key = frames[i].frame.name + frames[i].frame.image;
+ const frame = frames[i]!; // iterating over non empty array
+ const key = frame.frame.name + frame.frame.image;
const count = countMap.get(key)!;
- const [r, g, b] = colorBucket(0.7, frames[i].frame);
+ const [r, g, b] = colorBucket(0.7, frame.frame);
const color: ColorChannels = [r, g, b, Math.max(count / max, 0.1)];
- colors.set(frames[i].key, color);
+ colors.set(frame.key, color);
}
return colors;
diff --git a/static/app/utils/profiling/profile/chromeTraceProfile.tsx b/static/app/utils/profiling/profile/chromeTraceProfile.tsx
index 3583eb66113be9..c96b2d0a998b8d 100644
--- a/static/app/utils/profiling/profile/chromeTraceProfile.tsx
+++ b/static/app/utils/profiling/profile/chromeTraceProfile.tsx
@@ -25,7 +25,7 @@ export function splitEventsByProcessAndThreadId(
const collections: Map<ProcessId, Map<ThreadId, ChromeTrace.Event[]>> = new Map();
for (let i = 0; i < trace.length; i++) {
- const event = trace[i];
+ const event = trace[i]!; // iterating over non empty array
if (typeof event.pid !== 'number') {
continue;
@@ -103,7 +103,7 @@ function buildProfile(
const endQueue: Array<ChromeTrace.Event> = [];
for (let i = 0; i < timelineEvents.length; i++) {
- const event = timelineEvents[i];
+ const event = timelineEvents[i]!; // iterating over non empty array
// M events are not pushed to the queue, we just store their information
if (event.ph === 'M') {
diff --git a/static/app/utils/profiling/profile/jsSelfProfile.spec.tsx b/static/app/utils/profiling/profile/jsSelfProfile.spec.tsx
index ff2f57dfd9d14e..6e80abc0e835fa 100644
--- a/static/app/utils/profiling/profile/jsSelfProfile.spec.tsx
+++ b/static/app/utils/profiling/profile/jsSelfProfile.spec.tsx
@@ -126,6 +126,10 @@ describe('jsSelfProfile', () => {
const root = firstCallee(profile.appendOrderTree);
+ if (!root) {
+ throw new Error('root is null');
+ }
+
expect(root.totalWeight).toEqual(1000);
expect(root.selfWeight).toEqual(0);
diff --git a/static/app/utils/profiling/profile/profile.spec.tsx b/static/app/utils/profiling/profile/profile.spec.tsx
index f388e6b43b60b5..8890290440c51e 100644
--- a/static/app/utils/profiling/profile/profile.spec.tsx
+++ b/static/app/utils/profiling/profile/profile.spec.tsx
@@ -7,7 +7,13 @@ export const f = (name: string, key: number) =>
new Frame({name, key, is_application: false});
export const c = (fr: Frame) => new CallTreeNode(fr, null);
export const firstCallee = (node: CallTreeNode) => node.children[0];
-export const nthCallee = (node: CallTreeNode, n: number) => node.children[n];
+export const nthCallee = (node: CallTreeNode, n: number) => {
+ const child = node.children[n];
+ if (!child) {
+ throw new Error('Child not found');
+ }
+ return child;
+};
export const makeTestingBoilerplate = () => {
const timings: [Frame['name'], string][] = [];
diff --git a/static/app/utils/profiling/profile/utils.tsx b/static/app/utils/profiling/profile/utils.tsx
index f51fe99575a8ae..bb84ad078e3c14 100644
--- a/static/app/utils/profiling/profile/utils.tsx
+++ b/static/app/utils/profiling/profile/utils.tsx
@@ -136,7 +136,7 @@ function indexNodeToParents(
map[node.key] = [];
}
- map[node.key].push(parent);
+ map[node.key]!.push(parent); // we initialize this above
if (!node.children.length) {
leafs.push(node);
@@ -144,7 +144,7 @@ function indexNodeToParents(
}
for (let i = 0; i < node.children.length; i++) {
- indexNode(node.children[i], node);
+ indexNode(node.children[i]!, node); // iterating over non empty array
}
}
@@ -180,11 +180,12 @@ function reverseTrail(
children: [] as FlamegraphFrame[],
};
- if (!parentMap[n.key]) {
+ const parents = parentMap[n.key];
+ if (!parents) {
continue;
}
- for (const parent of parentMap[n.key]) {
+ for (const parent of parents) {
nc.children.push(...reverseTrail([parent], parentMap));
}
splits.push(nc);
diff --git a/static/app/utils/profiling/renderers/sampleTickRenderer.tsx b/static/app/utils/profiling/renderers/sampleTickRenderer.tsx
index 940405d879987e..1b752773e497ab 100644
--- a/static/app/utils/profiling/renderers/sampleTickRenderer.tsx
+++ b/static/app/utils/profiling/renderers/sampleTickRenderer.tsx
@@ -4,10 +4,22 @@ import {Flamegraph} from '../flamegraph';
import {FlamegraphTheme} from '../flamegraph/flamegraphTheme';
import {getContext, Rect} from '../gl/utils';
-function computeAbsoluteSampleTimestamps(startedAt: number, weights: readonly number[]) {
- const timeline = [startedAt + weights[0]];
+function computeAbsoluteSampleTimestamps(
+ startedAt: number,
+ weights: readonly number[]
+): number[] {
+ if (!weights.length) {
+ return [];
+ }
+
+ const first = weights[0];
+ if (typeof first !== 'number') {
+ throw new Error('Invalid weights, expected an array of numbers');
+ }
+ const timeline = [startedAt + first];
for (let i = 1; i < weights.length; i++) {
- timeline.push(timeline[i - 1] + weights[i]);
+ const previous = timeline[i - 1]!; // i starts at 1, so this is safe
+ timeline.push(previous + weights[i]!); // iterating over non empty array
}
return timeline;
}
@@ -53,7 +65,7 @@ class SampleTickRenderer {
context.lineWidth = this.theme.SIZES.INTERNAL_SAMPLE_TICK_LINE_WIDTH;
for (let i = 0; i < this.intervals.length; i++) {
- const interval = this.intervals[i];
+ const interval = this.intervals[i]!; // iterating over a non empty array
if (interval < configView.left) {
continue;
diff --git a/static/app/views/profiling/landing/profileCharts.tsx b/static/app/views/profiling/landing/profileCharts.tsx
index bc847d5dfbc324..b0b30d0d455982 100644
--- a/static/app/views/profiling/landing/profileCharts.tsx
+++ b/static/app/views/profiling/landing/profileCharts.tsx
@@ -49,7 +49,7 @@ export function ProfileCharts({query, router, selection}: ProfileChartsProps) {
if (rawData.axis === 'count') {
return {
data: rawData.values.map((value, i) => ({
- name: timestamps[i],
+ name: String(timestamps[i]),
// the response value contains nulls when no data is
// available, use 0 to represent it
value: value ?? 0,
@@ -62,7 +62,7 @@ export function ProfileCharts({query, router, selection}: ProfileChartsProps) {
return {
data: rawData.values.map((value, i) => ({
- name: timestamps[i],
+ name: String(timestamps[i]),
// the response value contains nulls when no data
// is available, use 0 to represent it
value: (value ?? 0) / 1e6, // convert ns to ms
|
c607cf114e57134c03ca2576080cf288d894510c
|
2023-01-25 23:40:27
|
Alberto Leal
|
chore(hybrid-cloud): Update SSO login page copy (#43655)
| false
|
Update SSO login page copy (#43655)
|
chore
|
diff --git a/src/sentry/templates/sentry/login.html b/src/sentry/templates/sentry/login.html
index 0d9ca9b069e1f5..4c6daf25914613 100644
--- a/src/sentry/templates/sentry/login.html
+++ b/src/sentry/templates/sentry/login.html
@@ -131,7 +131,7 @@ <h3>{% trans "Sign in to continue" %}</h3>
<div class="controls">
<label class="control-label">{% trans "Organization ID" %}</label>
<input type="text" class="form-control" name="organization" placeholder="acme" required>
- <p class="help-block">Your ID is the slug after the hostname. e.g. <code>{{ server_hostname }}/<strong>acme</strong>/</code> is <code>acme</code>.</p>
+ <p class="help-block">Your ID is the slug either before or after the hostname. For example, <code><strong>acme</strong></code> is the slug in either <code>{{ server_hostname }}/<strong>acme</strong>/</code> or <code><strong>acme</strong>.{{ server_hostname }}/</code>.</p>
</div>
</div>
<div class="auth-footer m-t-1">
|
5ae77e7433473db278183660a7b61d601e40e3fc
|
2023-08-16 02:50:14
|
Stephen Cefali
|
feat(notifications): new tables for notification settings (#54735)
| false
|
new tables for notification settings (#54735)
|
feat
|
diff --git a/fixtures/backup/model_dependencies/detailed.json b/fixtures/backup/model_dependencies/detailed.json
index fbac7088df3641..b0f0c16c2cb19c 100644
--- a/fixtures/backup/model_dependencies/detailed.json
+++ b/fixtures/backup/model_dependencies/detailed.json
@@ -1406,6 +1406,30 @@
"CONTROL"
]
},
+ "sentry.NotificationSettingOption": {
+ "foreign_keys": {
+ "user": {
+ "kind": "FlexibleForeignKey",
+ "model": "sentry.User"
+ }
+ },
+ "model": "sentry.NotificationSettingOption",
+ "silos": [
+ "CONTROL"
+ ]
+ },
+ "sentry.NotificationSettingProvider": {
+ "foreign_keys": {
+ "user": {
+ "kind": "FlexibleForeignKey",
+ "model": "sentry.User"
+ }
+ },
+ "model": "sentry.NotificationSettingProvider",
+ "silos": [
+ "CONTROL"
+ ]
+ },
"sentry.Option": {
"foreign_keys": {},
"model": "sentry.Option",
diff --git a/fixtures/backup/model_dependencies/flat.json b/fixtures/backup/model_dependencies/flat.json
index ae0c523279cd48..776e77c7947d36 100644
--- a/fixtures/backup/model_dependencies/flat.json
+++ b/fixtures/backup/model_dependencies/flat.json
@@ -324,6 +324,12 @@
"sentry.NotificationSetting": [
"sentry.User"
],
+ "sentry.NotificationSettingOption": [
+ "sentry.User"
+ ],
+ "sentry.NotificationSettingProvider": [
+ "sentry.User"
+ ],
"sentry.Option": [],
"sentry.OrgAuthToken": [
"sentry.User"
diff --git a/fixtures/backup/model_dependencies/sorted.json b/fixtures/backup/model_dependencies/sorted.json
index f56551f2c4e904..581888e0df7444 100644
--- a/fixtures/backup/model_dependencies/sorted.json
+++ b/fixtures/backup/model_dependencies/sorted.json
@@ -39,6 +39,8 @@
"sentry.LatestRepoReleaseEnvironment",
"sentry.User",
"sentry.NotificationSetting",
+ "sentry.NotificationSettingOption",
+ "sentry.NotificationSettingProvider",
"sentry.OrganizationMapping",
"sentry.OrganizationMemberMapping",
"sentry.OrgAuthToken",
diff --git a/migrations_lockfile.txt b/migrations_lockfile.txt
index 855a4030920f74..9439e16eaf5691 100644
--- a/migrations_lockfile.txt
+++ b/migrations_lockfile.txt
@@ -7,5 +7,5 @@ will then be regenerated, and you should be able to merge without conflicts.
nodestore: 0002_nodestore_no_dictfield
replays: 0003_add_size_to_recording_segment
-sentry: 0529_remove_pagerduty_service
+sentry: 0530_new_notification_tables
social_auth: 0002_default_auto_field
diff --git a/src/sentry/migrations/0530_new_notification_tables.py b/src/sentry/migrations/0530_new_notification_tables.py
new file mode 100644
index 00000000000000..459b6408106e08
--- /dev/null
+++ b/src/sentry/migrations/0530_new_notification_tables.py
@@ -0,0 +1,133 @@
+# Generated by Django 3.2.20 on 2023-08-15 17:22
+
+import django.db.models.deletion
+import django.utils.timezone
+from django.conf import settings
+from django.db import migrations, models
+
+import sentry.db.models.fields.bounded
+import sentry.db.models.fields.foreignkey
+import sentry.db.models.fields.hybrid_cloud_foreign_key
+from sentry.new_migrations.migrations import CheckedMigration
+
+
+class Migration(CheckedMigration):
+ # This flag is used to mark that a migration shouldn't be automatically run in production. For
+ # the most part, 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 dangerous:
+ # - Large data migrations. Typically we want these to be run manually by ops 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
+ # have ops run this and not block the deploy. Note that while adding an index is a schema
+ # change, it's completely safe to run the operation after the code has deployed.
+ is_dangerous = False
+
+ dependencies = [
+ ("sentry", "0529_remove_pagerduty_service"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="NotificationSettingProvider",
+ fields=[
+ (
+ "id",
+ sentry.db.models.fields.bounded.BoundedBigAutoField(
+ primary_key=True, serialize=False
+ ),
+ ),
+ ("date_updated", models.DateTimeField(default=django.utils.timezone.now)),
+ ("date_added", models.DateTimeField(default=django.utils.timezone.now, null=True)),
+ ("scope_type", models.CharField(max_length=32)),
+ ("scope_identifier", sentry.db.models.fields.bounded.BoundedBigIntegerField()),
+ (
+ "team_id",
+ sentry.db.models.fields.hybrid_cloud_foreign_key.HybridCloudForeignKey(
+ "sentry.Team", db_index=True, null=True, on_delete="CASCADE"
+ ),
+ ),
+ ("type", models.CharField(max_length=32)),
+ ("value", models.CharField(max_length=32)),
+ ("provider", models.CharField(max_length=32)),
+ (
+ "user",
+ sentry.db.models.fields.foreignkey.FlexibleForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "db_table": "sentry_notificationsettingprovider",
+ },
+ ),
+ migrations.CreateModel(
+ name="NotificationSettingOption",
+ fields=[
+ (
+ "id",
+ sentry.db.models.fields.bounded.BoundedBigAutoField(
+ primary_key=True, serialize=False
+ ),
+ ),
+ ("date_updated", models.DateTimeField(default=django.utils.timezone.now)),
+ ("date_added", models.DateTimeField(default=django.utils.timezone.now, null=True)),
+ ("scope_type", models.CharField(max_length=32)),
+ ("scope_identifier", sentry.db.models.fields.bounded.BoundedBigIntegerField()),
+ (
+ "team_id",
+ sentry.db.models.fields.hybrid_cloud_foreign_key.HybridCloudForeignKey(
+ "sentry.Team", db_index=True, null=True, on_delete="CASCADE"
+ ),
+ ),
+ ("type", models.CharField(max_length=32)),
+ ("value", models.CharField(max_length=32)),
+ (
+ "user",
+ sentry.db.models.fields.foreignkey.FlexibleForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "db_table": "sentry_notificationsettingoption",
+ },
+ ),
+ migrations.AddConstraint(
+ model_name="notificationsettingprovider",
+ constraint=models.CheckConstraint(
+ check=models.Q(
+ models.Q(("team_id__isnull", False), ("user_id__isnull", True)),
+ models.Q(("team_id__isnull", True), ("user_id__isnull", False)),
+ _connector="OR",
+ ),
+ name="notification_setting_provider_team_or_user_check",
+ ),
+ ),
+ migrations.AlterUniqueTogether(
+ name="notificationsettingprovider",
+ unique_together={
+ ("scope_type", "scope_identifier", "user_id", "team_id", "provider", "type")
+ },
+ ),
+ migrations.AddConstraint(
+ model_name="notificationsettingoption",
+ constraint=models.CheckConstraint(
+ check=models.Q(
+ models.Q(("team_id__isnull", False), ("user_id__isnull", True)),
+ models.Q(("team_id__isnull", True), ("user_id__isnull", False)),
+ _connector="OR",
+ ),
+ name="notification_setting_option_team_or_user_check",
+ ),
+ ),
+ migrations.AlterUniqueTogether(
+ name="notificationsettingoption",
+ unique_together={("scope_type", "scope_identifier", "user_id", "team_id", "type")},
+ ),
+ ]
diff --git a/src/sentry/models/__init__.py b/src/sentry/models/__init__.py
index b60dbfb70a0d6c..5666dcb9ec8c95 100644
--- a/src/sentry/models/__init__.py
+++ b/src/sentry/models/__init__.py
@@ -63,6 +63,8 @@
from .latestreporeleaseenvironment import * # NOQA
from .lostpasswordhash import * # NOQA
from .notificationsetting import * # NOQA
+from .notificationsettingoption import * # NOQA
+from .notificationsettingprovider import * # NOQA
from .options import * # NOQA
from .organization import * # NOQA
from .organizationaccessrequest import * # NOQA
diff --git a/src/sentry/models/notificationsettingbase.py b/src/sentry/models/notificationsettingbase.py
new file mode 100644
index 00000000000000..62b7e556eb8a4f
--- /dev/null
+++ b/src/sentry/models/notificationsettingbase.py
@@ -0,0 +1,35 @@
+import sentry_sdk
+from django.conf import settings
+from django.db import models
+
+from sentry.db.models import BoundedBigIntegerField, DefaultFieldsModel, FlexibleForeignKey
+from sentry.db.models.fields.hybrid_cloud_foreign_key import HybridCloudForeignKey
+
+
+class NotificationSettingBase(DefaultFieldsModel):
+ __include_in_export__ = False
+
+ scope_type = models.CharField(max_length=32, null=False)
+ scope_identifier = BoundedBigIntegerField(null=False)
+ team_id = HybridCloudForeignKey("sentry.Team", null=True, db_index=True, on_delete="CASCADE")
+ user = FlexibleForeignKey(
+ settings.AUTH_USER_MODEL, null=True, db_index=True, on_delete=models.CASCADE
+ )
+ type = models.CharField(max_length=32, null=False)
+ value = models.CharField(max_length=32, null=False)
+
+ class Meta:
+ abstract = True
+
+ def save(self, *args, **kwargs):
+ try:
+ assert not (
+ self.user_id is None and self.team_id is None
+ ), "Notification setting missing user & team"
+ except AssertionError as err:
+ sentry_sdk.capture_exception(err)
+ super().save(*args, **kwargs)
+
+
+# REQUIRED for migrations to run
+from sentry.trash import * # NOQA
diff --git a/src/sentry/models/notificationsettingoption.py b/src/sentry/models/notificationsettingoption.py
new file mode 100644
index 00000000000000..349d9d68defc50
--- /dev/null
+++ b/src/sentry/models/notificationsettingoption.py
@@ -0,0 +1,38 @@
+from django.db import models
+
+from sentry.db.models import control_silo_only_model, sane_repr
+
+from .notificationsettingbase import NotificationSettingBase
+
+
+@control_silo_only_model
+class NotificationSettingOption(NotificationSettingBase):
+ __include_in_export__ = False
+
+ class Meta:
+ app_label = "sentry"
+ db_table = "sentry_notificationsettingoption"
+ unique_together = (
+ (
+ "scope_type",
+ "scope_identifier",
+ "user_id",
+ "team_id",
+ "type",
+ ),
+ )
+ constraints = [
+ models.CheckConstraint(
+ check=models.Q(team_id__isnull=False, user_id__isnull=True)
+ | models.Q(team_id__isnull=True, user_id__isnull=False),
+ name="notification_setting_option_team_or_user_check",
+ )
+ ]
+
+ __repr__ = sane_repr(
+ "scope_str",
+ "scope_identifier",
+ "target",
+ "type_str",
+ "value_str",
+ )
diff --git a/src/sentry/models/notificationsettingprovider.py b/src/sentry/models/notificationsettingprovider.py
new file mode 100644
index 00000000000000..f8784b3466b4d2
--- /dev/null
+++ b/src/sentry/models/notificationsettingprovider.py
@@ -0,0 +1,43 @@
+from django.db import models
+
+from sentry.db.models import control_silo_only_model, sane_repr
+
+from .notificationsettingbase import NotificationSettingBase
+
+
+@control_silo_only_model
+class NotificationSettingProvider(NotificationSettingBase):
+ __include_in_export__ = False
+
+ provider = models.CharField(max_length=32, null=False)
+
+ class Meta:
+ app_label = "sentry"
+ db_table = "sentry_notificationsettingprovider"
+ unique_together = (
+ (
+ "scope_type",
+ "scope_identifier",
+ "user_id",
+ "team_id",
+ "provider",
+ "type",
+ ),
+ )
+ constraints = [
+ models.CheckConstraint(
+ check=models.Q(team_id__isnull=False, user_id__isnull=True)
+ | models.Q(team_id__isnull=True, user_id__isnull=False),
+ name="notification_setting_provider_team_or_user_check",
+ )
+ ]
+
+ __repr__ = sane_repr(
+ "scope_str",
+ "scope_identifier",
+ "user_id",
+ "team_id",
+ "provider_str",
+ "type_str",
+ "value_str",
+ )
|
dba6aa7357d8ad07c675c5e0a45ea88d45a0eeff
|
2022-03-18 04:18:20
|
Kelly Carino
|
fix(workflow): Handle zoom on metric alert details chart (#32723)
| false
|
Handle zoom on metric alert details chart (#32723)
|
fix
|
diff --git a/static/app/views/alerts/rules/details/metricChart.tsx b/static/app/views/alerts/rules/details/metricChart.tsx
index e68b6338a8755c..31fcd6da2b2ee6 100644
--- a/static/app/views/alerts/rules/details/metricChart.tsx
+++ b/static/app/views/alerts/rules/details/metricChart.tsx
@@ -597,6 +597,11 @@ class MetricChart extends React.PureComponent<Props, State> {
start={start}
end={end}
onZoom={zoomArgs => this.handleZoom(zoomArgs.start, zoomArgs.end)}
+ onFinished={() => {
+ // We want to do this whenever the chart finishes re-rendering so that we can update the dimensions of
+ // any graphics related to the triggers (e.g. the threshold areas + boundaries)
+ this.updateDimensions();
+ }}
>
{zoomRenderProps => (
<AreaChart
@@ -735,11 +740,6 @@ class MetricChart extends React.PureComponent<Props, State> {
.join('');
},
}}
- onFinished={() => {
- // We want to do this whenever the chart finishes re-rendering so that we can update the dimensions of
- // any graphics related to the triggers (e.g. the threshold areas + boundaries)
- this.updateDimensions();
- }}
/>
)}
</ChartZoom>
|
1e9d363b050a377b6dbd65ddddfe1cc66707f936
|
2022-03-17 02:21:54
|
Robin Rendle
|
fix(ui): spacing problems on the issue details page (#32667)
| false
|
spacing problems on the issue details page (#32667)
|
fix
|
diff --git a/static/app/components/group/releaseStats.tsx b/static/app/components/group/releaseStats.tsx
index 723cc6922b0ff6..aed8167883f101 100644
--- a/static/app/components/group/releaseStats.tsx
+++ b/static/app/components/group/releaseStats.tsx
@@ -53,29 +53,33 @@ const GroupReleaseStats = ({
<Placeholder height="288px" />
) : (
<Fragment>
- <GroupReleaseChart
- group={allEnvironments}
- environment={environmentLabel}
- environmentStats={group.stats}
- release={currentRelease?.release}
- releaseStats={currentRelease?.stats}
- statsPeriod="24h"
- title={t('Last 24 Hours')}
- firstSeen={group.firstSeen}
- lastSeen={group.lastSeen}
- />
- <GroupReleaseChart
- group={allEnvironments}
- environment={environmentLabel}
- environmentStats={group.stats}
- release={currentRelease?.release}
- releaseStats={currentRelease?.stats}
- statsPeriod="30d"
- title={t('Last 30 Days')}
- className="bar-chart-small"
- firstSeen={group.firstSeen}
- lastSeen={group.lastSeen}
- />
+ <GraphContainer>
+ <GroupReleaseChart
+ group={allEnvironments}
+ environment={environmentLabel}
+ environmentStats={group.stats}
+ release={currentRelease?.release}
+ releaseStats={currentRelease?.stats}
+ statsPeriod="24h"
+ title={t('Last 24 Hours')}
+ firstSeen={group.firstSeen}
+ lastSeen={group.lastSeen}
+ />
+ </GraphContainer>
+ <GraphContainer>
+ <GroupReleaseChart
+ group={allEnvironments}
+ environment={environmentLabel}
+ environmentStats={group.stats}
+ release={currentRelease?.release}
+ releaseStats={currentRelease?.stats}
+ statsPeriod="30d"
+ title={t('Last 30 Days')}
+ className="bar-chart-small"
+ firstSeen={group.firstSeen}
+ lastSeen={group.lastSeen}
+ />
+ </GraphContainer>
<SidebarSection
secondary
@@ -157,3 +161,7 @@ export default memo(GroupReleaseStats);
const TooltipWrapper = styled('span')`
margin-left: ${space(0.5)};
`;
+
+const GraphContainer = styled('div')`
+ margin-bottom: ${space(3)};
+`;
diff --git a/static/app/components/group/seenInfo.tsx b/static/app/components/group/seenInfo.tsx
index 1fbc0a1d20d0c2..e5e9f9d1018bfb 100644
--- a/static/app/components/group/seenInfo.tsx
+++ b/static/app/components/group/seenInfo.tsx
@@ -125,7 +125,7 @@ const HovercardWrapper = styled('div')`
`;
const DateWrapper = styled('div')`
- margin-bottom: ${space(2)};
+ margin-bottom: 0;
${overflowEllipsis};
`;
diff --git a/static/app/components/group/sidebarSection.tsx b/static/app/components/group/sidebarSection.tsx
index f0f34836581ee3..ae5d5ada4924b7 100644
--- a/static/app/components/group/sidebarSection.tsx
+++ b/static/app/components/group/sidebarSection.tsx
@@ -24,7 +24,7 @@ const Subheading = styled('h6')`
display: flex;
font-size: ${p => p.theme.fontSizeExtraSmall};
text-transform: uppercase;
- margin-bottom: ${space(1)};
+ margin-bottom: 0;
`;
interface SidebarSectionProps
@@ -49,7 +49,7 @@ function SidebarSection({title, children, secondary, ...props}: SidebarSectionPr
}
const SectionContent = styled('div')<{secondary?: boolean}>`
- margin-bottom: ${p => (p.secondary ? space(2) : space(3))};
+ margin-bottom: ${p => (p.secondary ? space(4) : space(4))};
`;
export default SidebarSection;
|
e92cfdf90ab71829742b062ffecde5654bef9bac
|
2024-12-24 01:05:14
|
Michelle Zhang
|
ref(tsc): convert histogram index to FC (#82484)
| false
|
convert histogram index to FC (#82484)
|
ref
|
diff --git a/static/app/utils/performance/histogram/index.tsx b/static/app/utils/performance/histogram/index.tsx
index 1f60a53f93d953..478d424bde68fe 100644
--- a/static/app/utils/performance/histogram/index.tsx
+++ b/static/app/utils/performance/histogram/index.tsx
@@ -1,9 +1,8 @@
-import {Component} from 'react';
import type {Location} from 'history';
import type {SelectValue} from 'sentry/types/core';
-import {browserHistory} from 'sentry/utils/browserHistory';
import {decodeScalar} from 'sentry/utils/queryString';
+import {useNavigate} from 'sentry/utils/useNavigate';
import {FILTER_OPTIONS} from './constants';
import type {DataFilter} from './types';
@@ -22,34 +21,30 @@ type Props = {
zoomKeys: string[];
};
-class Histogram extends Component<Props> {
- isZoomed() {
- const {location, zoomKeys} = this.props;
- return zoomKeys.map(key => location.query[key]).some(value => value !== undefined);
- }
+function Histogram(props: Props) {
+ const {location, zoomKeys, children} = props;
+ const navigate = useNavigate();
- handleResetView = () => {
- const {location, zoomKeys} = this.props;
+ const isZoomed = () => {
+ return zoomKeys.map(key => location.query[key]).some(value => value !== undefined);
+ };
- browserHistory.push({
+ const handleResetView = () => {
+ navigate({
pathname: location.pathname,
query: removeHistogramQueryStrings(location, zoomKeys),
});
};
- getActiveFilter() {
- const {location} = this.props;
-
+ const getActiveFilter = () => {
const dataFilter = location.query.dataFilter
? decodeScalar(location.query.dataFilter)
: FILTER_OPTIONS[0].value;
return FILTER_OPTIONS.find(item => item.value === dataFilter) || FILTER_OPTIONS[0];
- }
-
- handleFilterChange = (value: string) => {
- const {location, zoomKeys} = this.props;
+ };
- browserHistory.push({
+ const handleFilterChange = (value: string) => {
+ navigate({
pathname: location.pathname,
query: {
...removeHistogramQueryStrings(location, zoomKeys),
@@ -58,16 +53,14 @@ class Histogram extends Component<Props> {
});
};
- render() {
- const childrenProps = {
- isZoomed: this.isZoomed(),
- handleResetView: this.handleResetView,
- activeFilter: this.getActiveFilter(),
- handleFilterChange: this.handleFilterChange,
- filterOptions: FILTER_OPTIONS,
- };
- return this.props.children(childrenProps);
- }
+ const childrenProps = {
+ isZoomed: isZoomed(),
+ handleResetView,
+ activeFilter: getActiveFilter(),
+ handleFilterChange,
+ filterOptions: FILTER_OPTIONS,
+ };
+ return children(childrenProps);
}
export function removeHistogramQueryStrings(location: Location, zoomKeys: string[]) {
diff --git a/static/app/views/performance/transactionSummary/transactionVitals/index.spec.tsx b/static/app/views/performance/transactionSummary/transactionVitals/index.spec.tsx
index 48ba077a60845b..10ca08b0e3f799 100644
--- a/static/app/views/performance/transactionSummary/transactionVitals/index.spec.tsx
+++ b/static/app/views/performance/transactionSummary/transactionVitals/index.spec.tsx
@@ -14,8 +14,8 @@ import {
import ProjectsStore from 'sentry/stores/projectsStore';
import type {Project} from 'sentry/types/project';
-import {browserHistory} from 'sentry/utils/browserHistory';
import {useLocation} from 'sentry/utils/useLocation';
+import {useNavigate} from 'sentry/utils/useNavigate';
import TransactionVitals from 'sentry/views/performance/transactionSummary/transactionVitals';
import {
VITAL_GROUPS,
@@ -25,6 +25,9 @@ import {
jest.mock('sentry/utils/useLocation');
const mockUseLocation = jest.mocked(useLocation);
+jest.mock('sentry/utils/useNavigate');
+
+const mockUseNavigate = jest.mocked(useNavigate);
interface HistogramData {
count: number;
@@ -300,6 +303,8 @@ describe('Performance > Web Vitals', function () {
});
it('resets view properly', async function () {
+ const mockNavigate = jest.fn();
+ mockUseNavigate.mockReturnValue(mockNavigate);
const {organization, router} = initialize({
query: {
fidStart: '20',
@@ -314,7 +319,7 @@ describe('Performance > Web Vitals', function () {
await userEvent.click(screen.getByRole('button', {name: 'Reset View'}));
- expect(browserHistory.push).toHaveBeenCalledWith({
+ expect(mockNavigate).toHaveBeenCalledWith({
query: expect.not.objectContaining(
ZOOM_KEYS.reduce((obj, key) => {
obj[key] = expect.anything();
|
e6bc01fabc021b36ebdb520d33b7ebcaa08004c3
|
2022-01-03 23:13:10
|
Vu Luong
|
fix(ui): Use full opacity for close button in app alerts (#30794)
| false
|
Use full opacity for close button in app alerts (#30794)
|
fix
|
diff --git a/static/app/components/createAlertButton.tsx b/static/app/components/createAlertButton.tsx
index 9eef5615d97dcd..ca4b9c59c19d69 100644
--- a/static/app/components/createAlertButton.tsx
+++ b/static/app/components/createAlertButton.tsx
@@ -172,7 +172,7 @@ function IncompatibleQueryAlert({
</React.Fragment>
)}
<StyledCloseButton
- icon={<IconClose color="yellow300" size="sm" isCircled />}
+ icon={<IconClose size="sm" />}
aria-label={t('Close')}
size="zero"
onClick={onClose}
@@ -438,6 +438,5 @@ const StyledCloseButton = styled(Button)`
&:hover,
&:focus {
background-color: transparent;
- opacity: 1;
}
`;
diff --git a/static/app/views/app/alertMessage.tsx b/static/app/views/app/alertMessage.tsx
index 13925d98c538be..d79409070dcb87 100644
--- a/static/app/views/app/alertMessage.tsx
+++ b/static/app/views/app/alertMessage.tsx
@@ -33,7 +33,7 @@ const AlertMessage = ({alert, system}: Props) => {
{url ? <ExternalLink href={url}>{message}</ExternalLink> : message}
</StyledMessage>
<StyledCloseButton
- icon={<IconClose size="md" isCircled />}
+ icon={<IconClose size="sm" />}
aria-label={t('Close')}
onClick={alert.onClose ?? handleClose}
size="zero"
@@ -57,7 +57,6 @@ const StyledMessage = styled('span')`
const StyledCloseButton = styled(Button)`
background-color: transparent;
- opacity: 0.4;
transition: opacity 0.1s linear;
position: absolute;
top: 50%;
|
14995362eea076ae22c2575a44034b7cc43db524
|
2023-11-03 03:11:52
|
Bartek Ogryczak
|
fix(issue-platform): allowing extra fields in StackTrace/Frames (#59313)
| false
|
allowing extra fields in StackTrace/Frames (#59313)
|
fix
|
diff --git a/src/sentry/issues/event.schema.json b/src/sentry/issues/event.schema.json
index 342947b19a6a13..cc58baf8758a21 100644
--- a/src/sentry/issues/event.schema.json
+++ b/src/sentry/issues/event.schema.json
@@ -1810,7 +1810,7 @@
]
}
},
- "additionalProperties": false
+ "additionalProperties": true
}
]
},
diff --git a/tests/sentry/issues/test_occurrence_consumer.py b/tests/sentry/issues/test_occurrence_consumer.py
index ecdb93ac231cfc..dd87f0cba29679 100644
--- a/tests/sentry/issues/test_occurrence_consumer.py
+++ b/tests/sentry/issues/test_occurrence_consumer.py
@@ -260,6 +260,11 @@ def test_numeric_timestamp_valid_with_new_schema(self) -> None:
message["event"]["timestamp"] = 0000
self.run_test(message)
+ def test_frame_additional_fields_valid_with_new_schema(self) -> None:
+ message = deepcopy(get_test_message(self.project.id))
+ message["event"]["stacktrace"]["frames"][0]["data"] = {"foo": "bar"}
+ self.run_test(message)
+
def test_tags_not_required_with_new_schema(self) -> None:
# per https://develop.sentry.dev/sdk/event-payloads/ tags are optional
message = deepcopy(get_test_message(self.project.id))
|
670480032ffdd930a2d2efe9e73b9c518a255c4f
|
2019-07-09 00:40:36
|
Alberto Leal
|
feat: Remove ts-jest (#13846)
| false
|
Remove ts-jest (#13846)
|
feat
|
diff --git a/babel.config.js b/babel.config.js
index c9eb8dcbe42fae..49d6209393344c 100644
--- a/babel.config.js
+++ b/babel.config.js
@@ -1,6 +1,6 @@
/*eslint-env node*/
module.exports = {
- presets: ['@babel/react', '@babel/env'],
+ presets: ['@babel/react', '@babel/env', '@babel/preset-typescript'],
plugins: [
'emotion',
'lodash',
diff --git a/jest.config.js b/jest.config.js
index 522b7a4904b8be..154397b99a9367 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -29,13 +29,8 @@ module.exports = {
],
transform: {
'^.+\\.jsx?$': 'babel-jest',
- '^.+\\.tsx?$': 'ts-jest',
+ '^.+\\.tsx?$': 'babel-jest',
},
moduleFileExtensions: ['js', 'ts', 'jsx', 'tsx'],
- globals: {
- 'ts-jest': {
- tsConfig: './tsconfig.json',
- diagnostics: false,
- },
- },
+ globals: {},
};
diff --git a/package.json b/package.json
index 55fbd6843171ed..1df385ca6454fe 100644
--- a/package.json
+++ b/package.json
@@ -16,6 +16,7 @@
"@babel/polyfill": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"@babel/preset-react": "^7.0.0",
+ "@babel/preset-typescript": "^7.3.3",
"@babel/runtime": "^7.0.0",
"@sentry/browser": "^5.4.2",
"@sentry/integrations": "^5.4.2",
@@ -131,7 +132,6 @@
"stylelint-config-recommended": "^2.1.0",
"stylelint-config-styled-components": "^0.1.1",
"stylelint-processor-styled-components": "^1.3.0",
- "ts-jest": "^24.0.2",
"tsconfig-paths-webpack-plugin": "^3.2.0",
"webpack-dev-server": "^3.1.10"
},
diff --git a/yarn.lock b/yarn.lock
index 40b07935ac1508..bb4978641b64d6 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -772,6 +772,14 @@
"@babel/helper-plugin-utils" "^7.0.0"
"@babel/plugin-syntax-typescript" "^7.2.0"
+"@babel/plugin-transform-typescript@^7.3.2":
+ version "7.4.5"
+ resolved "https://registry.yarnpkg.com/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.4.5.tgz#ab3351ba35307b79981993536c93ff8be050ba28"
+ integrity sha512-RPB/YeGr4ZrFKNwfuQRlMf2lxoCUaU01MTw39/OFE/RiL8HDjtn68BwEPft1P7JN4akyEmjGWAMNldOV7o9V2g==
+ dependencies:
+ "@babel/helper-plugin-utils" "^7.0.0"
+ "@babel/plugin-syntax-typescript" "^7.2.0"
+
"@babel/plugin-transform-unicode-regex@^7.0.0", "@babel/plugin-transform-unicode-regex@^7.2.0":
version "7.2.0"
resolved "https://registry.yarnpkg.com/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.2.0.tgz#4eb8db16f972f8abb5062c161b8b115546ade08b"
@@ -910,6 +918,14 @@
"@babel/helper-plugin-utils" "^7.0.0"
"@babel/plugin-transform-typescript" "^7.1.0"
+"@babel/preset-typescript@^7.3.3":
+ version "7.3.3"
+ resolved "https://registry.yarnpkg.com/@babel/preset-typescript/-/preset-typescript-7.3.3.tgz#88669911053fa16b2b276ea2ede2ca603b3f307a"
+ integrity sha512-mzMVuIP4lqtn4du2ynEfdO0+RYcslwrZiJHXu4MGaC1ctJiW2fyaeDrtjJGs7R/KebZ1sgowcIoWf4uRpEfKEg==
+ dependencies:
+ "@babel/helper-plugin-utils" "^7.0.0"
+ "@babel/plugin-transform-typescript" "^7.3.2"
+
"@babel/[email protected]":
version "7.0.0"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.0.0.tgz#adeb78fedfc855aa05bc041640f3f6f98e85424c"
@@ -3301,13 +3317,6 @@ browserslist@^4.1.0, browserslist@^4.3.4, browserslist@^4.3.6:
electron-to-chromium "^1.3.96"
node-releases "^1.1.3"
[email protected]:
- version "0.2.6"
- resolved "https://registry.yarnpkg.com/bs-logger/-/bs-logger-0.2.6.tgz#eb7d365307a72cf974cc6cda76b68354ad336bd8"
- integrity sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==
- dependencies:
- fast-json-stable-stringify "2.x"
-
bser@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/bser/-/bser-2.0.0.tgz#9ac78d3ed5d915804fd87acb158bc797147a1719"
@@ -3315,11 +3324,6 @@ bser@^2.0.0:
dependencies:
node-int64 "^0.4.0"
[email protected]:
- version "1.1.1"
- resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz#32713bc028f75c02fdb710d7c7bcec1f2c6070ef"
- integrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==
-
buffer-from@^1.0.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.0.tgz#87fcaa3a298358e0ade6e442cfce840740d1ad04"
@@ -5816,7 +5820,7 @@ fast-glob@^2.0.2:
merge2 "^1.2.3"
micromatch "^3.1.10"
[email protected], fast-json-stable-stringify@^2.0.0:
+fast-json-stable-stringify@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz#d5142c0caee6b1189f87d3a76111064f86c8bbf2"
integrity sha1-1RQsDK7msRifh9OnYREGT4bIu/I=
@@ -8166,13 +8170,6 @@ json3@^3.3.2:
resolved "https://registry.yarnpkg.com/json3/-/json3-3.3.2.tgz#3c0434743df93e2f5c42aee7b19bcb483575f4e1"
integrity sha1-PAQ0dD35Pi9cQq7nsZvLSDV19OE=
[email protected], json5@^2.1.0:
- version "2.1.0"
- resolved "https://registry.yarnpkg.com/json5/-/json5-2.1.0.tgz#e7a0c62c48285c628d20a10b85c89bb807c32850"
- integrity sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==
- dependencies:
- minimist "^1.2.0"
-
json5@^0.5.0, json5@^0.5.1:
version "0.5.1"
resolved "https://registry.yarnpkg.com/json5/-/json5-0.5.1.tgz#1eade7acc012034ad84e2396767ead9fa5495821"
@@ -8185,6 +8182,13 @@ json5@^1.0.1:
dependencies:
minimist "^1.2.0"
+json5@^2.1.0:
+ version "2.1.0"
+ resolved "https://registry.yarnpkg.com/json5/-/json5-2.1.0.tgz#e7a0c62c48285c628d20a10b85c89bb807c32850"
+ integrity sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==
+ dependencies:
+ minimist "^1.2.0"
+
jsonfile@^2.1.0:
version "2.4.0"
resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-2.4.0.tgz#3736a2b428b87bbda0cc83b53fa3d633a35c2ae8"
@@ -8615,7 +8619,7 @@ make-dir@^1.3.0:
dependencies:
pify "^3.0.0"
[email protected], make-error@^1.3.5:
+make-error@^1.3.5:
version "1.3.5"
resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.5.tgz#efe4e81f6db28cadd605c70f29c831b58ef776c8"
integrity sha512-c3sIjNUow0+8swNwVpqoH4YCShKNFkMaw6oH1mNS2haDZQqkeZFlHS3dhoeEbKKmJB4vXpJucU6oH75aDYeE9g==
@@ -9047,7 +9051,7 @@ mixin-object@^2.0.1:
for-in "^0.1.3"
is-extendable "^0.1.1"
[email protected], [email protected], mkdirp@^0.5.0, mkdirp@^0.5.1, mkdirp@~0.5.0, mkdirp@~0.5.1:
[email protected], mkdirp@^0.5.0, mkdirp@^0.5.1, mkdirp@~0.5.0, mkdirp@~0.5.1:
version "0.5.1"
resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903"
integrity sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=
@@ -12044,13 +12048,6 @@ [email protected]:
resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.1.7.tgz#203114d82ad2c5ed9e8e0411b3932875e889e97b"
integrity sha1-IDEU2CrSxe2ejgQRs5ModeiJ6Xs=
[email protected]:
- version "1.11.1"
- resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.11.1.tgz#ea10d8110376982fef578df8fc30b9ac30a07a3e"
- integrity sha512-vIpgF6wfuJOZI7KKKSP+HmiKggadPQAdsp5HiC1mvqnfp0gF1vdwgBWZIdrVft9pgqoMFQN+R7BSWZiBxx+BBw==
- dependencies:
- path-parse "^1.0.6"
-
resolve@^1.1.6:
version "1.5.0"
resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.5.0.tgz#1f09acce796c9a762579f31b2c1cc4c3cddf9f36"
@@ -12280,7 +12277,7 @@ semver@^5.1.0, semver@^5.5.1, semver@^5.6.0:
resolved "https://registry.yarnpkg.com/semver/-/semver-5.6.0.tgz#7e74256fbaa49c75aa7c7a205cc22799cac80004"
integrity sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg==
-semver@^5.5, semver@^5.7.0:
+semver@^5.7.0:
version "5.7.0"
resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.0.tgz#790a7cf6fea5459bac96110b29b60412dc8ff96b"
integrity sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==
@@ -13604,21 +13601,6 @@ ts-essentials@^1.0.3:
resolved "https://registry.yarnpkg.com/ts-essentials/-/ts-essentials-1.0.4.tgz#ce3b5dade5f5d97cf69889c11bf7d2da8555b15a"
integrity sha512-q3N1xS4vZpRouhYHDPwO0bDW3EZ6SK9CrrDHxi/D6BPReSjpVgWIOpLS2o0gSBZm+7q/wyKp6RVM1AeeW7uyfQ==
-ts-jest@^24.0.2:
- version "24.0.2"
- resolved "https://registry.yarnpkg.com/ts-jest/-/ts-jest-24.0.2.tgz#8dde6cece97c31c03e80e474c749753ffd27194d"
- integrity sha512-h6ZCZiA1EQgjczxq+uGLXQlNgeg02WWJBbeT8j6nyIBRQdglqbvzDoHahTEIiS6Eor6x8mK6PfZ7brQ9Q6tzHw==
- dependencies:
- bs-logger "0.x"
- buffer-from "1.x"
- fast-json-stable-stringify "2.x"
- json5 "2.x"
- make-error "1.x"
- mkdirp "0.x"
- resolve "1.x"
- semver "^5.5"
- yargs-parser "10.x"
-
ts-loader@^6.0.4:
version "6.0.4"
resolved "https://registry.yarnpkg.com/ts-loader/-/ts-loader-6.0.4.tgz#bc331ad91a887a60632d94c9f79448666f2c4b63"
@@ -14531,7 +14513,7 @@ yallist@^3.0.0, yallist@^3.0.2:
resolved "https://registry.yarnpkg.com/yallist/-/yallist-3.0.3.tgz#b4b049e314be545e3ce802236d6cd22cd91c3de9"
integrity sha512-S+Zk8DEWE6oKpV+vI3qWkaK+jSbIK86pCwe2IF/xwIpQ8jEuxpw9NyaGjmp9+BoJv5FV2piqCDcoCtStppiq2A==
[email protected], yargs-parser@^10.1.0:
+yargs-parser@^10.1.0:
version "10.1.0"
resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-10.1.0.tgz#7202265b89f7e9e9f2e5765e0fe735a905edbaa8"
integrity sha512-VCIyR1wJoEBZUqk5PA+oOBF6ypbwh5aNB3I50guxAL/quggdfs4TtNHQrSazFA3fYZ+tEqfs0zIGlv0c/rgjbQ==
|
6439df16350746237ebda499800b2dbe8cc74f28
|
2021-10-29 01:59:30
|
josh
|
fix(devservices): chartcuterie is now latest (#29641)
| false
|
chartcuterie is now latest (#29641)
|
fix
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index af38b05f0c5a18..3720cd9b21f750 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -1874,7 +1874,7 @@ def build_cdc_postgres_init_db_volume(settings):
),
"chartcuterie": lambda settings, options: (
{
- "image": "us.gcr.io/sentryio/chartcuterie:nightly",
+ "image": "us.gcr.io/sentryio/chartcuterie:latest",
"pull": True,
"volumes": {settings.CHARTCUTERIE_CONFIG_DIR: {"bind": "/etc/chartcuterie"}},
"environment": {
|
a993c10d7c19dc5f30447ad0f31fb22e8b92301a
|
2021-03-24 22:02:53
|
Billy Vong
|
chore(deps): Upgrade css-loader, file-loader, less-loader in prep for webpack@5 (#24623)
| false
|
Upgrade css-loader, file-loader, less-loader in prep for webpack@5 (#24623)
|
chore
|
diff --git a/package.json b/package.json
index 40e64c6a0469e9..8ba5c947c63614 100644
--- a/package.json
+++ b/package.json
@@ -66,7 +66,7 @@
"core-js": "^3.2.1",
"create-react-class": "^15.6.2",
"crypto-js": "4.0.0",
- "css-loader": "^2.0.1",
+ "css-loader": "^5.0.1",
"diff": "4.0.2",
"dompurify": "^2.2.6",
"downsample": "1.3.0",
@@ -74,7 +74,7 @@
"echarts-for-react": "2.0.16",
"emotion": "10.0.27",
"emotion-theming": "10.0.27",
- "file-loader": "^3.0.1",
+ "file-loader": "^6.2.0",
"focus-visible": "^5.0.2",
"fork-ts-checker-webpack-plugin": "^4.1.2",
"framer-motion": "^2.9.4",
@@ -86,7 +86,7 @@
"jquery": "2.2.2",
"js-cookie": "2.2.1",
"less": "^3.9.0",
- "less-loader": "^4.1.0",
+ "less-loader": "^7.3.0",
"lodash": "^4.17.19",
"marked": "0.7.0",
"mini-css-extract-plugin": "^1.3.9",
@@ -166,7 +166,7 @@
"mockdate": "3.0.2",
"object.fromentries": "^2.0.0",
"prettier": "2.1.2",
- "react-refresh": "^0.9.0",
+ "react-refresh": "^0.8.3",
"react-test-renderer": "16.12.0",
"size-limit": "^4.5.6",
"source-map-loader": "^0.2.4",
diff --git a/webpack.config.js b/webpack.config.js
index f11431ddb35f73..74d2a6d3d00483 100644
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -271,6 +271,8 @@ let appConfig = {
{
loader: 'file-loader',
options: {
+ // This needs to be `false` because of platformicons package
+ esModule: false,
name: '[name].[hash:6].[ext]',
},
},
diff --git a/yarn.lock b/yarn.lock
index 9c155d6afe788d..02ea08b937db01 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -4730,7 +4730,7 @@ camelcase-keys@^6.1.1:
map-obj "^4.0.0"
quick-lru "^4.0.1"
-camelcase@^5.0.0, camelcase@^5.2.0, camelcase@^5.3.1:
+camelcase@^5.0.0, camelcase@^5.3.1:
version "5.3.1"
resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.3.1.tgz#e3c9b31569e106811df242f715725a1f4c494320"
integrity sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==
@@ -4740,6 +4740,11 @@ camelcase@^6.0.0:
resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.0.0.tgz#5259f7c30e35e278f1bdc2a4d91230b37cad981e"
integrity sha512-8KMDF1Vz2gzOq54ONPJS65IvTUaB1cHJ2DMM7MbPmLZljDH1qpzzLsWdiN9pHh6qvkRVDTi/07+eNGch/oLU4w==
+camelcase@^6.2.0:
+ version "6.2.0"
+ resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.2.0.tgz#924af881c9d525ac9d87f40d964e5cea982a1809"
+ integrity sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg==
+
caniuse-api@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/caniuse-api/-/caniuse-api-3.0.0.tgz#5e4d90e2274961d46291997df599e3ed008ee4c0"
@@ -5052,11 +5057,6 @@ clone@^1.0.2:
resolved "https://registry.yarnpkg.com/clone/-/clone-1.0.4.tgz#da309cc263df15994c688ca902179ca3c7cd7c7e"
integrity sha1-2jCcwmPfFZlMaIypAheco8fNfH4=
-clone@^2.1.1:
- version "2.1.2"
- resolved "https://registry.yarnpkg.com/clone/-/clone-2.1.2.tgz#1b7f4b9f591f1e8f83670401600345a02887435f"
- integrity sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18=
-
clsx@^1.0.4:
version "1.1.1"
resolved "https://registry.yarnpkg.com/clsx/-/clsx-1.1.1.tgz#98b3134f9abbdf23b2663491ace13c5c03a73188"
@@ -5144,6 +5144,11 @@ colorette@^1.2.1:
resolved "https://registry.yarnpkg.com/colorette/-/colorette-1.2.1.tgz#4d0b921325c14faf92633086a536db6e89564b1b"
integrity sha512-puCDz0CzydiSYOrnXpz/PKd69zRrribezjtE9yd4zvytoRc8+RY/KJPvtPFKZS3E3wP6neGyMe0vOTlHO5L3Pw==
+colorette@^1.2.2:
+ version "1.2.2"
+ resolved "https://registry.yarnpkg.com/colorette/-/colorette-1.2.2.tgz#cbcc79d5e99caea2dbf10eb3a26fd8b3e6acfa94"
+ integrity sha512-MKGMzyfeuutC/ZJ1cba9NqcNpfeqMUcYmyF1ZFY6/Cn7CNSAKx6a+s48sqLqyAiZuaP2TcqMhoo+dlwFnVxT9w==
+
colors@^1.1.2:
version "1.4.0"
resolved "https://registry.yarnpkg.com/colors/-/colors-1.4.0.tgz#c50491479d4c1bdaed2c9ced32cf7c7dc2360f78"
@@ -5556,23 +5561,6 @@ css-declaration-sorter@^4.0.1:
postcss "^7.0.1"
timsort "^0.3.0"
-css-loader@^2.0.1:
- version "2.1.1"
- resolved "https://registry.yarnpkg.com/css-loader/-/css-loader-2.1.1.tgz#d8254f72e412bb2238bb44dd674ffbef497333ea"
- integrity sha512-OcKJU/lt232vl1P9EEDamhoO9iKY3tIjY5GU+XDLblAykTdgs6Ux9P1hTHve8nFKy5KPpOXOsVI/hIwi3841+w==
- dependencies:
- camelcase "^5.2.0"
- icss-utils "^4.1.0"
- loader-utils "^1.2.3"
- normalize-path "^3.0.0"
- postcss "^7.0.14"
- postcss-modules-extract-imports "^2.0.0"
- postcss-modules-local-by-default "^2.0.6"
- postcss-modules-scope "^2.1.0"
- postcss-modules-values "^2.0.0"
- postcss-value-parser "^3.3.0"
- schema-utils "^1.0.0"
-
css-loader@^3.5.3:
version "3.6.0"
resolved "https://registry.yarnpkg.com/css-loader/-/css-loader-3.6.0.tgz#2e4b2c7e6e2d27f8c8f28f61bffcd2e6c91ef645"
@@ -5611,6 +5599,24 @@ css-loader@^4.2.1:
schema-utils "^2.7.0"
semver "^7.3.2"
+css-loader@^5.0.1:
+ version "5.1.3"
+ resolved "https://registry.yarnpkg.com/css-loader/-/css-loader-5.1.3.tgz#87f6fc96816b20debe3cf682f85c7e56a963d0d1"
+ integrity sha512-CoPZvyh8sLiGARK3gqczpfdedbM74klGWurF2CsNZ2lhNaXdLIUks+3Mfax3WBeRuHoglU+m7KG/+7gY6G4aag==
+ dependencies:
+ camelcase "^6.2.0"
+ cssesc "^3.0.0"
+ icss-utils "^5.1.0"
+ loader-utils "^2.0.0"
+ postcss "^8.2.8"
+ postcss-modules-extract-imports "^3.0.0"
+ postcss-modules-local-by-default "^4.0.0"
+ postcss-modules-scope "^3.0.0"
+ postcss-modules-values "^4.0.0"
+ postcss-value-parser "^4.1.0"
+ schema-utils "^3.0.0"
+ semver "^7.3.4"
+
css-select-base-adapter@^0.1.1:
version "0.1.1"
resolved "https://registry.yarnpkg.com/css-select-base-adapter/-/css-select-base-adapter-0.1.1.tgz#3b2ff4972cc362ab88561507a95408a1432135d7"
@@ -7246,14 +7252,6 @@ file-entry-cache@^5.0.1:
dependencies:
flat-cache "^2.0.1"
-file-loader@^3.0.1:
- version "3.0.1"
- resolved "https://registry.yarnpkg.com/file-loader/-/file-loader-3.0.1.tgz#f8e0ba0b599918b51adfe45d66d1e771ad560faa"
- integrity sha512-4sNIOXgtH/9WZq4NvlfU3Opn5ynUsqBwSLyM+I7UOwdGigTBYfVVQEwe/msZNX/j4pCJTIM14Fsw66Svo1oVrw==
- dependencies:
- loader-utils "^1.0.2"
- schema-utils "^1.0.0"
-
file-loader@^6.0.0:
version "6.0.0"
resolved "https://registry.yarnpkg.com/file-loader/-/file-loader-6.0.0.tgz#97bbfaab7a2460c07bcbd72d3a6922407f67649f"
@@ -7262,6 +7260,14 @@ file-loader@^6.0.0:
loader-utils "^2.0.0"
schema-utils "^2.6.5"
+file-loader@^6.2.0:
+ version "6.2.0"
+ resolved "https://registry.yarnpkg.com/file-loader/-/file-loader-6.2.0.tgz#baef7cf8e1840df325e4390b4484879480eebe4d"
+ integrity sha512-qo3glqyTa61Ytg4u73GultjHGjdRyig3tG6lPtyX/jOEJvHif9uB0/OCI2Kif6ctF3caQTW2G5gym21oAsI4pw==
+ dependencies:
+ loader-utils "^2.0.0"
+ schema-utils "^3.0.0"
+
file-system-cache@^1.0.5:
version "1.0.5"
resolved "https://registry.yarnpkg.com/file-system-cache/-/file-system-cache-1.0.5.tgz#84259b36a2bbb8d3d6eb1021d3132ffe64cfff4f"
@@ -8359,18 +8365,18 @@ [email protected], iconv-lite@^0.4.24, iconv-lite@~0.4.13:
dependencies:
safer-buffer ">= 2.1.2 < 3"
-icss-replace-symbols@^1.1.0:
- version "1.1.0"
- resolved "https://registry.yarnpkg.com/icss-replace-symbols/-/icss-replace-symbols-1.1.0.tgz#06ea6f83679a7749e386cfe1fe812ae5db223ded"
- integrity sha1-Bupvg2ead0njhs/h/oEq5dsiPe0=
-
-icss-utils@^4.0.0, icss-utils@^4.1.0, icss-utils@^4.1.1:
+icss-utils@^4.0.0, icss-utils@^4.1.1:
version "4.1.1"
resolved "https://registry.yarnpkg.com/icss-utils/-/icss-utils-4.1.1.tgz#21170b53789ee27447c2f47dd683081403f9a467"
integrity sha512-4aFq7wvWyMHKgxsH8QQtGpvbASCf+eM3wPRLI6R+MgAnTCZ6STYsRvttLvRWK0Nfif5piF394St3HeJDaljGPA==
dependencies:
postcss "^7.0.14"
+icss-utils@^5.0.0, icss-utils@^5.1.0:
+ version "5.1.0"
+ resolved "https://registry.yarnpkg.com/icss-utils/-/icss-utils-5.1.0.tgz#c6be6858abd013d768e98366ae47e25d5887b1ae"
+ integrity sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA==
+
ieee754@^1.1.4:
version "1.1.13"
resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.1.13.tgz#ec168558e95aa181fd87d37f55c32bbcb6708b84"
@@ -9979,6 +9985,11 @@ kleur@^3.0.3:
resolved "https://registry.yarnpkg.com/kleur/-/kleur-3.0.3.tgz#a79c9ecc86ee1ce3fa6206d1216c501f147fc07e"
integrity sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==
+klona@^2.0.4:
+ version "2.0.4"
+ resolved "https://registry.yarnpkg.com/klona/-/klona-2.0.4.tgz#7bb1e3affb0cb8624547ef7e8f6708ea2e39dfc0"
+ integrity sha512-ZRbnvdg/NxqzC7L9Uyqzf4psi1OM4Cuc+sJAkQPjO6XkQIJTNbfK2Rsmbw8fx1p2mkZdp2FZYo2+LwXYY/uwIA==
+
known-css-properties@^0.18.0:
version "0.18.0"
resolved "https://registry.yarnpkg.com/known-css-properties/-/known-css-properties-0.18.0.tgz#d6e00b56ee1d5b0d171fd86df1583cfb012c521f"
@@ -10015,14 +10026,14 @@ left-pad@^1.3.0:
resolved "https://registry.yarnpkg.com/left-pad/-/left-pad-1.3.0.tgz#5b8a3a7765dfe001261dde915589e782f8c94d1e"
integrity sha512-XI5MPzVNApjAyhQzphX8BkmKsKUxD4LdyK24iZeQGinBN9yTQT3bFlCBy/aVx2HrNcqQGsdot8ghrjyrvMCoEA==
-less-loader@^4.1.0:
- version "4.1.0"
- resolved "https://registry.yarnpkg.com/less-loader/-/less-loader-4.1.0.tgz#2c1352c5b09a4f84101490274fd51674de41363e"
- integrity sha512-KNTsgCE9tMOM70+ddxp9yyt9iHqgmSs0yTZc5XH5Wo+g80RWRIYNqE58QJKm/yMud5wZEvz50ugRDuzVIkyahg==
+less-loader@^7.3.0:
+ version "7.3.0"
+ resolved "https://registry.yarnpkg.com/less-loader/-/less-loader-7.3.0.tgz#f9d6d36d18739d642067a05fb5bd70c8c61317e5"
+ integrity sha512-Mi8915g7NMaLlgi77mgTTQvK022xKRQBIVDSyfl3ErTuBhmZBQab0mjeJjNNqGbdR+qrfTleKXqbGI4uEFavxg==
dependencies:
- clone "^2.1.1"
- loader-utils "^1.1.0"
- pify "^3.0.0"
+ klona "^2.0.4"
+ loader-utils "^2.0.0"
+ schema-utils "^3.0.0"
less@^3.9.0:
version "3.13.1"
@@ -10124,7 +10135,7 @@ [email protected], loader-utils@^2.0.0:
emojis-list "^3.0.0"
json5 "^2.1.2"
-loader-utils@^1.0.2, loader-utils@^1.1.0, loader-utils@^1.2.3, loader-utils@^1.4.0:
+loader-utils@^1.1.0, loader-utils@^1.2.3, loader-utils@^1.4.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-1.4.0.tgz#c579b5e34cb34b1a74edc6c1fb36bfa371d5a613"
integrity sha512-qH0WSMBtn/oHuwjy/NucEgbx5dbxxnxup9s4PVXJUDHZBQY+s0NWA9rJf53RBnQZxfch7euUui7hpoAPvALZdA==
@@ -10831,6 +10842,11 @@ nanoid@^3.1.10:
resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.1.12.tgz#6f7736c62e8d39421601e4a0c77623a97ea69654"
integrity sha512-1qstj9z5+x491jfiC4Nelk+f8XBad7LN20PmyWINJEMRSf3wcAjAWysw1qaA8z6NSKe2sjq1hRSDpBH5paCb6A==
+nanoid@^3.1.20:
+ version "3.1.22"
+ resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.1.22.tgz#b35f8fb7d151990a8aebd5aa5015c03cf726f844"
+ integrity sha512-/2ZUaJX2ANuLtTvqTlgqBQNJoQO398KyJgZloL0PZkC0dpysjncRUPsFe3DUPzz/y3h+u7C46np8RMuvF3jsSQ==
+
nanomatch@^1.2.9:
version "1.2.13"
resolved "https://registry.yarnpkg.com/nanomatch/-/nanomatch-1.2.13.tgz#b87a8aa4fc0de8fe6be88895b38983ff265bd119"
@@ -11927,14 +11943,10 @@ postcss-modules-extract-imports@^2.0.0:
dependencies:
postcss "^7.0.5"
-postcss-modules-local-by-default@^2.0.6:
- version "2.0.6"
- resolved "https://registry.yarnpkg.com/postcss-modules-local-by-default/-/postcss-modules-local-by-default-2.0.6.tgz#dd9953f6dd476b5fd1ef2d8830c8929760b56e63"
- integrity sha512-oLUV5YNkeIBa0yQl7EYnxMgy4N6noxmiwZStaEJUSe2xPMcdNc8WmBQuQCx18H5psYbVxz8zoHk0RAAYZXP9gA==
- dependencies:
- postcss "^7.0.6"
- postcss-selector-parser "^6.0.0"
- postcss-value-parser "^3.3.1"
+postcss-modules-extract-imports@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/postcss-modules-extract-imports/-/postcss-modules-extract-imports-3.0.0.tgz#cda1f047c0ae80c97dbe28c3e76a43b88025741d"
+ integrity sha512-bdHleFnP3kZ4NYDhuGlVK+CMrQ/pqUm8bx/oGL93K6gVwiclvX5x0n76fYMKuIGKzlABOy13zsvqjb0f92TEXw==
postcss-modules-local-by-default@^3.0.2, postcss-modules-local-by-default@^3.0.3:
version "3.0.3"
@@ -11946,7 +11958,16 @@ postcss-modules-local-by-default@^3.0.2, postcss-modules-local-by-default@^3.0.3
postcss-selector-parser "^6.0.2"
postcss-value-parser "^4.1.0"
-postcss-modules-scope@^2.1.0, postcss-modules-scope@^2.2.0:
+postcss-modules-local-by-default@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/postcss-modules-local-by-default/-/postcss-modules-local-by-default-4.0.0.tgz#ebbb54fae1598eecfdf691a02b3ff3b390a5a51c"
+ integrity sha512-sT7ihtmGSF9yhm6ggikHdV0hlziDTX7oFoXtuVWeDd3hHObNkcHRo9V3yg7vCAY7cONyxJC/XXCmmiHHcvX7bQ==
+ dependencies:
+ icss-utils "^5.0.0"
+ postcss-selector-parser "^6.0.2"
+ postcss-value-parser "^4.1.0"
+
+postcss-modules-scope@^2.2.0:
version "2.2.0"
resolved "https://registry.yarnpkg.com/postcss-modules-scope/-/postcss-modules-scope-2.2.0.tgz#385cae013cc7743f5a7d7602d1073a89eaae62ee"
integrity sha512-YyEgsTMRpNd+HmyC7H/mh3y+MeFWevy7V1evVhJWewmMbjDHIbZbOXICC2y+m1xI1UVfIT1HMW/O04Hxyu9oXQ==
@@ -11954,13 +11975,12 @@ postcss-modules-scope@^2.1.0, postcss-modules-scope@^2.2.0:
postcss "^7.0.6"
postcss-selector-parser "^6.0.0"
-postcss-modules-values@^2.0.0:
- version "2.0.0"
- resolved "https://registry.yarnpkg.com/postcss-modules-values/-/postcss-modules-values-2.0.0.tgz#479b46dc0c5ca3dc7fa5270851836b9ec7152f64"
- integrity sha512-Ki7JZa7ff1N3EIMlPnGTZfUMe69FFwiQPnVSXC9mnn3jozCRBYIxiZd44yJOV2AmabOo4qFf8s0dC/+lweG7+w==
+postcss-modules-scope@^3.0.0:
+ version "3.0.0"
+ resolved "https://registry.yarnpkg.com/postcss-modules-scope/-/postcss-modules-scope-3.0.0.tgz#9ef3151456d3bbfa120ca44898dfca6f2fa01f06"
+ integrity sha512-hncihwFA2yPath8oZ15PZqvWGkWf+XUfQgUGamS4LqoP1anQLOsOJw0vr7J7IwLpoY9fatA2qiGUGmuZL0Iqlg==
dependencies:
- icss-replace-symbols "^1.1.0"
- postcss "^7.0.6"
+ postcss-selector-parser "^6.0.4"
postcss-modules-values@^3.0.0:
version "3.0.0"
@@ -11970,6 +11990,13 @@ postcss-modules-values@^3.0.0:
icss-utils "^4.0.0"
postcss "^7.0.6"
+postcss-modules-values@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/postcss-modules-values/-/postcss-modules-values-4.0.0.tgz#d7c5e7e68c3bb3c9b27cbf48ca0bb3ffb4602c9c"
+ integrity sha512-RDxHkAiEGI78gS2ofyvCsu7iycRv7oqw5xMWn9iMoR0N/7mf9D50ecQqUo5BZ9Zh2vH4bCUR/ktCqbB9m8vJjQ==
+ dependencies:
+ icss-utils "^5.0.0"
+
postcss-normalize-charset@^4.0.1:
version "4.0.1"
resolved "https://registry.yarnpkg.com/postcss-normalize-charset/-/postcss-normalize-charset-4.0.1.tgz#8b35add3aee83a136b0471e0d59be58a50285dd4"
@@ -12144,6 +12171,16 @@ postcss-selector-parser@^6.0.0, postcss-selector-parser@^6.0.2:
indexes-of "^1.0.1"
uniq "^1.0.1"
+postcss-selector-parser@^6.0.4:
+ version "6.0.4"
+ resolved "https://registry.yarnpkg.com/postcss-selector-parser/-/postcss-selector-parser-6.0.4.tgz#56075a1380a04604c38b063ea7767a129af5c2b3"
+ integrity sha512-gjMeXBempyInaBqpp8gODmwZ52WaYsVOsfr4L4lDQ7n3ncD6mEyySiDtgzCT+NYC0mmeOLvtsF8iaEf0YT6dBw==
+ dependencies:
+ cssesc "^3.0.0"
+ indexes-of "^1.0.1"
+ uniq "^1.0.1"
+ util-deprecate "^1.0.2"
+
postcss-svgo@^4.0.2:
version "4.0.2"
resolved "https://registry.yarnpkg.com/postcss-svgo/-/postcss-svgo-4.0.2.tgz#17b997bc711b333bab143aaed3b8d3d6e3d38258"
@@ -12168,7 +12205,7 @@ postcss-unique-selectors@^4.0.1:
postcss "^7.0.0"
uniqs "^2.0.0"
-postcss-value-parser@^3.0.0, postcss-value-parser@^3.3.0, postcss-value-parser@^3.3.1:
+postcss-value-parser@^3.0.0, postcss-value-parser@^3.3.1:
version "3.3.1"
resolved "https://registry.yarnpkg.com/postcss-value-parser/-/postcss-value-parser-3.3.1.tgz#9ff822547e2893213cf1c30efa51ac5fd1ba8281"
integrity sha512-pISE66AbVkp4fDQ7VHBwRNXzAAKJjw4Vw7nWI/+Q3vuly7SNfgYXvm6i5IgFylHGK5sP/xHAbB7N49OS4gWNyQ==
@@ -12187,6 +12224,15 @@ postcss@^7.0.0, postcss@^7.0.1, postcss@^7.0.14, postcss@^7.0.2, postcss@^7.0.21
source-map "^0.6.1"
supports-color "^6.1.0"
+postcss@^8.2.8:
+ version "8.2.8"
+ resolved "https://registry.yarnpkg.com/postcss/-/postcss-8.2.8.tgz#0b90f9382efda424c4f0f69a2ead6f6830d08ece"
+ integrity sha512-1F0Xb2T21xET7oQV9eKuctbM9S7BC0fetoHCc4H13z0PT6haiRLP4T0ZY4XWh7iLP0usgqykT6p9B2RtOf4FPw==
+ dependencies:
+ colorette "^1.2.2"
+ nanoid "^3.1.20"
+ source-map "^0.6.1"
+
prelude-ls@~1.1.2:
version "1.1.2"
resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54"
@@ -12841,11 +12887,6 @@ react-refresh@^0.8.3:
resolved "https://registry.yarnpkg.com/react-refresh/-/react-refresh-0.8.3.tgz#721d4657672d400c5e3c75d063c4a85fb2d5d68f"
integrity sha512-X8jZHc7nCMjaCqoU+V2I0cOhNW+QMBwSUkeXnTi8IPe6zaRWfn60ZzvFDZqWPfmSJfjub7dDW1SP0jaHWLu/hg==
-react-refresh@^0.9.0:
- version "0.9.0"
- resolved "https://registry.yarnpkg.com/react-refresh/-/react-refresh-0.9.0.tgz#71863337adc3e5c2f8a6bfddd12ae3bfe32aafbf"
- integrity sha512-Gvzk7OZpiqKSkxsQvO/mbTN1poglhmAV7gR/DdIrRrSMXraRQQlfikRJOr3Nb9GTMPC5kof948Zy6jJZIFtDvQ==
-
[email protected]:
version "3.2.0"
resolved "https://registry.yarnpkg.com/react-router/-/react-router-3.2.0.tgz#62b6279d589b70b34e265113e4c0a9261a02ed36"
@@ -13740,6 +13781,13 @@ semver@^6.0.0, semver@^6.3.0:
resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d"
integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==
+semver@^7.3.4:
+ version "7.3.4"
+ resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.4.tgz#27aaa7d2e4ca76452f98d3add093a72c943edc97"
+ integrity sha512-tCfb2WLjqFAtXn4KEdxIhalnRtoKFN7nAwj0B3ZXCbQloV2tq5eDbcTmT68JJD3nRJq24/XgxtQKFIpQdtvmVw==
+ dependencies:
+ lru-cache "^6.0.0"
+
[email protected]:
version "0.17.1"
resolved "https://registry.yarnpkg.com/send/-/send-0.17.1.tgz#c1d8b059f7900f7466dd4938bdc44e11ddb376c8"
|
526f08eeaafa3a830f70671ad473afd7b9b05a0f
|
2022-12-22 21:44:03
|
Anthony Ryan
|
chore(ui): Losslessly compress PNG images (#42599)
| false
|
Losslessly compress PNG images (#42599)
|
chore
|
diff --git a/.github/screenshots/issue-details.png b/.github/screenshots/issue-details.png
index a892ddeee7735c..52188d4863a73c 100644
Binary files a/.github/screenshots/issue-details.png and b/.github/screenshots/issue-details.png differ
diff --git a/.github/screenshots/projects.png b/.github/screenshots/projects.png
index 87eeac723ebd2c..6d477581bad8bb 100644
Binary files a/.github/screenshots/projects.png and b/.github/screenshots/projects.png differ
diff --git a/.github/screenshots/releases.png b/.github/screenshots/releases.png
index 47741ef520793d..6fa117ce9f48a5 100644
Binary files a/.github/screenshots/releases.png and b/.github/screenshots/releases.png differ
diff --git a/.github/screenshots/transaction-summary.png b/.github/screenshots/transaction-summary.png
index b7a38dc5c07e63..64555ee60a39d7 100644
Binary files a/.github/screenshots/transaction-summary.png and b/.github/screenshots/transaction-summary.png differ
diff --git a/docs-ui/images/gradients.png b/docs-ui/images/gradients.png
index d74b57989ef33a..6243761eaf18ba 100644
Binary files a/docs-ui/images/gradients.png and b/docs-ui/images/gradients.png differ
diff --git a/fixtures/rookout-bw.png b/fixtures/rookout-bw.png
index dc2632cddc7d90..44376a2a3c65e8 100644
Binary files a/fixtures/rookout-bw.png and b/fixtures/rookout-bw.png differ
diff --git a/fixtures/rookout-color.png b/fixtures/rookout-color.png
index 796cb83d625c12..7c1273b0c2afe5 100644
Binary files a/fixtures/rookout-color.png and b/fixtures/rookout-color.png differ
diff --git a/src/sentry/static/sentry/images/email/alert-badge-critical.png b/src/sentry/static/sentry/images/email/alert-badge-critical.png
index 92b254dd700d19..15050e22d2f9fd 100644
Binary files a/src/sentry/static/sentry/images/email/alert-badge-critical.png and b/src/sentry/static/sentry/images/email/alert-badge-critical.png differ
diff --git a/src/sentry/static/sentry/images/email/alert-badge-warning.png b/src/sentry/static/sentry/images/email/alert-badge-warning.png
index ba7164c4939b59..cafee3797143ca 100644
Binary files a/src/sentry/static/sentry/images/email/alert-badge-warning.png and b/src/sentry/static/sentry/images/email/alert-badge-warning.png differ
diff --git a/src/sentry/static/sentry/images/email/arrow-decrease.png b/src/sentry/static/sentry/images/email/arrow-decrease.png
index 6c82bf12d02b2a..812a3f1419d620 100644
Binary files a/src/sentry/static/sentry/images/email/arrow-decrease.png and b/src/sentry/static/sentry/images/email/arrow-decrease.png differ
diff --git a/src/sentry/static/sentry/images/email/arrow-increase.png b/src/sentry/static/sentry/images/email/arrow-increase.png
index 97ab08ddccebc7..629b675c6dfa1e 100644
Binary files a/src/sentry/static/sentry/images/email/arrow-increase.png and b/src/sentry/static/sentry/images/email/arrow-increase.png differ
diff --git a/src/sentry/static/sentry/images/email/arrow-right.png b/src/sentry/static/sentry/images/email/arrow-right.png
index 1cee9a49dde8bc..8b340d59920943 100644
Binary files a/src/sentry/static/sentry/images/email/arrow-right.png and b/src/sentry/static/sentry/images/email/arrow-right.png differ
diff --git a/src/sentry/static/sentry/images/email/avatar-notch.png b/src/sentry/static/sentry/images/email/avatar-notch.png
index da09ef715def0f..6146834a30eab3 100644
Binary files a/src/sentry/static/sentry/images/email/avatar-notch.png and b/src/sentry/static/sentry/images/email/avatar-notch.png differ
diff --git a/src/sentry/static/sentry/images/email/circle-bg.png b/src/sentry/static/sentry/images/email/circle-bg.png
index f718cdca616979..2dde561d702836 100644
Binary files a/src/sentry/static/sentry/images/email/circle-bg.png and b/src/sentry/static/sentry/images/email/circle-bg.png differ
diff --git a/src/sentry/static/sentry/images/email/circle-bottom-center.png b/src/sentry/static/sentry/images/email/circle-bottom-center.png
index 17c7c73cda4938..885f77562860cb 100644
Binary files a/src/sentry/static/sentry/images/email/circle-bottom-center.png and b/src/sentry/static/sentry/images/email/circle-bottom-center.png differ
diff --git a/src/sentry/static/sentry/images/email/circle-bottom-left.png b/src/sentry/static/sentry/images/email/circle-bottom-left.png
index 4053238e571af7..56248153e5ccba 100644
Binary files a/src/sentry/static/sentry/images/email/circle-bottom-left.png and b/src/sentry/static/sentry/images/email/circle-bottom-left.png differ
diff --git a/src/sentry/static/sentry/images/email/circle-bottom-right.png b/src/sentry/static/sentry/images/email/circle-bottom-right.png
index 433fc2d9def34a..fb9ab1b92418bd 100644
Binary files a/src/sentry/static/sentry/images/email/circle-bottom-right.png and b/src/sentry/static/sentry/images/email/circle-bottom-right.png differ
diff --git a/src/sentry/static/sentry/images/email/circle-middle-left.png b/src/sentry/static/sentry/images/email/circle-middle-left.png
index ee75ad8cc70e69..3bc76d22d19315 100644
Binary files a/src/sentry/static/sentry/images/email/circle-middle-left.png and b/src/sentry/static/sentry/images/email/circle-middle-left.png differ
diff --git a/src/sentry/static/sentry/images/email/circle-middle-right.png b/src/sentry/static/sentry/images/email/circle-middle-right.png
index eda8f96b00338b..01774d44c9bf78 100644
Binary files a/src/sentry/static/sentry/images/email/circle-middle-right.png and b/src/sentry/static/sentry/images/email/circle-middle-right.png differ
diff --git a/src/sentry/static/sentry/images/email/circle-top-center.png b/src/sentry/static/sentry/images/email/circle-top-center.png
index a2db9a37dd5f4e..cced1cb88686a8 100644
Binary files a/src/sentry/static/sentry/images/email/circle-top-center.png and b/src/sentry/static/sentry/images/email/circle-top-center.png differ
diff --git a/src/sentry/static/sentry/images/email/circle-top-left.png b/src/sentry/static/sentry/images/email/circle-top-left.png
index a1847800c6ec41..1c72deeaad999f 100644
Binary files a/src/sentry/static/sentry/images/email/circle-top-left.png and b/src/sentry/static/sentry/images/email/circle-top-left.png differ
diff --git a/src/sentry/static/sentry/images/email/circle-top-right.png b/src/sentry/static/sentry/images/email/circle-top-right.png
index ff7a2c762ee830..becb91bc2cfc40 100644
Binary files a/src/sentry/static/sentry/images/email/circle-top-right.png and b/src/sentry/static/sentry/images/email/circle-top-right.png differ
diff --git a/src/sentry/static/sentry/images/email/icon-circle-exclamation.png b/src/sentry/static/sentry/images/email/icon-circle-exclamation.png
index aecd767a846b2a..a06b570c456cae 100644
Binary files a/src/sentry/static/sentry/images/email/icon-circle-exclamation.png and b/src/sentry/static/sentry/images/email/icon-circle-exclamation.png differ
diff --git a/src/sentry/static/sentry/images/email/icon-circle-lightning.png b/src/sentry/static/sentry/images/email/icon-circle-lightning.png
index be9788d80d93b3..58695f6766cc72 100644
Binary files a/src/sentry/static/sentry/images/email/icon-circle-lightning.png and b/src/sentry/static/sentry/images/email/icon-circle-lightning.png differ
diff --git a/src/sentry/static/sentry/images/email/icon-warning.png b/src/sentry/static/sentry/images/email/icon-warning.png
index b80a7a1f539b42..06b04fc194492d 100644
Binary files a/src/sentry/static/sentry/images/email/icon-warning.png and b/src/sentry/static/sentry/images/email/icon-warning.png differ
diff --git a/src/sentry/static/sentry/images/email/sentry-pattern.png b/src/sentry/static/sentry/images/email/sentry-pattern.png
index 3b55347807434c..556385d446b17c 100644
Binary files a/src/sentry/static/sentry/images/email/sentry-pattern.png and b/src/sentry/static/sentry/images/email/sentry-pattern.png differ
diff --git a/src/sentry/static/sentry/images/email/sentry_logo_full.png b/src/sentry/static/sentry/images/email/sentry_logo_full.png
index 8228feba539ad0..8eaa5cdd743f29 100644
Binary files a/src/sentry/static/sentry/images/email/sentry_logo_full.png and b/src/sentry/static/sentry/images/email/sentry_logo_full.png differ
diff --git a/src/sentry/static/sentry/images/email/sentry_logo_mark.png b/src/sentry/static/sentry/images/email/sentry_logo_mark.png
index e9ecc628c0bafd..72b276aeb03b69 100644
Binary files a/src/sentry/static/sentry/images/email/sentry_logo_mark.png and b/src/sentry/static/sentry/images/email/sentry_logo_mark.png differ
diff --git a/src/sentry/static/sentry/images/email/slack-logo.png b/src/sentry/static/sentry/images/email/slack-logo.png
index 89d3f848a7be25..a28d13f1f23627 100644
Binary files a/src/sentry/static/sentry/images/email/slack-logo.png and b/src/sentry/static/sentry/images/email/slack-logo.png differ
diff --git a/src/sentry/static/sentry/images/favicon-dark.png b/src/sentry/static/sentry/images/favicon-dark.png
index d4ebbddda6a372..ad809160ed01e1 100644
Binary files a/src/sentry/static/sentry/images/favicon-dark.png and b/src/sentry/static/sentry/images/favicon-dark.png differ
diff --git a/src/sentry/static/sentry/images/favicon.png b/src/sentry/static/sentry/images/favicon.png
index 784210549a2508..b4ad103a610ed1 100644
Binary files a/src/sentry/static/sentry/images/favicon.png and b/src/sentry/static/sentry/images/favicon.png differ
diff --git a/src/sentry/static/sentry/images/favicon_dev.png b/src/sentry/static/sentry/images/favicon_dev.png
index 06d8f918570efe..d83073f18954f0 100644
Binary files a/src/sentry/static/sentry/images/favicon_dev.png and b/src/sentry/static/sentry/images/favicon_dev.png differ
diff --git a/src/sentry/static/sentry/images/logos/apple-touch-icon-152x152.png b/src/sentry/static/sentry/images/logos/apple-touch-icon-152x152.png
index dbf215cb806992..b267c0111cc82a 100644
Binary files a/src/sentry/static/sentry/images/logos/apple-touch-icon-152x152.png and b/src/sentry/static/sentry/images/logos/apple-touch-icon-152x152.png differ
diff --git a/src/sentry/static/sentry/images/logos/apple-touch-icon-76x76.png b/src/sentry/static/sentry/images/logos/apple-touch-icon-76x76.png
index bb166ec20b67ba..838eaf2b8b823b 100644
Binary files a/src/sentry/static/sentry/images/logos/apple-touch-icon-76x76.png and b/src/sentry/static/sentry/images/logos/apple-touch-icon-76x76.png differ
diff --git a/src/sentry/static/sentry/images/logos/apple-touch-icon.png b/src/sentry/static/sentry/images/logos/apple-touch-icon.png
index f3cc5509ba0508..e7058558261bae 100644
Binary files a/src/sentry/static/sentry/images/logos/apple-touch-icon.png and b/src/sentry/static/sentry/images/logos/apple-touch-icon.png differ
diff --git a/src/sentry/static/sentry/images/logos/default-organization-logo.png b/src/sentry/static/sentry/images/logos/default-organization-logo.png
index 007acd161b27ac..8f35ddc9c668bf 100644
Binary files a/src/sentry/static/sentry/images/logos/default-organization-logo.png and b/src/sentry/static/sentry/images/logos/default-organization-logo.png differ
diff --git a/src/sentry/static/sentry/images/logos/sentry-avatar.png b/src/sentry/static/sentry/images/logos/sentry-avatar.png
index e094616d89d1d3..2895eb0a2cd0bf 100644
Binary files a/src/sentry/static/sentry/images/logos/sentry-avatar.png and b/src/sentry/static/sentry/images/logos/sentry-avatar.png differ
diff --git a/src/sentry/static/sentry/images/sentry-email-avatar.png b/src/sentry/static/sentry/images/sentry-email-avatar.png
index 389352373cd2eb..35eb18d4c0253a 100644
Binary files a/src/sentry/static/sentry/images/sentry-email-avatar.png and b/src/sentry/static/sentry/images/sentry-email-avatar.png differ
diff --git a/src/sentry/static/sentry/images/sentry-glyph-black.png b/src/sentry/static/sentry/images/sentry-glyph-black.png
index 787c55fe74ffd8..5a8bcd7b6c6491 100644
Binary files a/src/sentry/static/sentry/images/sentry-glyph-black.png and b/src/sentry/static/sentry/images/sentry-glyph-black.png differ
diff --git a/static/images/pattern/sentry-pattern.png b/static/images/pattern/sentry-pattern.png
index 1f7312b5f6af00..8447c4684d6a36 100644
Binary files a/static/images/pattern/sentry-pattern.png and b/static/images/pattern/sentry-pattern.png differ
diff --git a/static/images/sentry-avatar.png b/static/images/sentry-avatar.png
index e094616d89d1d3..2895eb0a2cd0bf 100644
Binary files a/static/images/sentry-avatar.png and b/static/images/sentry-avatar.png differ
diff --git a/static/images/spot/habitsSuccessfulCustomer.jpg b/static/images/spot/habitsSuccessfulCustomer.jpg
index df15ed1caca48d..220b6223f536ab 100644
Binary files a/static/images/spot/habitsSuccessfulCustomer.jpg and b/static/images/spot/habitsSuccessfulCustomer.jpg differ
diff --git a/static/images/spot/sentry-robot.png b/static/images/spot/sentry-robot.png
index 6de269df2d3cb9..5e0b239f1f7b1e 100644
Binary files a/static/images/spot/sentry-robot.png and b/static/images/spot/sentry-robot.png differ
|
a9895178b56b9cf20e4b4d18d09ff0b005ec230d
|
2024-01-08 22:40:13
|
Dominik Buszowiecki
|
feat(browser-starfish): add initial ui to enable image view (#62223)
| false
|
add initial ui to enable image view (#62223)
|
feat
|
diff --git a/static/app/views/performance/browser/resources/resourceSummaryPage/sampleImages.tsx b/static/app/views/performance/browser/resources/resourceSummaryPage/sampleImages.tsx
index d980f313b0bdb8..a583c4b7ca79a3 100644
--- a/static/app/views/performance/browser/resources/resourceSummaryPage/sampleImages.tsx
+++ b/static/app/views/performance/browser/resources/resourceSummaryPage/sampleImages.tsx
@@ -1,8 +1,16 @@
+import {CSSProperties, useState} from 'react';
+import {useTheme} from '@emotion/react';
import styled from '@emotion/styled';
+import {Button} from 'sentry/components/button';
+import Link from 'sentry/components/links/link';
import {t} from 'sentry/locale';
+import {space} from 'sentry/styles/space';
import {formatBytesBase2} from 'sentry/utils';
import getDynamicText from 'sentry/utils/getDynamicText';
+import usePageFilters from 'sentry/utils/usePageFilters';
+import useProjects from 'sentry/utils/useProjects';
+import {normalizeUrl} from 'sentry/utils/withDomainRequired';
import {useIndexedResourcesQuery} from 'sentry/views/performance/browser/resources/utils/useIndexedResourceQuery';
import ChartPanel from 'sentry/views/starfish/components/chartPanel';
import {SpanIndexedField} from 'sentry/views/starfish/types';
@@ -13,6 +21,9 @@ const {SPAN_GROUP, SPAN_DESCRIPTION, HTTP_RESPONSE_CONTENT_LENGTH} = SpanIndexed
const imageWidth = '200px';
function SampleImages({groupId}: Props) {
+ const isImagesEnabled = true; // TODO - this is temporary, this will be controlled by a project setting
+ const [showImages, setShowImages] = useState(isImagesEnabled);
+
const imageResources = useIndexedResourcesQuery({
queryConditions: [`${SPAN_GROUP}:${groupId}`],
sorts: [{field: `measurements.${HTTP_RESPONSE_CONTENT_LENGTH}`, kind: 'desc'}],
@@ -33,51 +44,90 @@ function SampleImages({groupId}: Props) {
.splice(0, 5);
return (
- <ChartPanel title={t('Example Images')}>
- <ImageWrapper>
- {filteredResources.map(resource => {
- return (
- <ImageContainer
- src={resource[SPAN_DESCRIPTION]}
- fileName={getFileNameFromDescription(resource[SPAN_DESCRIPTION])}
- size={resource[`measurements.${HTTP_RESPONSE_CONTENT_LENGTH}`]}
- key={resource[SPAN_DESCRIPTION]}
- />
- );
- })}
- </ImageWrapper>
+ <ChartPanel title={showImages ? t('Largest Images') : undefined}>
+ {showImages ? (
+ <ImageWrapper>
+ {filteredResources.map(resource => {
+ return (
+ <ImageContainer
+ src={resource[SPAN_DESCRIPTION]}
+ showImage={isImagesEnabled}
+ fileName={getFileNameFromDescription(resource[SPAN_DESCRIPTION])}
+ size={resource[`measurements.${HTTP_RESPONSE_CONTENT_LENGTH}`]}
+ key={resource[SPAN_DESCRIPTION]}
+ />
+ );
+ })}
+ </ImageWrapper>
+ ) : (
+ // TODO - the selection to show only links should be persisted for awhile
+ <DisabledImages onClickShowLinks={() => setShowImages(true)} />
+ )}
</ChartPanel>
);
}
-function ImageContainer({
- src,
- fileName,
- size,
-}: {
+function DisabledImages(props: {onClickShowLinks?: () => void}) {
+ const {onClickShowLinks} = props;
+ const {
+ selection: {projects: selectedProjects},
+ } = usePageFilters();
+ const {projects} = useProjects();
+ const firstProjectSelected = projects.find(
+ project => project.id === selectedProjects[0].toString()
+ );
+
+ return (
+ <div>
+ <DisabledImageTextContainer>
+ <h6>{t('Images not shown')}</h6>
+ {t(
+ 'You know, you can see the actual images that are on your site if you opt into this feature.'
+ )}
+ </DisabledImageTextContainer>
+ <ButtonContainer>
+ <Button onClick={onClickShowLinks}>Only show links</Button>
+ <Link
+ to={normalizeUrl(
+ `/settings/projects/${firstProjectSelected?.slug}/performance/`
+ )}
+ >
+ <Button priority="primary">Enable in Settings</Button>
+ </Link>
+ </ButtonContainer>
+ </div>
+ );
+}
+
+function ImageContainer(props: {
fileName: string;
+ showImage: boolean;
size: number;
src: string;
}) {
+ const theme = useTheme();
+ const [hasError, setHasError] = useState(false);
+
+ const {fileName, size, src, showImage = true} = props;
const fileSize = getDynamicText({
value: formatBytesBase2(size),
fixed: 'xx KB',
});
+ const commonStyles: CSSProperties = {minWidth: imageWidth, height: '200px'};
+
return (
<div style={{width: '100%', wordWrap: 'break-word'}}>
- <img src={src} style={{minWidth: imageWidth, height: '200px'}} />
+ {showImage && !hasError ? (
+ <img onError={() => setHasError(true)} src={src} style={commonStyles} />
+ ) : (
+ <div style={{...commonStyles, backgroundColor: theme.gray100}} />
+ )}
{fileName} ({fileSize})
</div>
);
}
-const ImageWrapper = styled('div')`
- display: grid;
- grid-template-columns: repeat(auto-fill, ${imageWidth});
- gap: 30px;
-`;
-
const getFileNameFromDescription = (description: string) => {
try {
const url = new URL(description);
@@ -87,4 +137,26 @@ const getFileNameFromDescription = (description: string) => {
}
};
+const ImageWrapper = styled('div')`
+ display: grid;
+ grid-template-columns: repeat(auto-fill, ${imageWidth});
+ padding-top: ${space(2)};
+ gap: 30px;
+`;
+
+const ButtonContainer = styled('div')`
+ display: grid;
+ grid-template-columns: repeat(2, auto);
+ gap: ${space(1)};
+ justify-content: center;
+ align-items: center;
+ padding-top: ${space(2)};
+`;
+
+const DisabledImageTextContainer = styled('div')`
+ text-align: center;
+ width: 300px;
+ margin: auto;
+`;
+
export default SampleImages;
diff --git a/static/app/views/performance/browser/resources/utils/useIndexedResourceQuery.ts b/static/app/views/performance/browser/resources/utils/useIndexedResourceQuery.ts
index 2184ec0e3cbdf9..fef3cca6dd8860 100644
--- a/static/app/views/performance/browser/resources/utils/useIndexedResourceQuery.ts
+++ b/static/app/views/performance/browser/resources/utils/useIndexedResourceQuery.ts
@@ -10,6 +10,7 @@ import {SpanIndexedField} from 'sentry/views/starfish/types';
const {SPAN_DESCRIPTION, HTTP_RESPONSE_CONTENT_LENGTH} = SpanIndexedField;
type Options = {
+ enabled?: boolean;
limit?: number;
queryConditions?: string[];
referrer?: string;
@@ -21,6 +22,7 @@ export const useIndexedResourcesQuery = ({
limit = 50,
sorts,
referrer,
+ enabled = true,
}: Options) => {
const pageFilters = usePageFilters();
const location = useLocation();
@@ -55,6 +57,7 @@ export const useIndexedResourcesQuery = ({
orgSlug,
referrer,
options: {
+ enabled,
refetchOnWindowFocus: false,
},
});
|
7b6bc7538f9bcb548d321ea7011c0e3fc87e81fa
|
2023-10-23 18:18:37
|
Ogi
|
feat(ddm): 10s granularity support (#58581)
| false
|
10s granularity support (#58581)
|
feat
|
diff --git a/static/app/utils/metrics.tsx b/static/app/utils/metrics.tsx
index c9480dd33c52e4..d713add1c1957a 100644
--- a/static/app/utils/metrics.tsx
+++ b/static/app/utils/metrics.tsx
@@ -2,7 +2,12 @@ import {useEffect, useMemo, useState} from 'react';
import {InjectedRouter} from 'react-router';
import moment from 'moment';
-import {getInterval} from 'sentry/components/charts/utils';
+import {ApiResult} from 'sentry/api';
+import {
+ DateTimeObject,
+ getDiffInMinutes,
+ getInterval,
+} from 'sentry/components/charts/utils';
import {t} from 'sentry/locale';
import {defined, formatBytesBase2, formatBytesBase10} from 'sentry/utils';
import {formatPercentage, getDuration} from 'sentry/utils/formatters';
@@ -134,7 +139,7 @@ export function useMetricsData({
const useCase = getUseCaseFromMri(mri);
const field = op ? `${op}(${mri})` : mri;
- const interval = getInterval(datetime, 'metrics');
+ const interval = getMetricsInterval(datetime);
const queryToSend = {
...getDateTimeParams(datetime),
@@ -146,7 +151,6 @@ export function useMetricsData({
interval,
groupBy,
allowPrivate: true, // TODO(ddm): reconsider before widening audience
-
// max result groups
per_page: 20,
};
@@ -158,18 +162,27 @@ export function useMetricsData({
staleTime: 0,
refetchOnReconnect: true,
refetchOnWindowFocus: true,
- // auto refetch every 60 seconds
- refetchInterval: data => {
- // don't refetch if the request failed
- if (!data) {
- return false;
- }
- return 60 * 1000;
- },
+ refetchInterval: data => getRefetchInterval(data, interval),
}
);
}
+function getRefetchInterval(
+ data: ApiResult | undefined,
+ interval: string
+): number | false {
+ // no data means request failed - don't refetch
+ if (!data) {
+ return false;
+ }
+ if (interval === '10s') {
+ // refetch every 10 seconds
+ return 10 * 1000;
+ }
+ // refetch every 60 seconds
+ return 60 * 1000;
+}
+
// Wraps useMetricsData and provides two additional features:
// 1. return data is undefined only during the initial load
// 2. provides a callback to trim the data to a specific time range when chart zoom is used
@@ -221,6 +234,23 @@ export function useMetricsDataZoom(props: MetricsQuery) {
};
}
+// Wraps getInterval since other users of this function do not have support for 10s granularity
+function getMetricsInterval(dateTimeObj: DateTimeObject) {
+ const interval = getInterval(dateTimeObj, 'metrics');
+
+ if (interval !== '1m') {
+ return interval;
+ }
+
+ const diffInMinutes = getDiffInMinutes(dateTimeObj);
+
+ if (diffInMinutes <= 60) {
+ return '10s';
+ }
+
+ return interval;
+}
+
function getDateTimeParams({start, end, period}: PageFilters['datetime']) {
return period
? {statsPeriod: period}
diff --git a/static/app/views/ddm/chart.tsx b/static/app/views/ddm/chart.tsx
index 6834bd817a6a98..88156ec908e6fe 100644
--- a/static/app/views/ddm/chart.tsx
+++ b/static/app/views/ddm/chart.tsx
@@ -66,6 +66,7 @@ export function MetricChart({
// TODO(ddm): This assumes that all series have the same bucket size
const bucketSize = seriesToShow[0]?.data[1]?.name - seriesToShow[0]?.data[0]?.name;
+ const isSubMinuteBucket = bucketSize < 60_000;
const seriesLength = seriesToShow[0]?.data.length;
const formatters = {
@@ -75,6 +76,7 @@ export function MetricChart({
isGroupedByDate: true,
bucketSize,
showTimeInTooltip: true,
+ addSecondsToTimeFormat: isSubMinuteBucket,
};
const displayFogOfWar = operation && ['sum', 'count'].includes(operation);
@@ -185,8 +187,7 @@ function FogOfWar({
return null;
}
- // For smaller time frames we want to show a wider fog of war
- const widthFactor = bucketSize > 30 * 60_000 ? 1 : 2;
+ const widthFactor = getWidthFactor(bucketSize);
const fogOfWarWidth = widthFactor * bucketSize + 30_000;
const seriesWidth = bucketSize * seriesLength;
@@ -201,6 +202,22 @@ function FogOfWar({
return <FogOfWarOverlay width={width ?? 0} />;
}
+function getWidthFactor(bucketSize: number) {
+ // In general, fog of war should cover the last bucket
+ if (bucketSize > 30 * 60_000) {
+ return 1;
+ }
+
+ // for 10s timeframe we want to show a fog of war that spans last 10 buckets
+ // because on average, we are missing last 90 seconds of data
+ if (bucketSize <= 10_000) {
+ return 10;
+ }
+
+ // For smaller time frames we want to show a wider fog of war
+ return 2;
+}
+
const ChartWrapper = styled('div')`
position: relative;
height: 300px;
|
e0fcb5451cc4c59a25d4207c8543b8faa7e9a126
|
2024-07-24 22:58:08
|
Michelle Fu
|
feat(anomaly detection): Send subscription update data to Seer (#74522)
| false
|
Send subscription update data to Seer (#74522)
|
feat
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index 539431a1525b57..fe139502dee4af 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -3136,9 +3136,14 @@ def custom_parameter_sort(parameter: dict) -> tuple[str, int]:
SEER_GROUPING_URL = SEER_DEFAULT_URL # for local development, these share a URL
SEER_GROUPING_TIMEOUT = 1
+SEER_ANOMALY_DETECTION_MODEL_VERSION = "v1"
SEER_ANOMALY_DETECTION_URL = SEER_DEFAULT_URL # for local development, these share a URL
SEER_ANOMALY_DETECTION_TIMEOUT = 5
+SEER_ANOMALY_DETECTION_ENDPOINT_URL = (
+ f"/{SEER_ANOMALY_DETECTION_MODEL_VERSION}/anomaly-detection/detect"
+)
+
SEER_AUTOFIX_GITHUB_APP_USER_ID = 157164994
SEER_AUTOFIX_FORCE_USE_REPOS: list[dict] = []
diff --git a/src/sentry/incidents/subscription_processor.py b/src/sentry/incidents/subscription_processor.py
index 72a96f1b58d38f..48a3f167f37f13 100644
--- a/src/sentry/incidents/subscription_processor.py
+++ b/src/sentry/incidents/subscription_processor.py
@@ -12,8 +12,10 @@
from django.utils import timezone
from sentry_redis_tools.retrying_cluster import RetryingRedisCluster
from snuba_sdk import Column, Condition, Limit, Op
+from urllib3.exceptions import MaxRetryError, TimeoutError
from sentry import features
+from sentry.conf.server import SEER_ANOMALY_DETECTION_ENDPOINT_URL
from sentry.constants import CRASH_RATE_ALERT_AGGREGATE_ALIAS, CRASH_RATE_ALERT_SESSION_COUNT_ALIAS
from sentry.incidents.logic import (
CRITICAL_TRIGGER_LABEL,
@@ -24,6 +26,7 @@
)
from sentry.incidents.models.alert_rule import (
AlertRule,
+ AlertRuleDetectionType,
AlertRuleMonitorTypeInt,
AlertRuleThresholdType,
AlertRuleTrigger,
@@ -43,6 +46,8 @@
from sentry.incidents.tasks import handle_trigger_action
from sentry.incidents.utils.types import QuerySubscriptionUpdate
from sentry.models.project import Project
+from sentry.net.http import connection_from_url
+from sentry.seer.signed_seer_api import make_signed_seer_api_request
from sentry.snuba.dataset import Dataset
from sentry.snuba.entity_subscription import (
ENTITY_TIME_COLUMNS,
@@ -51,8 +56,9 @@
get_entity_subscription_from_snuba_query,
)
from sentry.snuba.models import QuerySubscription
-from sentry.utils import metrics, redis
+from sentry.utils import json, metrics, redis
from sentry.utils.dates import to_datetime
+from sentry.utils.json import JSONDecodeError
logger = logging.getLogger(__name__)
REDIS_TTL = int(timedelta(days=7).total_seconds())
@@ -89,6 +95,11 @@ class SubscriptionProcessor:
AlertRuleThresholdType.BELOW: (operator.lt, operator.gt),
}
+ seer_anomaly_detection_connection_pool = connection_from_url(
+ settings.SEER_ANOMALY_DETECTION_URL,
+ timeout=settings.SEER_ANOMALY_DETECTION_TIMEOUT,
+ )
+
def __init__(self, subscription: QuerySubscription) -> None:
self.subscription = subscription
try:
@@ -500,6 +511,15 @@ def process_update(self, subscription_update: QuerySubscriptionUpdate) -> None:
aggregation_value = self.get_aggregation_value(subscription_update)
+ self.has_anomaly_detection = features.has(
+ "organizations:anomaly-detection-alerts", self.subscription.project.organization
+ )
+
+ if self.has_anomaly_detection:
+ potential_anomalies = self.get_anomaly_data_from_seer(aggregation_value)
+ if potential_anomalies is None:
+ return []
+
# Trigger callbacks for any AlertRules that may need to know about the subscription update
# Current callback will update the activation metric values & delete querysubscription on finish
# TODO: register over/under triggers as alert rule callbacks as well
@@ -522,31 +542,70 @@ def process_update(self, subscription_update: QuerySubscriptionUpdate) -> None:
with transaction.atomic(router.db_for_write(AlertRule)):
# Triggers is the threshold - NOT an instance of a trigger
for trigger in self.triggers:
- if alert_operator(
- aggregation_value, trigger.alert_threshold
- ) and not self.check_trigger_matches_status(trigger, TriggerStatus.ACTIVE):
- # If the value has breached our threshold (above/below)
- # And the trigger is not yet active
- metrics.incr("incidents.alert_rules.threshold", tags={"type": "alert"})
- # triggering a threshold will create an incident and set the status to active
- incident_trigger = self.trigger_alert_threshold(trigger, aggregation_value)
- if incident_trigger is not None:
- fired_incident_triggers.append(incident_trigger)
- else:
- self.trigger_alert_counts[trigger.id] = 0
-
if (
- resolve_operator(aggregation_value, self.calculate_resolve_threshold(trigger))
- and self.active_incident
- and self.check_trigger_matches_status(trigger, TriggerStatus.ACTIVE)
+ self.has_anomaly_detection
+ and trigger.alert_rule.detection_type == AlertRuleDetectionType.DYNAMIC
):
- metrics.incr("incidents.alert_rules.threshold", tags={"type": "resolve"})
- incident_trigger = self.trigger_resolve_threshold(trigger, aggregation_value)
-
- if incident_trigger is not None:
- fired_incident_triggers.append(incident_trigger)
+ # NOTE: There should only be one anomaly in the list
+ for potential_anomaly in potential_anomalies:
+ if self.has_anomaly(
+ potential_anomaly, trigger.label
+ ) and not self.check_trigger_matches_status(trigger, TriggerStatus.ACTIVE):
+ metrics.incr("incidents.alert_rules.threshold", tags={"type": "alert"})
+ incident_trigger = self.trigger_alert_threshold(
+ trigger, aggregation_value
+ )
+ if incident_trigger is not None:
+ fired_incident_triggers.append(incident_trigger)
+ else:
+ self.trigger_alert_counts[trigger.id] = 0
+
+ if (
+ not self.has_anomaly(potential_anomaly, trigger.label)
+ and self.active_incident
+ and self.check_trigger_matches_status(trigger, TriggerStatus.ACTIVE)
+ ):
+ metrics.incr(
+ "incidents.alert_rules.threshold", tags={"type": "resolve"}
+ )
+ incident_trigger = self.trigger_resolve_threshold(
+ trigger, aggregation_value
+ )
+
+ if incident_trigger is not None:
+ fired_incident_triggers.append(incident_trigger)
+ else:
+ self.trigger_resolve_counts[trigger.id] = 0
else:
- self.trigger_resolve_counts[trigger.id] = 0
+ if alert_operator(
+ aggregation_value, trigger.alert_threshold
+ ) and not self.check_trigger_matches_status(trigger, TriggerStatus.ACTIVE):
+ # If the value has breached our threshold (above/below)
+ # And the trigger is not yet active
+ metrics.incr("incidents.alert_rules.threshold", tags={"type": "alert"})
+ # triggering a threshold will create an incident and set the status to active
+ incident_trigger = self.trigger_alert_threshold(trigger, aggregation_value)
+ if incident_trigger is not None:
+ fired_incident_triggers.append(incident_trigger)
+ else:
+ self.trigger_alert_counts[trigger.id] = 0
+
+ if (
+ resolve_operator(
+ aggregation_value, self.calculate_resolve_threshold(trigger)
+ )
+ and self.active_incident
+ and self.check_trigger_matches_status(trigger, TriggerStatus.ACTIVE)
+ ):
+ metrics.incr("incidents.alert_rules.threshold", tags={"type": "resolve"})
+ incident_trigger = self.trigger_resolve_threshold(
+ trigger, aggregation_value
+ )
+
+ if incident_trigger is not None:
+ fired_incident_triggers.append(incident_trigger)
+ else:
+ self.trigger_resolve_counts[trigger.id] = 0
if fired_incident_triggers:
# For all the newly created incidents
@@ -562,6 +621,98 @@ def process_update(self, subscription_update: QuerySubscriptionUpdate) -> None:
# before the next one then we might alert twice.
self.update_alert_rule_stats()
+ def has_anomaly(self, anomaly, label: str) -> bool:
+ """
+ Helper function to determine whether we care about an anomaly based on the
+ anomaly type and trigger type.
+ TODO: replace the anomaly types with constants (once they're added to Sentry)
+ """
+ anomaly_type = anomaly.get("anomaly", {}).get("anomaly_type")
+
+ if anomaly_type == "anomaly_high" or (
+ label == WARNING_TRIGGER_LABEL and anomaly_type == "anomaly_low"
+ ):
+ return True
+ return False
+
+ def get_anomaly_data_from_seer(self, aggregation_value: float | None):
+ try:
+ anomaly_detection_config = {
+ "time_period": self.alert_rule.threshold_period,
+ "sensitivity": self.alert_rule.sensitivity,
+ "seasonality": self.alert_rule.seasonality,
+ "direction": self.alert_rule.threshold_type,
+ }
+
+ context = {
+ "id": self.alert_rule.id,
+ "cur_window": {
+ "timestamp": self.last_update,
+ "value": aggregation_value,
+ },
+ }
+ response = make_signed_seer_api_request(
+ self.seer_anomaly_detection_connection_pool,
+ SEER_ANOMALY_DETECTION_ENDPOINT_URL,
+ json.dumps(
+ {
+ "organization_id": self.subscription.project.organization.id,
+ "project_id": self.subscription.project_id,
+ "config": anomaly_detection_config,
+ "context": context,
+ }
+ ).encode("utf-8"),
+ )
+ except (TimeoutError, MaxRetryError):
+ logger.warning(
+ "Timeout error when hitting anomaly detection endpoint",
+ extra={
+ "subscription_id": self.subscription.id,
+ "dataset": self.subscription.snuba_query.dataset,
+ "organization_id": self.subscription.project.organization.id,
+ "project_id": self.subscription.project_id,
+ "alert_rule_id": self.alert_rule.id,
+ },
+ )
+ return None
+
+ if response.status != 200:
+ logger.error(
+ f"Received {response.status} when calling Seer endpoint {SEER_ANOMALY_DETECTION_ENDPOINT_URL}.", # noqa
+ extra={"response_data": response.data},
+ )
+ return None
+
+ try:
+ results = json.loads(response.data.decode("utf-8")).get("anomalies")
+ if not results:
+ logger.warning(
+ "Seer anomaly detection response returned no potential anomalies",
+ extra={
+ "ad_config": anomaly_detection_config,
+ "context": context,
+ "response_data": response.data,
+ "reponse_code": response.status,
+ },
+ )
+ return None
+ return results
+ except (
+ AttributeError,
+ UnicodeError,
+ JSONDecodeError,
+ ):
+ logger.exception(
+ "Failed to parse Seer anomaly detection response",
+ extra={
+ "ad_config": anomaly_detection_config,
+ "context": context,
+ "response_data": response.data,
+ "reponse_code": response.status,
+ },
+ )
+ return None
+
def calculate_event_date_from_update_date(self, update_date: datetime) -> datetime:
"""
Calculates the date that an event actually happened based on the date that we
diff --git a/tests/sentry/incidents/test_subscription_processor.py b/tests/sentry/incidents/test_subscription_processor.py
index 34c886baaf34d5..d06db81808e5f2 100644
--- a/tests/sentry/incidents/test_subscription_processor.py
+++ b/tests/sentry/incidents/test_subscription_processor.py
@@ -4,12 +4,15 @@
from functools import cached_property
from random import randint
from unittest import mock
-from unittest.mock import Mock, call, patch
+from unittest.mock import MagicMock, Mock, call, patch
from uuid import uuid4
+import orjson
import pytest
from django.utils import timezone
+from urllib3.response import HTTPResponse
+from sentry.conf.server import SEER_ANOMALY_DETECTION_ENDPOINT_URL
from sentry.incidents.logic import (
CRITICAL_TRIGGER_LABEL,
WARNING_TRIGGER_LABEL,
@@ -19,7 +22,10 @@
)
from sentry.incidents.models.alert_rule import (
AlertRule,
+ AlertRuleDetectionType,
AlertRuleMonitorTypeInt,
+ AlertRuleSeasonality,
+ AlertRuleSensitivity,
AlertRuleThresholdType,
AlertRuleTrigger,
AlertRuleTriggerAction,
@@ -52,6 +58,7 @@
from sentry.testutils.cases import BaseMetricsTestCase, SnubaTestCase, TestCase
from sentry.testutils.factories import DEFAULT_EVENT_DATA
from sentry.testutils.helpers.datetime import freeze_time, iso_format
+from sentry.testutils.helpers.features import with_feature
from sentry.utils import json
EMPTY = object()
@@ -285,6 +292,18 @@ def comparison_rule_below(self):
self.trigger.update(alert_threshold=50)
return rule
+ @cached_property
+ def dynamic_rule(self):
+ rule = self.rule
+ rule.update(
+ detection_type=AlertRuleDetectionType.DYNAMIC,
+ sensitivity=AlertRuleSensitivity.HIGH,
+ seasonality=AlertRuleSeasonality.AUTO,
+ )
+ # dynamic alert rules have a threshold of 0.0
+ self.trigger.update(alert_threshold=0)
+ return rule
+
@cached_property
def trigger(self):
return self.rule.alertruletrigger_set.get()
@@ -408,6 +427,232 @@ def test_no_alert(self):
self.assert_trigger_does_not_exist(self.trigger)
self.assert_action_handler_called_with_actions(None, [])
+ @mock.patch(
+ "sentry.incidents.subscription_processor.SubscriptionProcessor.seer_anomaly_detection_connection_pool.urlopen"
+ )
+ @with_feature("organizations:incidents")
+ @with_feature("organizations:anomaly-detection-alerts")
+ def test_seer_call(self, mock_seer_request: MagicMock):
+ # trigger a warning
+ rule = self.dynamic_rule
+ trigger = self.trigger
+ warning_trigger = create_alert_rule_trigger(rule, WARNING_TRIGGER_LABEL, 0)
+ warning_action = create_alert_rule_trigger_action(
+ warning_trigger,
+ AlertRuleTriggerAction.Type.EMAIL,
+ AlertRuleTriggerAction.TargetType.USER,
+ str(self.user.id),
+ )
+ seer_return_value_1 = {
+ "anomalies": [
+ {
+ "anomaly": {"anomaly_score": 0.7, "anomaly_type": "anomaly_low"},
+ "timestamp": 1,
+ "value": 5,
+ }
+ ]
+ }
+
+ mock_seer_request.return_value = HTTPResponse(orjson.dumps(seer_return_value_1), status=200)
+ processor = self.send_update(rule, 5, timedelta(minutes=-3))
+
+ assert mock_seer_request.call_args.args[0] == "POST"
+ assert mock_seer_request.call_args.args[1] == SEER_ANOMALY_DETECTION_ENDPOINT_URL
+ deserialized_body = json.loads(mock_seer_request.call_args.kwargs["body"])
+ assert deserialized_body["organization_id"] == self.sub.project.organization.id
+ assert deserialized_body["project_id"] == self.sub.project_id
+ assert deserialized_body["config"]["time_period"] == rule.threshold_period
+ assert deserialized_body["config"]["sensitivity"] == rule.sensitivity.value
+ assert deserialized_body["config"]["seasonality"] == rule.seasonality.value
+ assert deserialized_body["config"]["direction"] == rule.threshold_type
+ assert deserialized_body["context"]["id"] == rule.id
+ assert deserialized_body["context"]["cur_window"]["value"] == 5
+
+ self.assert_trigger_counts(processor, trigger, 0, 0)
+ self.assert_trigger_counts(processor, warning_trigger, 0, 0)
+ incident = self.assert_active_incident(rule)
+ self.assert_trigger_exists_with_status(incident, warning_trigger, TriggerStatus.ACTIVE)
+ self.assert_trigger_does_not_exist(trigger)
+ self.assert_actions_fired_for_incident(
+ incident,
+ [warning_action],
+ [(5, IncidentStatus.WARNING, mock.ANY)],
+ )
+
+ # trigger critical
+ seer_return_value_2 = {
+ "anomalies": [
+ {
+ "anomaly": {"anomaly_score": 0.9, "anomaly_type": "anomaly_high"},
+ "timestamp": 1,
+ "value": 10,
+ }
+ ]
+ }
+
+ mock_seer_request.return_value = HTTPResponse(orjson.dumps(seer_return_value_2), status=200)
+ processor = self.send_update(rule, 10, timedelta(minutes=-2))
+
+ assert mock_seer_request.call_args.args[0] == "POST"
+ assert mock_seer_request.call_args.args[1] == SEER_ANOMALY_DETECTION_ENDPOINT_URL
+ deserialized_body = json.loads(mock_seer_request.call_args.kwargs["body"])
+ assert deserialized_body["organization_id"] == self.sub.project.organization.id
+ assert deserialized_body["project_id"] == self.sub.project_id
+ assert deserialized_body["config"]["time_period"] == rule.threshold_period
+ assert deserialized_body["config"]["sensitivity"] == rule.sensitivity.value
+ assert deserialized_body["config"]["seasonality"] == rule.seasonality.value
+ assert deserialized_body["config"]["direction"] == rule.threshold_type
+ assert deserialized_body["context"]["id"] == rule.id
+ assert deserialized_body["context"]["cur_window"]["value"] == 10
+
+ self.assert_trigger_counts(processor, trigger, 0, 0)
+ self.assert_trigger_counts(processor, warning_trigger, 0, 0)
+ incident = self.assert_active_incident(rule)
+ self.assert_trigger_exists_with_status(incident, warning_trigger, TriggerStatus.ACTIVE)
+ self.assert_trigger_exists_with_status(incident, trigger, TriggerStatus.ACTIVE)
+ self.assert_actions_fired_for_incident(
+ incident,
+ [warning_action],
+ [(10, IncidentStatus.CRITICAL, mock.ANY)],
+ )
+
+ # trigger a resolution
+ seer_return_value_3 = {
+ "anomalies": [
+ {
+ "anomaly": {"anomaly_score": 0.5, "anomaly_type": "none"},
+ "timestamp": 1,
+ "value": 1,
+ }
+ ]
+ }
+
+ mock_seer_request.return_value = HTTPResponse(orjson.dumps(seer_return_value_3), status=200)
+ processor = self.send_update(rule, 1, timedelta(minutes=-1))
+
+ assert mock_seer_request.call_args.args[0] == "POST"
+ assert mock_seer_request.call_args.args[1] == SEER_ANOMALY_DETECTION_ENDPOINT_URL
+ deserialized_body = json.loads(mock_seer_request.call_args.kwargs["body"])
+ assert deserialized_body["organization_id"] == self.sub.project.organization.id
+ assert deserialized_body["project_id"] == self.sub.project_id
+ assert deserialized_body["config"]["time_period"] == rule.threshold_period
+ assert deserialized_body["config"]["sensitivity"] == rule.sensitivity.value
+ assert deserialized_body["config"]["seasonality"] == rule.seasonality.value
+ assert deserialized_body["config"]["direction"] == rule.threshold_type
+ assert deserialized_body["context"]["id"] == rule.id
+ assert deserialized_body["context"]["cur_window"]["value"] == 1
+
+ self.assert_trigger_counts(processor, self.trigger, 0, 0)
+ self.assert_trigger_counts(processor, warning_trigger, 0, 0)
+ self.assert_no_active_incident(rule)
+ self.assert_trigger_exists_with_status(incident, warning_trigger, TriggerStatus.RESOLVED)
+ self.assert_trigger_exists_with_status(incident, trigger, TriggerStatus.RESOLVED)
+ self.assert_actions_resolved_for_incident(
+ incident, [warning_action], [(1, IncidentStatus.CLOSED, mock.ANY)]
+ )
+
+ def test_has_anomaly(self):
+ rule = self.dynamic_rule
+ # test alert ABOVE
+ anomaly1 = {
+ "anomaly": {"anomaly_score": 0.9, "anomaly_type": "anomaly_high"},
+ "timestamp": 1,
+ "value": 10,
+ }
+
+ anomaly2 = {
+ "anomaly": {"anomaly_score": 0.6, "anomaly_type": "anomaly_low"},
+ "timestamp": 1,
+ "value": 10,
+ }
+
+ not_anomaly = {
+ "anomaly": {"anomaly_score": 0.2, "anomaly_type": "none"},
+ "timestamp": 1,
+ "value": 10,
+ }
+
+ warning_trigger = create_alert_rule_trigger(rule, WARNING_TRIGGER_LABEL, 0)
+ warning_label = warning_trigger.label
+
+ label = self.trigger.label
+
+ processor = SubscriptionProcessor(self.sub)
+ assert processor.has_anomaly(anomaly1, label)
+ assert processor.has_anomaly(anomaly1, warning_label)
+ assert not processor.has_anomaly(anomaly2, label)
+ assert processor.has_anomaly(anomaly2, warning_label)
+ assert not processor.has_anomaly(not_anomaly, label)
+ assert not processor.has_anomaly(not_anomaly, warning_label)
+
+ @with_feature("organizations:anomaly-detection-alerts")
+ @mock.patch(
+ "sentry.incidents.subscription_processor.SubscriptionProcessor.seer_anomaly_detection_connection_pool.urlopen"
+ )
+ @mock.patch("sentry.incidents.subscription_processor.logger")
+ def test_seer_call_timeout_error(self, mock_logger, mock_seer_request):
+ rule = self.dynamic_rule
+ processor = SubscriptionProcessor(self.sub)
+ from urllib3.exceptions import TimeoutError
+
+ mock_seer_request.side_effect = TimeoutError
+ result = processor.get_anomaly_data_from_seer(10)
+ timeout_extra = {
+ "subscription_id": self.sub.id,
+ "dataset": self.sub.snuba_query.dataset,
+ "organization_id": self.sub.project.organization.id,
+ "project_id": self.sub.project_id,
+ "alert_rule_id": rule.id,
+ }
+ mock_logger.warning.assert_called_with(
+ "Timeout error when hitting anomaly detection endpoint",
+ extra=timeout_extra,
+ )
+
+ assert result is None
+
+ @with_feature("organizations:anomaly-detection-alerts")
+ @mock.patch(
+ "sentry.incidents.subscription_processor.SubscriptionProcessor.seer_anomaly_detection_connection_pool.urlopen"
+ )
+ @mock.patch("sentry.incidents.subscription_processor.logger")
+ def test_seer_call_empty_list(self, mock_logger, mock_seer_request):
+ processor = SubscriptionProcessor(self.sub)
+ seer_return_value: dict[str, list] = {"anomalies": []}
+ mock_seer_request.return_value = HTTPResponse(orjson.dumps(seer_return_value), status=200)
+ result = processor.get_anomaly_data_from_seer(10)
+ assert mock_logger.warning.call_args[0] == (
+ "Seer anomaly detection response returned no potential anomalies",
+ )
+ assert result is None
+
+ @with_feature("organizations:anomaly-detection-alerts")
+ @mock.patch(
+ "sentry.incidents.subscription_processor.SubscriptionProcessor.seer_anomaly_detection_connection_pool.urlopen"
+ )
+ @mock.patch("sentry.incidents.subscription_processor.logger")
+ def test_seer_call_bad_status(self, mock_logger, mock_seer_request):
+ processor = SubscriptionProcessor(self.sub)
+ mock_seer_request.return_value = HTTPResponse("You flew too close to the sun", status=403)
+ result = processor.get_anomaly_data_from_seer(10)
+ assert mock_logger.error.called_with(
+ f"Received 403 when calling Seer endpoint {SEER_ANOMALY_DETECTION_ENDPOINT_URL}.", # noqa
+ extra={"response_data": "You flew too close to the sun"},
+ )
+ assert result is None
+
+ @with_feature("organizations:anomaly-detection-alerts")
+ @mock.patch(
+ "sentry.incidents.subscription_processor.SubscriptionProcessor.seer_anomaly_detection_connection_pool.urlopen"
+ )
+ @mock.patch("sentry.incidents.subscription_processor.logger")
+ def test_seer_call_failed_parse(self, mock_logger, mock_seer_request):
+ processor = SubscriptionProcessor(self.sub)
+ mock_seer_request.return_value = HTTPResponse(None, status=200) # type: ignore[arg-type]
+ result = processor.get_anomaly_data_from_seer(10)
+ assert mock_logger.exception.called_with("Failed to parse Seer anomaly detection response")
+ assert result is None
+
def test_alert(self):
# Verify that an alert rule that only expects a single update to be over the
# alert threshold triggers correctly
|
a91bb138240bc0be0deefd6a3e380a3f394e424d
|
2019-05-17 20:03:06
|
Mark Story
|
chore: Update picklefield to remove warnings (#13251)
| false
|
Update picklefield to remove warnings (#13251)
|
chore
|
diff --git a/requirements-base.txt b/requirements-base.txt
index 6213cc912eb73b..fbae99ccc6fb00 100644
--- a/requirements-base.txt
+++ b/requirements-base.txt
@@ -9,7 +9,7 @@ croniter>=0.3.26,<0.4.0
cssutils>=0.9.9,<0.10.0
django-crispy-forms>=1.4.0,<1.5.0
django-jsonfield>=0.9.13,<0.9.14
-django-picklefield>=0.3.0,<0.4.0
+django-picklefield>=0.3.0,<1.1.0
django-sudo>=2.1.0,<3.0.0
django-templatetag-sugar>=0.1.0
Django>=1.8,<1.9
|
4f236a8ce26d04cc290a5e7d0a361fae2d547d2b
|
2024-06-18 05:40:31
|
Michelle Zhang
|
ref(replay): use placeholder for loading in tabs (#72909)
| false
|
use placeholder for loading in tabs (#72909)
|
ref
|
diff --git a/static/app/views/replays/detail/layout/index.tsx b/static/app/views/replays/detail/layout/index.tsx
index 495eff8c79c540..063d193acf8457 100644
--- a/static/app/views/replays/detail/layout/index.tsx
+++ b/static/app/views/replays/detail/layout/index.tsx
@@ -2,6 +2,7 @@ import {useRef} from 'react';
import styled from '@emotion/styled';
import ErrorBoundary from 'sentry/components/errorBoundary';
+import Placeholder from 'sentry/components/placeholder';
import ReplayController from 'sentry/components/replays/replayController';
import ReplayView from 'sentry/components/replays/replayView';
import {space} from 'sentry/styles/space';
@@ -69,7 +70,9 @@ function ReplayLayout({
);
}
- const focusArea = (
+ const focusArea = isLoading ? (
+ <Placeholder width="100%" height="100%" />
+ ) : (
<FluidPanel title={<SmallMarginFocusTabs isVideoReplay={isVideoReplay} />}>
<ErrorBoundary mini>
<FocusArea isVideoReplay={isVideoReplay} replayRecord={replayRecord} />
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.