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
⌀ |
|---|---|---|---|---|---|---|---|
ebcf2bf5f6436ab6d28a58d1f878e7824fb9727d
|
2021-03-04 07:36:49
|
NisanthanNanthakumar
|
feat(codeowners): Set CodeOwners APIs behind feature flags (#24201)
| false
|
Set CodeOwners APIs behind feature flags (#24201)
|
feat
|
diff --git a/src/sentry/api/endpoints/external_team.py b/src/sentry/api/endpoints/external_team.py
index 205714ed07c63a..eb1151b2329de6 100644
--- a/src/sentry/api/endpoints/external_team.py
+++ b/src/sentry/api/endpoints/external_team.py
@@ -4,8 +4,10 @@
from rest_framework import serializers, status
from rest_framework.response import Response
-from sentry.api.serializers.rest_framework.base import CamelSnakeModelSerializer
+from rest_framework.exceptions import PermissionDenied
+from sentry import features
+from sentry.api.serializers.rest_framework.base import CamelSnakeModelSerializer
from sentry.api.bases.team import TeamEndpoint
from sentry.api.serializers import serialize
from sentry.models import ExternalTeam, EXTERNAL_PROVIDERS
@@ -25,7 +27,7 @@ class Meta:
def validate_provider(self, provider):
if provider not in EXTERNAL_PROVIDERS.values():
raise serializers.ValidationError(
- f'The provider "{provider}" is not supported. We currently accept Github and Gitlab team identities.'
+ f'The provider "{provider}" is not supported. We currently accept GitHub and GitLab team identities.'
)
return ExternalTeam.get_provider_enum(provider)
@@ -46,7 +48,14 @@ def update(self, instance, validated_data):
)
-class ExternalTeamEndpoint(TeamEndpoint):
+class ExternalTeamMixin:
+ def has_feature(self, request, team):
+ return features.has(
+ "organizations:external-team-associations", team.organization, actor=request.user
+ )
+
+
+class ExternalTeamEndpoint(TeamEndpoint, ExternalTeamMixin):
def post(self, request, team):
"""
Create an External Team
@@ -59,6 +68,9 @@ def post(self, request, team):
:param required string external_name: the associated Github/Gitlab team name.
:auth: required
"""
+ if not self.has_feature(request, team):
+ raise PermissionDenied
+
serializer = ExternalTeamSerializer(data={**request.data, "team_id": team.id})
if serializer.is_valid():
external_team, created = serializer.save()
diff --git a/src/sentry/api/endpoints/external_team_details.py b/src/sentry/api/endpoints/external_team_details.py
index 441b3754ebc9f8..df5b807954ef5a 100644
--- a/src/sentry/api/endpoints/external_team_details.py
+++ b/src/sentry/api/endpoints/external_team_details.py
@@ -3,17 +3,18 @@
from rest_framework import status
from rest_framework.response import Response
+from rest_framework.exceptions import PermissionDenied
from sentry.api.bases.team import TeamEndpoint
from sentry.api.serializers import serialize
from sentry.models import ExternalTeam
-from .external_team import ExternalTeamSerializer
+from .external_team import ExternalTeamSerializer, ExternalTeamMixin
logger = logging.getLogger(__name__)
-class ExternalTeamDetailsEndpoint(TeamEndpoint):
+class ExternalTeamDetailsEndpoint(TeamEndpoint, ExternalTeamMixin):
def convert_args(
self, request, organization_slug, team_slug, external_team_id, *args, **kwargs
):
@@ -40,6 +41,8 @@ def put(self, request, team, external_team):
:param string provider: enum("github","gitlab")
:auth: required
"""
+ if not self.has_feature(request, team):
+ raise PermissionDenied
serializer = ExternalTeamSerializer(
instance=external_team, data={**request.data, "team_id": team.id}, partial=True
@@ -57,6 +60,8 @@ def delete(self, request, team, external_team):
"""
Delete an External Team
"""
+ if not self.has_feature(request, team):
+ raise PermissionDenied
external_team.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/src/sentry/api/endpoints/external_user.py b/src/sentry/api/endpoints/external_user.py
index b5251b563b011d..af7a154ab1de87 100644
--- a/src/sentry/api/endpoints/external_user.py
+++ b/src/sentry/api/endpoints/external_user.py
@@ -4,10 +4,11 @@
from rest_framework import serializers, status
from rest_framework.response import Response
-from sentry.api.serializers.rest_framework.base import CamelSnakeModelSerializer
+from rest_framework.exceptions import PermissionDenied
+from sentry import features
+from sentry.api.serializers.rest_framework.base import CamelSnakeModelSerializer
from sentry.api.bases.organization import OrganizationEndpoint
-
from sentry.api.serializers import serialize
from sentry.models import ExternalUser, EXTERNAL_PROVIDERS, OrganizationMember
@@ -58,7 +59,14 @@ def update(self, instance, validated_data):
)
-class ExternalUserEndpoint(OrganizationEndpoint):
+class ExternalUserMixin:
+ def has_feature(self, request, organization):
+ return features.has(
+ "organizations:external-user-associations", organization, actor=request.user
+ )
+
+
+class ExternalUserEndpoint(OrganizationEndpoint, ExternalUserMixin):
def post(self, request, organization):
"""
Create an External User
@@ -71,6 +79,9 @@ def post(self, request, organization):
:param required int member_id: the organization_member id.
:auth: required
"""
+ if not self.has_feature(request, organization):
+ raise PermissionDenied
+
serializer = ExternalUserSerializer(
context={"organization": organization}, data={**request.data}
)
diff --git a/src/sentry/api/endpoints/external_user_details.py b/src/sentry/api/endpoints/external_user_details.py
index ebbf29a1116309..a446f2375e43cd 100644
--- a/src/sentry/api/endpoints/external_user_details.py
+++ b/src/sentry/api/endpoints/external_user_details.py
@@ -3,17 +3,18 @@
from rest_framework import status
from rest_framework.response import Response
+from rest_framework.exceptions import PermissionDenied
from sentry.api.bases.organization import OrganizationEndpoint
from sentry.api.serializers import serialize
from sentry.models import ExternalUser
-from .external_user import ExternalUserSerializer
+from .external_user import ExternalUserSerializer, ExternalUserMixin
logger = logging.getLogger(__name__)
-class ExternalUserDetailsEndpoint(OrganizationEndpoint):
+class ExternalUserDetailsEndpoint(OrganizationEndpoint, ExternalUserMixin):
def convert_args(self, request, organization_slug, external_user_id, *args, **kwargs):
args, kwargs = super().convert_args(request, organization_slug, *args, **kwargs)
try:
@@ -38,6 +39,8 @@ def put(self, request, organization, external_user):
:param string provider: enum("github","gitlab")
:auth: required
"""
+ if not self.has_feature(request, organization):
+ raise PermissionDenied
serializer = ExternalUserSerializer(
instance=external_user,
@@ -58,6 +61,8 @@ def delete(self, request, organization, external_user):
"""
Delete an External Team
"""
+ if not self.has_feature(request, organization):
+ raise PermissionDenied
external_user.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/src/sentry/api/endpoints/project_codeowners.py b/src/sentry/api/endpoints/project_codeowners.py
index 7534af6e0068d2..01c7a7fa56da1c 100644
--- a/src/sentry/api/endpoints/project_codeowners.py
+++ b/src/sentry/api/endpoints/project_codeowners.py
@@ -4,7 +4,9 @@
from rest_framework import serializers, status
from rest_framework.response import Response
+from rest_framework.exceptions import PermissionDenied
+from sentry import features
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.serializers import serialize
from sentry.models import (
@@ -149,7 +151,12 @@ def update(self, instance, validated_data):
return self.instance
-class ProjectCodeOwnersEndpoint(ProjectEndpoint, ProjectOwnershipMixin):
+class ProjectCodeOwnersMixin:
+ def has_feature(self, request, project):
+ return features.has("projects:import-codeowners", project, actor=request.user)
+
+
+class ProjectCodeOwnersEndpoint(ProjectEndpoint, ProjectOwnershipMixin, ProjectCodeOwnersMixin):
def get(self, request, project):
"""
Retrieve List of CODEOWNERS configurations for a project
@@ -159,6 +166,10 @@ def get(self, request, project):
:auth: required
"""
+
+ if not self.has_feature(request, project):
+ raise PermissionDenied
+
codeowners = list(ProjectCodeOwners.objects.filter(project=project))
return Response(serialize(codeowners, request.user), status.HTTP_200_OK)
@@ -174,6 +185,9 @@ def post(self, request, project):
:param string codeMappingId: id of the RepositoryProjectPathConfig object
:auth: required
"""
+ if not self.has_feature(request, project):
+ raise PermissionDenied
+
serializer = ProjectCodeOwnerSerializer(
context={"ownership": self.get_ownership(project), "project": project},
data={**request.data},
diff --git a/src/sentry/api/endpoints/project_codeowners_details.py b/src/sentry/api/endpoints/project_codeowners_details.py
index 058e175d3fcf74..ba8fffe0e0ee09 100644
--- a/src/sentry/api/endpoints/project_codeowners_details.py
+++ b/src/sentry/api/endpoints/project_codeowners_details.py
@@ -2,19 +2,23 @@
from rest_framework import status
from rest_framework.response import Response
+from rest_framework.exceptions import PermissionDenied
+
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.serializers import serialize
from sentry.models import ProjectCodeOwners
from sentry.api.exceptions import ResourceDoesNotExist
-from .project_codeowners import ProjectCodeOwnerSerializer
+from .project_codeowners import ProjectCodeOwnerSerializer, ProjectCodeOwnersMixin
from sentry.api.endpoints.project_ownership import ProjectOwnershipMixin
logger = logging.getLogger(__name__)
-class ProjectCodeOwnersDetailsEndpoint(ProjectEndpoint, ProjectOwnershipMixin):
+class ProjectCodeOwnersDetailsEndpoint(
+ ProjectEndpoint, ProjectOwnershipMixin, ProjectCodeOwnersMixin
+):
def convert_args(
self, request, organization_slug, project_slug, codeowners_id, *args, **kwargs
):
@@ -42,6 +46,9 @@ def put(self, request, project, codeowners):
:param string codeMappingId: id of the RepositoryProjectPathConfig object
:auth: required
"""
+ if not self.has_feature(request, project):
+ raise PermissionDenied
+
serializer = ProjectCodeOwnerSerializer(
instance=codeowners,
context={"ownership": self.get_ownership(project), "project": project},
@@ -59,6 +66,8 @@ def delete(self, request, project, codeowners):
"""
Delete a CodeOwners
"""
+ if not self.has_feature(request, project):
+ raise PermissionDenied
codeowners.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index eef19fb3c424bf..0eff49a2c0ada7 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -905,6 +905,10 @@ def create_partitioned_queues(name):
"organizations:dashboards-edit": False,
# Enable experimental performance improvements.
"organizations:enterprise-perf": False,
+ # Enable the API to create/update/delete external team associations
+ "organizations:external-team-associations": False,
+ # Enable the API to create/update/delete external user associations
+ "organizations:external-user-associations": False,
# Special feature flag primarily used on the sentry.io SAAS product for
# easily enabling features while in early development.
"organizations:internal-catchall": False,
@@ -982,6 +986,8 @@ def create_partitioned_queues(name):
"projects:discard-groups": False,
# DEPRECATED: pending removal
"projects:dsym": False,
+ # Enable the API to importing CODEOWNERS for a project
+ "projects:import-codeowners": False,
# Enable selection of members, teams or code owners as email targets for issue alerts.
"projects:issue-alerts-targeting": True,
# Enable functionality for attaching minidumps to events and displaying
diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py
index 11feb1b724419e..c348873dbedde5 100644
--- a/src/sentry/features/__init__.py
+++ b/src/sentry/features/__init__.py
@@ -68,6 +68,8 @@
default_manager.add("organizations:event-attachments", OrganizationFeature) # NOQA
default_manager.add("organizations:event-attachments-viewer", OrganizationFeature) # NOQA
default_manager.add("organizations:events", OrganizationFeature) # NOQA
+default_manager.add("organizations:external-team-associations", OrganizationFeature) # NOQA
+default_manager.add("organizations:external-user-associations", OrganizationFeature) # NOQA
default_manager.add("organizations:filters-and-sampling", OrganizationFeature) # NOQA
default_manager.add("organizations:global-views", OrganizationFeature) # NOQA
default_manager.add("organizations:incidents", OrganizationFeature) # NOQA
@@ -123,7 +125,6 @@
default_manager.add("organizations:performance-ops-breakdown", OrganizationFeature) # NOQA
default_manager.add("organizations:performance-tag-explorer", OrganizationFeature) # NOQA
default_manager.add("organizations:team-alerts-ownership", OrganizationFeature) # NOQA
-
# NOTE: Don't add features down here! Add them to their specific group and sort
# them alphabetically! The order features are registered is not important.
@@ -132,6 +133,7 @@
default_manager.add("projects:custom-inbound-filters", ProjectFeature) # NOQA
default_manager.add("projects:data-forwarding", ProjectFeature) # NOQA
default_manager.add("projects:discard-groups", ProjectFeature) # NOQA
+default_manager.add("projects:import-codeowners", ProjectFeature) # NOQA
default_manager.add("projects:issue-alerts-targeting", ProjectFeature) # NOQA
default_manager.add("projects:minidump", ProjectFeature) # NOQA
default_manager.add("projects:rate-limits", ProjectFeature) # NOQA
diff --git a/tests/sentry/api/endpoints/test_external_team.py b/tests/sentry/api/endpoints/test_external_team.py
index a643b4c992e22e..57a7605c5f1ef9 100644
--- a/tests/sentry/api/endpoints/test_external_team.py
+++ b/tests/sentry/api/endpoints/test_external_team.py
@@ -18,7 +18,8 @@ def setUp(self):
def test_basic_post(self):
data = {"externalName": "@getsentry/ecosystem", "provider": "github"}
- response = self.client.post(self.url, data)
+ with self.feature({"organizations:external-team-associations": True}):
+ response = self.client.post(self.url, data)
assert response.status_code == 201, response.content
assert response.data == {
"id": str(response.data["id"]),
@@ -26,19 +27,28 @@ def test_basic_post(self):
**data,
}
+ def test_without_feature_flag(self):
+ data = {"externalName": "@getsentry/ecosystem", "provider": "github"}
+ response = self.client.post(self.url, data)
+ assert response.status_code == 403
+ assert response.data == {"detail": "You do not have permission to perform this action."}
+
def test_missing_provider(self):
- response = self.client.post(self.url, {"externalName": "@getsentry/ecosystem"})
+ with self.feature({"organizations:external-team-associations": True}):
+ response = self.client.post(self.url, {"externalName": "@getsentry/ecosystem"})
assert response.status_code == 400
assert response.data == {"provider": ["This field is required."]}
def test_missing_externalName(self):
- response = self.client.post(self.url, {"provider": "gitlab"})
+ with self.feature({"organizations:external-team-associations": True}):
+ response = self.client.post(self.url, {"provider": "gitlab"})
assert response.status_code == 400
assert response.data == {"externalName": ["This field is required."]}
def test_invalid_provider(self):
data = {"externalName": "@getsentry/ecosystem", "provider": "git"}
- response = self.client.post(self.url, data)
+ with self.feature({"organizations:external-team-associations": True}):
+ response = self.client.post(self.url, data)
assert response.status_code == 400
assert response.data == {"provider": ['"git" is not a valid choice.']}
@@ -52,7 +62,8 @@ def test_create_existing_association(self):
"externalName": self.external_team.external_name,
"provider": ExternalTeam.get_provider_string(self.external_team.provider),
}
- response = self.client.post(self.url, data)
+ with self.feature({"organizations:external-team-associations": True}):
+ response = self.client.post(self.url, data)
assert response.status_code == 200
assert response.data == {
"id": str(self.external_team.id),
diff --git a/tests/sentry/api/endpoints/test_external_team_details.py b/tests/sentry/api/endpoints/test_external_team_details.py
index ec0296b80d3466..11cbfa7bf60f7c 100644
--- a/tests/sentry/api/endpoints/test_external_team_details.py
+++ b/tests/sentry/api/endpoints/test_external_team_details.py
@@ -20,17 +20,20 @@ def setUp(self):
)
def test_basic_delete(self):
- resp = self.client.delete(self.url)
+ with self.feature({"organizations:external-team-associations": True}):
+ resp = self.client.delete(self.url)
assert resp.status_code == 204
assert not ExternalTeam.objects.filter(id=str(self.external_team.id)).exists()
def test_basic_update(self):
- resp = self.client.put(self.url, {"externalName": "@getsentry/growth"})
+ with self.feature({"organizations:external-team-associations": True}):
+ resp = self.client.put(self.url, {"externalName": "@getsentry/growth"})
assert resp.status_code == 200
assert resp.data["id"] == str(self.external_team.id)
assert resp.data["externalName"] == "@getsentry/growth"
def test_invalid_provider_update(self):
- resp = self.client.put(self.url, {"provider": "git"})
+ with self.feature({"organizations:external-team-associations": True}):
+ resp = self.client.put(self.url, {"provider": "git"})
assert resp.status_code == 400
assert resp.data == {"provider": ['"git" is not a valid choice.']}
diff --git a/tests/sentry/api/endpoints/test_external_user.py b/tests/sentry/api/endpoints/test_external_user.py
index ed7764f2c93420..4e2c0df8c8a569 100644
--- a/tests/sentry/api/endpoints/test_external_user.py
+++ b/tests/sentry/api/endpoints/test_external_user.py
@@ -20,7 +20,8 @@ def setUp(self):
}
def test_basic_post(self):
- response = self.client.post(self.url, self.data)
+ with self.feature({"organizations:external-user-associations": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 201, response.content
assert response.data == {
**self.data,
@@ -28,27 +29,36 @@ def test_basic_post(self):
"memberId": str(self.organization_member.id),
}
+ def test_without_feature_flag(self):
+ response = self.client.post(self.url, self.data)
+ assert response.status_code == 403
+ assert response.data == {"detail": "You do not have permission to perform this action."}
+
def test_missing_provider(self):
self.data.pop("provider")
- response = self.client.post(self.url, self.data)
+ with self.feature({"organizations:external-user-associations": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 400
assert response.data == {"provider": ["This field is required."]}
def test_missing_externalName(self):
self.data.pop("externalName")
- response = self.client.post(self.url, self.data)
+ with self.feature({"organizations:external-user-associations": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 400
assert response.data == {"externalName": ["This field is required."]}
def test_missing_memberId(self):
self.data.pop("memberId")
- response = self.client.post(self.url, self.data)
+ with self.feature({"organizations:external-user-associations": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 400
assert response.data == {"memberId": ["This field is required."]}
def test_invalid_provider(self):
self.data.update(provider="unknown")
- response = self.client.post(self.url, self.data)
+ with self.feature({"organizations:external-user-associations": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 400
assert response.data == {"provider": ['"unknown" is not a valid choice.']}
@@ -57,7 +67,8 @@ def test_create_existing_association(self):
self.user, self.organization, external_name=self.data["externalName"]
)
- response = self.client.post(self.url, self.data)
+ with self.feature({"organizations:external-user-associations": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 200
assert response.data == {
**self.data,
diff --git a/tests/sentry/api/endpoints/test_external_user_details.py b/tests/sentry/api/endpoints/test_external_user_details.py
index b7ecfa06089a0c..6518e90fb48a69 100644
--- a/tests/sentry/api/endpoints/test_external_user_details.py
+++ b/tests/sentry/api/endpoints/test_external_user_details.py
@@ -16,17 +16,20 @@ def setUp(self):
)
def test_basic_delete(self):
- resp = self.client.delete(self.url)
+ with self.feature({"organizations:external-user-associations": True}):
+ resp = self.client.delete(self.url)
assert resp.status_code == 204
assert not ExternalUser.objects.filter(id=str(self.external_user.id)).exists()
def test_basic_update(self):
- resp = self.client.put(self.url, {"externalName": "@new_username"})
+ with self.feature({"organizations:external-user-associations": True}):
+ resp = self.client.put(self.url, {"externalName": "@new_username"})
assert resp.status_code == 200
assert resp.data["id"] == str(self.external_user.id)
assert resp.data["externalName"] == "@new_username"
def test_invalid_provider_update(self):
- resp = self.client.put(self.url, {"provider": "unknown"})
+ with self.feature({"organizations:external-user-associations": True}):
+ resp = self.client.put(self.url, {"provider": "unknown"})
assert resp.status_code == 400
assert resp.data == {"provider": ['"unknown" is not a valid choice.']}
diff --git a/tests/sentry/api/endpoints/test_project_codeowners.py b/tests/sentry/api/endpoints/test_project_codeowners.py
index f69cde563eb61f..d82454be230a43 100644
--- a/tests/sentry/api/endpoints/test_project_codeowners.py
+++ b/tests/sentry/api/endpoints/test_project_codeowners.py
@@ -54,13 +54,20 @@ def _create_codeowner_with_integration(self):
)
def test_no_codeowners(self):
- resp = self.client.get(self.url)
+ with self.feature({"projects:import-codeowners": True}):
+ resp = self.client.get(self.url)
assert resp.status_code == 200
assert resp.data == []
+ def test_without_feature_flag(self):
+ resp = self.client.get(self.url)
+ assert resp.status_code == 403
+ assert resp.data == {"detail": "You do not have permission to perform this action."}
+
def test_codeowners_without_integrations(self):
code_owner = self.create_codeowners(self.project, self.code_mapping, raw="*.js @tiger-team")
- resp = self.client.get(self.url)
+ with self.feature({"projects:import-codeowners": True}):
+ resp = self.client.get(self.url)
assert resp.status_code == 200
resp_data = resp.data[0]
assert resp_data["raw"] == code_owner.raw
@@ -71,7 +78,8 @@ def test_codeowners_without_integrations(self):
def test_codeowners_with_integration(self):
self._create_codeowner_with_integration()
- resp = self.client.get(self.url)
+ with self.feature({"projects:import-codeowners": True}):
+ resp = self.client.get(self.url)
assert resp.status_code == 200
resp_data = resp.data[0]
assert resp_data["raw"] == self.code_owner.raw
@@ -81,8 +89,8 @@ def test_codeowners_with_integration(self):
assert resp_data["provider"] == self.integration.provider
def test_basic_post(self):
-
- response = self.client.post(self.url, self.data)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 201, response.content
assert response.data["id"]
assert {
@@ -93,19 +101,22 @@ def test_basic_post(self):
def test_empty_codeowners_text(self):
self.data["raw"] = ""
- response = self.client.post(self.url, self.data)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 400
assert response.data == {"raw": ["This field may not be blank."]}
def test_invalid_codeowners_text(self):
self.data["raw"] = "docs/*"
- response = self.client.post(self.url, self.data)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 400
assert response.data == {"raw": ["Parse error: 'ownership' (line 1, column 1)"]}
def test_cannot_find_external_user_name_association(self):
self.data["raw"] = "docs/* @MeredithAnya "
- response = self.client.post(self.url, self.data)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 400
assert response.data == {
"raw": ["The following usernames do not have an association in Sentry: @MeredithAnya."]
@@ -113,7 +124,8 @@ def test_cannot_find_external_user_name_association(self):
def test_cannot_find_sentry_user_with_email(self):
self.data["raw"] = "docs/* [email protected]"
- response = self.client.post(self.url, self.data)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 400
assert response.data == {
"raw": [
@@ -123,7 +135,8 @@ def test_cannot_find_sentry_user_with_email(self):
def test_cannot_find_external_team_name_association(self):
self.data["raw"] = "docs/* @getsentry/frontend"
- response = self.client.post(self.url, self.data)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 400
assert response.data == {
"raw": [
@@ -133,7 +146,8 @@ def test_cannot_find_external_team_name_association(self):
def test_cannot_find__multiple_external_name_association(self):
self.data["raw"] = "docs/* @AnotherUser @getsentry/frontend @getsentry/docs"
- response = self.client.post(self.url, self.data)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 400
assert response.data == {
"raw": [
@@ -143,24 +157,28 @@ def test_cannot_find__multiple_external_name_association(self):
def test_missing_code_mapping_id(self):
self.data.pop("codeMappingId")
- response = self.client.post(self.url, self.data)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 400
assert response.data == {"codeMappingId": ["This field is required."]}
def test_invalid_code_mapping_id(self):
self.data["codeMappingId"] = 500
- response = self.client.post(self.url, self.data)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 400
assert response.data == {"codeMappingId": ["This code mapping does not exist."]}
def test_default_project_ownership_record_created(self):
assert ProjectOwnership.objects.filter(project=self.project).exists() is False
- response = self.client.post(self.url, self.data)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 201, response.content
assert ProjectOwnership.objects.filter(project=self.project).exists() is True
def test_schema_is_correct(self):
- response = self.client.post(self.url, self.data)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 201, response.content
assert response.data["id"]
project_codeowners = ProjectCodeOwners.objects.get(id=response.data["id"])
@@ -179,7 +197,8 @@ def test_schema_is_correct(self):
def test_schema_preserves_comments(self):
self.data["raw"] = "docs/* @NisanthanNanthakumar @getsentry/ecosystem\n"
- response = self.client.post(self.url, self.data)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 201, response.content
assert response.data["id"]
project_codeowners = ProjectCodeOwners.objects.get(id=response.data["id"])
@@ -198,7 +217,8 @@ def test_schema_preserves_comments(self):
def test_raw_email_correct_schema(self):
self.data["raw"] = f"docs/* {self.user.email} @getsentry/ecosystem\n"
- response = self.client.post(self.url, self.data)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.post(self.url, self.data)
assert response.status_code == 201, response.content
assert response.data["id"]
project_codeowners = ProjectCodeOwners.objects.get(id=response.data["id"])
diff --git a/tests/sentry/api/endpoints/test_project_codeowners_details.py b/tests/sentry/api/endpoints/test_project_codeowners_details.py
index 59161996c9326a..076af330ef314c 100644
--- a/tests/sentry/api/endpoints/test_project_codeowners_details.py
+++ b/tests/sentry/api/endpoints/test_project_codeowners_details.py
@@ -36,7 +36,8 @@ def setUp(self):
)
def test_basic_delete(self):
- response = self.client.delete(self.url)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.delete(self.url)
assert response.status_code == 204
assert not ProjectCodeOwners.objects.filter(id=str(self.codeowners.id)).exists()
@@ -46,7 +47,8 @@ def test_basic_update(self):
data = {
"raw": "\n# cool stuff comment\n*.js @getsentry/frontend @NisanthanNanthakumar\n# good comment\n\n\n docs/* @getsentry/docs @getsentry/ecosystem\n\n"
}
- response = self.client.put(self.url, data)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.put(self.url, data)
assert response.status_code == 200
assert response.data["id"] == str(self.codeowners.id)
assert response.data["raw"] == data["raw"].strip()
@@ -60,8 +62,8 @@ def test_wrong_codeowners_id(self):
"codeowners_id": 1000,
},
)
-
- response = self.client.put(self.url, self.data)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.put(self.url, self.data)
assert response.status_code == 404
assert response.data == {"detail": "The requested resource does not exist"}
@@ -69,7 +71,8 @@ def test_missing_external_associations_update(self):
data = {
"raw": "\n# cool stuff comment\n*.js @getsentry/frontend @NisanthanNanthakumar\n# good comment\n\n\n docs/* @getsentry/docs @getsentry/ecosystem\nsrc/sentry/* @AnotherUser\n\n"
}
- response = self.client.put(self.url, data)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.put(self.url, data)
assert response.status_code == 400
assert response.data == {
"raw": [
@@ -78,12 +81,14 @@ def test_missing_external_associations_update(self):
}
def test_invalid_code_mapping_id_update(self):
- response = self.client.put(self.url, {"codeMappingId": 500})
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.put(self.url, {"codeMappingId": 500})
assert response.status_code == 400
assert response.data == {"codeMappingId": ["This code mapping does not exist."]}
def test_codeowners_email_update(self):
data = {"raw": f"\n# cool stuff comment\n*.js {self.user.email}\n# good comment\n\n\n"}
- response = self.client.put(self.url, data)
+ with self.feature({"projects:import-codeowners": True}):
+ response = self.client.put(self.url, data)
assert response.status_code == 200
assert response.data["raw"] == "# cool stuff comment\n*.js [email protected]\n# good comment"
|
b0495fb2af4cb8ba24a5eb66cf0e8879e4e066ff
|
2019-11-21 00:39:06
|
Lyn Nagara
|
test: Use store_event instead of crete_event (#15661)
| false
|
Use store_event instead of crete_event (#15661)
|
test
|
diff --git a/tests/sentry/api/serializers/test_event.py b/tests/sentry/api/serializers/test_event.py
index aa5c7abd102cdf..48e8432fd55d71 100644
--- a/tests/sentry/api/serializers/test_event.py
+++ b/tests/sentry/api/serializers/test_event.py
@@ -24,29 +24,37 @@ def test_simple(self):
assert result["eventID"] == event_id
def test_eventerror(self):
- event = self.create_event(
- data={"errors": [{"type": EventError.INVALID_DATA, "name": u"ü"}]}
+ event = self.store_event(
+ data={
+ "event_id": "a" * 32,
+ "timestamp": iso_format(before_now(minutes=1)),
+ "stacktrace": [u"ü"],
+ },
+ project_id=self.project.id,
+ assert_no_errors=False,
)
result = serialize(event)
assert len(result["errors"]) == 1
assert "data" in result["errors"][0]
assert result["errors"][0]["type"] == EventError.INVALID_DATA
- assert result["errors"][0]["data"] == {"name": u"ü"}
+ assert result["errors"][0]["data"] == {
+ u"name": u"stacktrace",
+ u"reason": u"expected rawstacktrace",
+ u"value": [u"\xfc"],
+ }
assert "startTimestamp" not in result
assert "timestamp" not in result
def test_hidden_eventerror(self):
- event = self.create_event(
+ event = self.store_event(
data={
- "errors": [
- {"type": EventError.INVALID_DATA, "name": u"breadcrumbs.values.42.data"},
- {
- "type": EventError.INVALID_DATA,
- "name": u"exception.values.0.stacktrace.frames.42.vars",
- },
- ]
- }
+ "event_id": "a" * 32,
+ "timestamp": iso_format(before_now(minutes=1)),
+ "breadcrumbs": [u"ü"],
+ },
+ project_id=self.project.id,
+ assert_no_errors=False,
)
result = serialize(event)
@@ -54,15 +62,19 @@ def test_hidden_eventerror(self):
def test_renamed_attributes(self):
# Only includes meta for simple top-level attributes
- event = self.create_event(
+ event = self.store_event(
data={
+ "event_id": "a" * 32,
+ "timestamp": iso_format(before_now(minutes=1)),
"extra": {"extra": True},
"modules": {"modules": "foobar"},
"_meta": {
"extra": {"": {"err": ["extra error"]}},
"modules": {"": {"err": ["modules error"]}},
},
- }
+ },
+ project_id=self.project.id,
+ assert_no_errors=False,
)
result = serialize(event)
@@ -72,11 +84,15 @@ def test_renamed_attributes(self):
assert result["_meta"]["packages"] == {"": {"err": ["modules error"]}}
def test_message_interface(self):
- event = self.create_event(
+ event = self.store_event(
data={
+ "event_id": "a" * 32,
+ "timestamp": iso_format(before_now(minutes=1)),
"logentry": {"formatted": "bar"},
"_meta": {"logentry": {"formatted": {"": {"err": ["some error"]}}}},
- }
+ },
+ project_id=self.project.id,
+ assert_no_errors=False,
)
result = serialize(event)
@@ -84,11 +100,15 @@ def test_message_interface(self):
assert result["_meta"]["message"] == {"": {"err": ["some error"]}}
def test_message_formatted(self):
- event = self.create_event(
+ event = self.store_event(
data={
- "logentry": {"message": "bar", "formatted": "baz"},
+ "event_id": "a" * 32,
+ "timestamp": iso_format(before_now(minutes=1)),
+ "logentry": {"formatted": "baz"},
"_meta": {"logentry": {"formatted": {"": {"err": ["some error"]}}}},
- }
+ },
+ project_id=self.project.id,
+ assert_no_errors=False,
)
result = serialize(event)
@@ -96,15 +116,26 @@ def test_message_formatted(self):
assert result["_meta"]["message"] == {"": {"err": ["some error"]}}
def test_message_legacy(self):
- event = self.create_event(data={"logentry": None})
+ event = self.store_event(
+ data={
+ "event_id": "a" * 32,
+ "timestamp": iso_format(before_now(minutes=1)),
+ "logentry": {"formatted": None},
+ },
+ project_id=self.project.id,
+ assert_no_errors=False,
+ )
+
event.message = "search message"
result = serialize(event)
assert result["message"] == "search message"
def test_tags_tuples(self):
- event = self.create_event(
+ event = self.store_event(
data={
+ "event_id": "a" * 32,
+ "timestamp": iso_format(before_now(minutes=1)),
"tags": [["foo", "foo"], ["bar", "bar"]],
"_meta": {
"tags": {
@@ -112,7 +143,9 @@ def test_tags_tuples(self):
"1": {"1": {"": {"err": ["bar error"]}}},
}
},
- }
+ },
+ project_id=self.project.id,
+ assert_no_errors=False,
)
result = serialize(event)
@@ -122,9 +155,10 @@ def test_tags_tuples(self):
assert result["_meta"]["tags"]["1"]["value"] == {"": {"err": ["foo error"]}}
def test_tags_dict(self):
- event = self.create_event(
+ event = self.store_event(
data={
- # Sentry normalizes this internally
+ "event_id": "a" * 32,
+ "timestamp": iso_format(before_now(minutes=1)),
"tags": {"foo": "foo", "bar": "bar"},
"_meta": {
"tags": {
@@ -132,7 +166,9 @@ def test_tags_dict(self):
"bar": {"": {"err": ["bar error"]}},
}
},
- }
+ },
+ project_id=self.project.id,
+ assert_no_errors=False,
)
result = serialize(event)
@@ -142,8 +178,10 @@ def test_tags_dict(self):
assert result["_meta"]["tags"]["1"]["value"] == {"": {"err": ["foo error"]}}
def test_none_interfaces(self):
- event = self.create_event(
+ event = self.store_event(
data={
+ "event_id": "a" * 32,
+ "timestamp": iso_format(before_now(minutes=1)),
"breadcrumbs": None,
"exception": None,
"logentry": None,
@@ -152,7 +190,8 @@ def test_none_interfaces(self):
"contexts": None,
"sdk": None,
"_meta": None,
- }
+ },
+ project_id=self.project.id,
)
result = serialize(event)
@@ -187,11 +226,14 @@ def test_transaction_event_empty_spans(self):
class SharedEventSerializerTest(TestCase):
def test_simple(self):
- event = self.create_event(event_id="a")
+ event = self.store_event(
+ data={"event_id": "a" * 32, "timestamp": iso_format(before_now(minutes=1))},
+ project_id=self.project.id,
+ )
result = serialize(event, None, SharedEventSerializer())
- assert result["id"] == six.text_type(event.event_id)
- assert result["eventID"] == "a"
+ assert result["id"] == "a" * 32
+ assert result["eventID"] == "a" * 32
assert result.get("context") is None
assert result.get("contexts") is None
assert result.get("user") is None
diff --git a/tests/snuba/models/test_event.py b/tests/snuba/models/test_event.py
index 9021d420c9a565..6f1b588ec2adad 100644
--- a/tests/snuba/models/test_event.py
+++ b/tests/snuba/models/test_event.py
@@ -1,12 +1,12 @@
from __future__ import absolute_import
-import calendar
from datetime import datetime, timedelta
from sentry.api.serializers import serialize
from sentry.models.event import Event, SnubaEvent
from sentry.testutils import SnubaTestCase, TestCase
from sentry import eventstore, nodestore
+from sentry.testutils.helpers.datetime import iso_format, before_now
class SnubaEventTest(TestCase, SnubaTestCase):
@@ -17,19 +17,13 @@ def setUp(self):
self.now = datetime.utcnow().replace(microsecond=0) - timedelta(seconds=10)
self.proj1 = self.create_project()
self.proj1env1 = self.create_environment(project=self.proj1, name="test")
- self.proj1group1 = self.create_group(
- self.proj1, first_seen=self.now, last_seen=self.now + timedelta(seconds=14400)
- )
# Raw event data
self.data = {
"event_id": self.event_id,
- "primary_hash": "1" * 32,
- "project_id": self.proj1.id,
"message": "message 1",
"platform": "python",
- "timestamp": calendar.timegm(self.now.timetuple()),
- "received": calendar.timegm(self.now.timetuple()),
+ "timestamp": iso_format(before_now(minutes=1)),
"tags": {
"foo": "bar",
"baz": "quux",
@@ -40,26 +34,8 @@ def setUp(self):
"user": {"id": u"user1", "email": u"[email protected]"},
}
- # Create a regular django Event from the data, which will save the.
- # data in nodestore too. Once Postgres events are deprecated, we can
- # turn this off and just put the payload in nodestore.
- make_django_event = True
- if make_django_event:
- self.create_event(
- event_id=self.data["event_id"],
- datetime=self.now,
- project=self.proj1,
- group=self.proj1group1,
- data=self.data,
- )
- nodestore_data = nodestore.get(
- SnubaEvent.generate_node_id(self.proj1.id, self.event_id)
- )
- assert self.data["event_id"] == nodestore_data["event_id"]
- else:
- node_id = SnubaEvent.generate_node_id(self.proj1.id, self.event_id)
- nodestore.set(node_id, self.data)
- assert nodestore.get(node_id) == self.data
+ event1 = self.store_event(data=self.data, project_id=self.proj1.id)
+ self.proj1group1 = event1.group
def test_fetch(self):
event = eventstore.get_event_by_id(self.proj1.id, self.event_id)
@@ -119,7 +95,9 @@ def test_event_with_no_body(self):
# Check that the regular serializer still gives us back tags
assert serialized["tags"] == [
{"_meta": None, "key": "baz", "value": "quux"},
+ {"_meta": None, "key": "environment", "value": "prod"},
{"_meta": None, "key": "foo", "value": "bar"},
+ {"_meta": None, "key": "level", "value": "error"},
{"_meta": None, "key": "release", "value": "release1"},
{"_meta": None, "key": "user", "query": "user.id:user1", "value": "id:user1"},
]
|
e3cba3810598baf2292a4f0d3cda32af8b56304e
|
2024-01-26 02:14:29
|
Scott Cooper
|
feat(releases): Convert release files changed to fc (#63683)
| false
|
Convert release files changed to fc (#63683)
|
feat
|
diff --git a/static/app/views/releases/detail/commitsAndFiles/commits.tsx b/static/app/views/releases/detail/commitsAndFiles/commits.tsx
index 4a1e1d86111914..2ba21198278a65 100644
--- a/static/app/views/releases/detail/commitsAndFiles/commits.tsx
+++ b/static/app/views/releases/detail/commitsAndFiles/commits.tsx
@@ -129,7 +129,7 @@ class Commits extends DeprecatedAsyncView<Props, State> {
}
renderBody() {
- const {location, router, activeReleaseRepo, releaseRepos} = this.props;
+ const {activeReleaseRepo, releaseRepos} = this.props;
return (
<Fragment>
@@ -137,8 +137,6 @@ class Commits extends DeprecatedAsyncView<Props, State> {
<RepositorySwitcher
repositories={releaseRepos}
activeRepository={activeReleaseRepo}
- location={location}
- router={router}
/>
)}
{this.renderContent()}
diff --git a/static/app/views/releases/detail/commitsAndFiles/filesChanged.spec.tsx b/static/app/views/releases/detail/commitsAndFiles/filesChanged.spec.tsx
new file mode 100644
index 00000000000000..b48b761d65c5c5
--- /dev/null
+++ b/static/app/views/releases/detail/commitsAndFiles/filesChanged.spec.tsx
@@ -0,0 +1,142 @@
+import selectEvent from 'react-select-event';
+import {CommitAuthorFixture} from 'sentry-fixture/commitAuthor';
+import {ReleaseFixture} from 'sentry-fixture/release';
+import {ReleaseProjectFixture} from 'sentry-fixture/releaseProject';
+import {RepositoryFixture} from 'sentry-fixture/repository';
+
+import {initializeOrg} from 'sentry-test/initializeOrg';
+import {render, screen} from 'sentry-test/reactTestingLibrary';
+
+import RepositoryStore from 'sentry/stores/repositoryStore';
+import type {CommitFile, ReleaseProject} from 'sentry/types';
+import {ReleaseContext} from 'sentry/views/releases/detail';
+
+import FilesChanged from './filesChanged';
+
+function CommitFileFixture(params: Partial<CommitFile> = {}): CommitFile {
+ return {
+ id: '111222',
+ orgId: 1,
+ author: CommitAuthorFixture(),
+ commitMessage: 'feat(issues): Add alert (#1337)',
+ filename: 'static/app/components/alert.tsx',
+ type: 'M',
+ repoName: 'getsentry/sentry',
+ ...params,
+ };
+}
+
+describe('FilesChanged', () => {
+ const release = ReleaseFixture();
+ const project = ReleaseProjectFixture() as Required<ReleaseProject>;
+ const {routerProps, routerContext, organization} = initializeOrg({
+ router: {params: {release: release.version}},
+ });
+ const repos = [RepositoryFixture({integrationId: '1'})];
+
+ function renderComponent() {
+ return render(
+ <ReleaseContext.Provider
+ value={{
+ release,
+ project,
+ deploys: [],
+ refetchData: () => {},
+ hasHealthData: false,
+ releaseBounds: {} as any,
+ releaseMeta: {} as any,
+ }}
+ >
+ <FilesChanged
+ releaseRepos={[]}
+ orgSlug={organization.slug}
+ projectSlug={project.slug}
+ {...routerProps}
+ />
+ </ReleaseContext.Provider>,
+ {context: routerContext}
+ );
+ }
+
+ beforeEach(() => {
+ MockApiClient.clearMockResponses();
+ MockApiClient.addMockResponse({
+ url: `/organizations/${organization.slug}/repos/`,
+ body: repos,
+ });
+ RepositoryStore.init();
+ });
+
+ it('should render no repositories message', async () => {
+ MockApiClient.addMockResponse({
+ url: `/organizations/${organization.slug}/repos/`,
+ body: [],
+ });
+ renderComponent();
+ expect(
+ await screen.findByText('Releases are better with commit data!')
+ ).toBeInTheDocument();
+ });
+
+ it('should render no files changed', async () => {
+ MockApiClient.addMockResponse({
+ url: `/projects/${organization.slug}/${project.slug}/releases/${encodeURIComponent(
+ release.version
+ )}/repositories/`,
+ body: repos,
+ });
+ MockApiClient.addMockResponse({
+ url: `/organizations/org-slug/releases/${encodeURIComponent(
+ release.version
+ )}/commitfiles/`,
+ body: [],
+ });
+ renderComponent();
+ expect(await screen.findByText(/There are no changed files/)).toBeInTheDocument();
+ });
+
+ it('should render list of files changed', async () => {
+ MockApiClient.addMockResponse({
+ url: `/projects/${organization.slug}/${project.slug}/releases/${encodeURIComponent(
+ release.version
+ )}/repositories/`,
+ body: repos,
+ });
+ MockApiClient.addMockResponse({
+ url: `/organizations/org-slug/releases/${encodeURIComponent(
+ release.version
+ )}/commitfiles/`,
+ body: [CommitFileFixture()],
+ });
+ renderComponent();
+ expect(await screen.findByText('1 file changed')).toBeInTheDocument();
+ expect(screen.getByText('static/app/components/alert.tsx')).toBeInTheDocument();
+ });
+
+ it('should render repo picker', async () => {
+ MockApiClient.addMockResponse({
+ url: `/projects/${organization.slug}/${project.slug}/releases/${encodeURIComponent(
+ release.version
+ )}/repositories/`,
+ body: [
+ repos[0]!,
+ RepositoryFixture({
+ id: '5',
+ name: 'getsentry/sentry-frontend',
+ integrationId: '1',
+ }),
+ ],
+ });
+ MockApiClient.addMockResponse({
+ url: `/organizations/org-slug/releases/${encodeURIComponent(
+ release.version
+ )}/commitfiles/`,
+ body: [CommitFileFixture()],
+ });
+ renderComponent();
+ expect(await screen.findByRole('button')).toHaveTextContent('example/repo-name');
+ expect(screen.queryByText('getsentry/sentry-frontend')).not.toBeInTheDocument();
+ selectEvent.openMenu(screen.getByRole('button'));
+ expect(screen.getByText('getsentry/sentry-frontend')).toBeInTheDocument();
+ });
+});
diff --git a/static/app/views/releases/detail/commitsAndFiles/filesChanged.tsx b/static/app/views/releases/detail/commitsAndFiles/filesChanged.tsx
index f7061a92c5c88c..10c0022c11d9ff 100644
--- a/static/app/views/releases/detail/commitsAndFiles/filesChanged.tsx
+++ b/static/app/views/releases/detail/commitsAndFiles/filesChanged.tsx
@@ -1,18 +1,22 @@
import {Fragment} from 'react';
-import {RouteComponentProps} from 'react-router';
-import {Location} from 'history';
+import type {RouteComponentProps} from 'react-router';
import * as Layout from 'sentry/components/layouts/thirds';
+import LoadingError from 'sentry/components/loadingError';
import LoadingIndicator from 'sentry/components/loadingIndicator';
import Pagination from 'sentry/components/pagination';
import Panel from 'sentry/components/panels/panel';
import PanelBody from 'sentry/components/panels/panelBody';
import PanelHeader from 'sentry/components/panels/panelHeader';
+import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
import {t, tn} from 'sentry/locale';
import {CommitFile, Organization, Project, Repository} from 'sentry/types';
import {formatVersion} from 'sentry/utils/formatters';
+import {useApiQuery} from 'sentry/utils/queryClient';
import routeTitleGen from 'sentry/utils/routeTitle';
-import DeprecatedAsyncView from 'sentry/views/deprecatedAsyncView';
+import {useLocation} from 'sentry/utils/useLocation';
+import useOrganization from 'sentry/utils/useOrganization';
+import {useParams} from 'sentry/utils/useParams';
import {getFilesByRepository, getQuery, getReposToRender} from '../utils';
@@ -21,144 +25,106 @@ import FileChange from './fileChange';
import RepositorySwitcher from './repositorySwitcher';
import withReleaseRepos from './withReleaseRepos';
-type Props = RouteComponentProps<{release: string}, {}> & {
- location: Location;
+// TODO(scttcper): Some props are no longer used, but required because of the HoC
+interface FilesChangedProps extends RouteComponentProps<{release: string}, {}> {
orgSlug: Organization['slug'];
projectSlug: Project['slug'];
- release: string;
releaseRepos: Repository[];
activeReleaseRepo?: Repository;
-} & DeprecatedAsyncView['props'];
-
-type State = {
- fileList: CommitFile[];
-} & DeprecatedAsyncView['state'];
-
-class FilesChanged extends DeprecatedAsyncView<Props, State> {
- getTitle() {
- const {params, orgSlug, projectSlug} = this.props;
-
- return routeTitleGen(
- t('Files Changed - Release %s', formatVersion(params.release)),
- orgSlug,
- false,
- projectSlug
- );
- }
-
- getDefaultState(): State {
- return {
- ...super.getDefaultState(),
- fileList: [],
- };
- }
-
- componentDidUpdate(prevProps: Props, prevState: State) {
- if (prevProps.activeReleaseRepo?.name !== this.props.activeReleaseRepo?.name) {
- this.remountComponent();
- return;
- }
- super.componentDidUpdate(prevProps, prevState);
- }
-
- getEndpoints(): ReturnType<DeprecatedAsyncView['getEndpoints']> {
- const {activeReleaseRepo: activeRepository, location, release, orgSlug} = this.props;
-
- const query = getQuery({location, activeRepository});
-
- return [
- [
- 'fileList',
- `/organizations/${orgSlug}/releases/${encodeURIComponent(release)}/commitfiles/`,
- {query},
- ],
- ];
- }
-
- renderLoading() {
- return this.renderBody();
- }
-
- renderContent() {
- const {fileList, fileListPageLinks, loading} = this.state;
- const {activeReleaseRepo} = this.props;
-
- if (loading) {
- return <LoadingIndicator />;
- }
+}
- if (!fileList.length) {
- return (
- <EmptyState>
- {!activeReleaseRepo
- ? t('There are no changed files associated with this release.')
- : t(
- 'There are no changed files associated with this release in the %s repository.',
- activeReleaseRepo.name
- )}
- </EmptyState>
- );
+function FilesChanged({activeReleaseRepo, releaseRepos, projectSlug}: FilesChangedProps) {
+ const location = useLocation();
+ const params = useParams<{release: string}>();
+ const organization = useOrganization();
+
+ const query = getQuery({location, activeRepository: activeReleaseRepo});
+ const {
+ data: fileList = [],
+ isLoading: isLoadingFileList,
+ error: fileListError,
+ refetch,
+ getResponseHeader,
+ } = useApiQuery<CommitFile[]>(
+ [
+ `/organizations/${organization.slug}/releases/${encodeURIComponent(
+ params.release
+ )}/commitfiles/`,
+ {query},
+ ],
+ {
+ staleTime: Infinity,
}
-
- const filesByRepository = getFilesByRepository(fileList);
- const reposToRender = getReposToRender(Object.keys(filesByRepository));
-
- return (
- <Fragment>
- {reposToRender.map(repoName => {
- const repoData = filesByRepository[repoName];
- const files = Object.keys(repoData);
- const fileCount = files.length;
- return (
- <Panel key={repoName}>
- <PanelHeader>
- <span>{repoName}</span>
- <span>{tn('%s file changed', '%s files changed', fileCount)}</span>
- </PanelHeader>
- <PanelBody>
- {files.map(filename => {
- const {authors} = repoData[filename];
- return (
- <FileChange
- key={filename}
- filename={filename}
- authors={Object.values(authors)}
- />
- );
- })}
- </PanelBody>
- </Panel>
- );
- })}
- <Pagination pageLinks={fileListPageLinks} />
- </Fragment>
- );
- }
-
- renderBody() {
- const {activeReleaseRepo, releaseRepos, router, location} = this.props;
- return (
- <Fragment>
- {releaseRepos.length > 1 && (
- <RepositorySwitcher
- repositories={releaseRepos}
- activeRepository={activeReleaseRepo}
- location={location}
- router={router}
- />
+ );
+
+ const filesByRepository = getFilesByRepository(fileList);
+ const reposToRender = getReposToRender(Object.keys(filesByRepository));
+ const fileListPageLinks = getResponseHeader?.('Link');
+
+ return (
+ <Fragment>
+ <SentryDocumentTitle
+ title={routeTitleGen(
+ t('Files Changed - Release %s', formatVersion(params.release)),
+ organization.slug,
+ false,
+ projectSlug
)}
- {this.renderContent()}
- </Fragment>
- );
- }
-
- renderComponent() {
- return (
+ />
<Layout.Body>
- <Layout.Main fullWidth>{super.renderComponent()}</Layout.Main>
+ <Layout.Main fullWidth>
+ {releaseRepos.length > 1 && (
+ <RepositorySwitcher
+ repositories={releaseRepos}
+ activeRepository={activeReleaseRepo}
+ />
+ )}
+ {fileListError && <LoadingError onRetry={refetch} />}
+ {isLoadingFileList ? (
+ <LoadingIndicator />
+ ) : fileList.length ? (
+ <Fragment>
+ {reposToRender.map(repoName => {
+ const repoData = filesByRepository[repoName];
+ const files = Object.keys(repoData);
+ const fileCount = files.length;
+ return (
+ <Panel key={repoName}>
+ <PanelHeader>
+ <span>{repoName}</span>
+ <span>{tn('%s file changed', '%s files changed', fileCount)}</span>
+ </PanelHeader>
+ <PanelBody>
+ {files.map(filename => {
+ const {authors} = repoData[filename];
+ return (
+ <FileChange
+ key={filename}
+ filename={filename}
+ authors={Object.values(authors)}
+ />
+ );
+ })}
+ </PanelBody>
+ </Panel>
+ );
+ })}
+ <Pagination pageLinks={fileListPageLinks} />
+ </Fragment>
+ ) : (
+ <EmptyState>
+ {activeReleaseRepo
+ ? t(
+ 'There are no changed files associated with this release in the %s repository.',
+ activeReleaseRepo.name
+ )
+ : t('There are no changed files associated with this release.')}
+ </EmptyState>
+ )}
+ </Layout.Main>
</Layout.Body>
- );
- }
+ </Fragment>
+ );
}
export default withReleaseRepos(FilesChanged);
diff --git a/static/app/views/releases/detail/commitsAndFiles/repositorySwitcher.tsx b/static/app/views/releases/detail/commitsAndFiles/repositorySwitcher.tsx
index 5a793c7a7ad209..67b7d7d761ee35 100644
--- a/static/app/views/releases/detail/commitsAndFiles/repositorySwitcher.tsx
+++ b/static/app/views/releases/detail/commitsAndFiles/repositorySwitcher.tsx
@@ -1,49 +1,43 @@
-import {PureComponent} from 'react';
-import {InjectedRouter} from 'react-router';
import styled from '@emotion/styled';
-import {Location} from 'history';
import {CompactSelect} from 'sentry/components/compactSelect';
import {t} from 'sentry/locale';
import {space} from 'sentry/styles/space';
import {Repository} from 'sentry/types';
+import {useLocation} from 'sentry/utils/useLocation';
+import useRouter from 'sentry/utils/useRouter';
-type Props = {
- location: Location;
- repositories: Array<Repository>;
- router: InjectedRouter;
+interface RepositorySwitcherProps {
+ repositories: Repository[];
activeRepository?: Repository;
-};
+}
-class RepositorySwitcher extends PureComponent<Props> {
- handleRepoFilterChange = (activeRepo: string) => {
- const {router, location} = this.props;
+function RepositorySwitcher({repositories, activeRepository}: RepositorySwitcherProps) {
+ const router = useRouter();
+ const location = useLocation();
+ const handleRepoFilterChange = (activeRepo: string) => {
router.push({
...location,
query: {...location.query, cursor: undefined, activeRepo},
});
};
- render() {
- const {activeRepository, repositories} = this.props;
-
- const activeRepo = activeRepository?.name;
-
- return (
- <StyledCompactSelect
- triggerLabel={activeRepo}
- triggerProps={{prefix: t('Filter')}}
- value={activeRepo}
- options={repositories.map(repo => ({
- value: repo.name,
- textValue: repo.name,
- label: <RepoLabel>{repo.name}</RepoLabel>,
- }))}
- onChange={opt => this.handleRepoFilterChange(String(opt?.value))}
- />
- );
- }
+ const activeRepo = activeRepository?.name;
+
+ return (
+ <StyledCompactSelect
+ triggerLabel={activeRepo}
+ triggerProps={{prefix: t('Filter')}}
+ value={activeRepo}
+ options={repositories.map(repo => ({
+ value: repo.name,
+ textValue: repo.name,
+ label: <RepoLabel>{repo.name}</RepoLabel>,
+ }))}
+ onChange={opt => handleRepoFilterChange(String(opt?.value))}
+ />
+ );
}
export default RepositorySwitcher;
|
343f3c0dc0cccaa47129016bd3a60385adf6b1cf
|
2024-05-04 00:27:42
|
colin-sentry
|
fix(ai-monitoring): Add ai.pipeline op to aggregate measurements (#70267)
| false
|
Add ai.pipeline op to aggregate measurements (#70267)
|
fix
|
diff --git a/static/app/views/performance/newTraceDetails/traceDrawer/details/span/sections/keys.tsx b/static/app/views/performance/newTraceDetails/traceDrawer/details/span/sections/keys.tsx
index 4e9a201b3c2a31..54aa5f5d34eb76 100644
--- a/static/app/views/performance/newTraceDetails/traceDrawer/details/span/sections/keys.tsx
+++ b/static/app/views/performance/newTraceDetails/traceDrawer/details/span/sections/keys.tsx
@@ -73,7 +73,7 @@ export function SpanKeys({node}: {node: TraceTreeNode<TraceTree.Span>}) {
const items: SectionCardKeyValueList = [];
const aggregateMeasurements: SectionCardKeyValueList = useMemo(() => {
- if (!node.value.op?.startsWith('ai.pipeline.')) {
+ if (!/^ai\.pipeline($|\.)/.test(node.value.op ?? '')) {
return [];
}
|
fcca448e499156d68806933817d015a1fa7053fd
|
2024-07-02 21:59:50
|
Richard Roggenkemper
|
feat(empty-states): Add python and javascript (#73606)
| false
|
Add python and javascript (#73606)
|
feat
|
diff --git a/static/app/views/issueList/noGroupsHandler/index.tsx b/static/app/views/issueList/noGroupsHandler/index.tsx
index 51e0e6f5f08b29..be5b7ef24afd43 100644
--- a/static/app/views/issueList/noGroupsHandler/index.tsx
+++ b/static/app/views/issueList/noGroupsHandler/index.tsx
@@ -16,13 +16,6 @@ import NoUnresolvedIssues from './noUnresolvedIssues';
const WaitingForEvents = lazy(() => import('sentry/components/waitingForEvents'));
const UpdatedEmptyState = lazy(() => import('sentry/components/updatedEmptyState'));
-const updatedEmptyStatePlatforms = [
- 'python-django',
- 'node',
- 'javascript-nextjs',
- 'android',
-];
-
type Props = {
api: Client;
groupIds: string[];
@@ -137,6 +130,16 @@ class NoGroupsHandler extends Component<Props, State> {
const project = projects && projects.length > 0 ? projects[0] : undefined;
const sampleIssueId = groupIds.length > 0 ? groupIds[0] : undefined;
+ const updatedEmptyStatePlatforms = [
+ 'python-django',
+ 'node',
+ 'javascript-nextjs',
+ 'android',
+ ...(organization.features.includes('issue-stream-empty-state-additional-platforms')
+ ? ['python', 'javascript']
+ : []),
+ ];
+
const hasUpdatedEmptyState =
organization.features.includes('issue-stream-empty-state') &&
project?.platform &&
|
c01d787ef97816038083c5fa266a02dfa1029dcf
|
2023-09-25 23:20:13
|
Rahul Kumar Saini
|
feat(CoGS): Dynamic Sampling Use Case IDs (#56787)
| false
|
Dynamic Sampling Use Case IDs (#56787)
|
feat
|
diff --git a/src/sentry/dynamic_sampling/tasks/boost_low_volume_projects.py b/src/sentry/dynamic_sampling/tasks/boost_low_volume_projects.py
index 7d061c9f343f7f..ebc80f03654ea9 100644
--- a/src/sentry/dynamic_sampling/tasks/boost_low_volume_projects.py
+++ b/src/sentry/dynamic_sampling/tasks/boost_low_volume_projects.py
@@ -56,6 +56,7 @@
)
from sentry.models import Organization, Project
from sentry.sentry_metrics import indexer
+from sentry.sentry_metrics.use_case_id_registry import UseCaseID
from sentry.silo import SiloMode
from sentry.snuba.dataset import Dataset, EntityKey
from sentry.snuba.metrics.naming_layer.mri import TransactionMRI
@@ -184,7 +185,10 @@ def fetch_projects_with_total_root_transaction_count_and_rates(
.set_offset(offset)
)
request = Request(
- dataset=Dataset.PerformanceMetrics.value, app_id="dynamic_sampling", query=query
+ dataset=Dataset.PerformanceMetrics.value,
+ app_id="dynamic_sampling",
+ query=query,
+ tenant_ids={"use_case_id": UseCaseID.TRANSACTIONS.value},
)
data = raw_snql_query(
request,
diff --git a/src/sentry/dynamic_sampling/tasks/boost_low_volume_transactions.py b/src/sentry/dynamic_sampling/tasks/boost_low_volume_transactions.py
index 85b4d334777203..9f96b092b52bbb 100644
--- a/src/sentry/dynamic_sampling/tasks/boost_low_volume_transactions.py
+++ b/src/sentry/dynamic_sampling/tasks/boost_low_volume_transactions.py
@@ -48,6 +48,7 @@
)
from sentry.models import Organization
from sentry.sentry_metrics import indexer
+from sentry.sentry_metrics.use_case_id_registry import UseCaseID
from sentry.silo import SiloMode
from sentry.snuba.dataset import Dataset, EntityKey
from sentry.snuba.metrics.naming_layer.mri import TransactionMRI
@@ -311,7 +312,10 @@ def __next__(self):
.set_offset(self.offset)
)
request = Request(
- dataset=Dataset.PerformanceMetrics.value, app_id="dynamic_sampling", query=query
+ dataset=Dataset.PerformanceMetrics.value,
+ app_id="dynamic_sampling",
+ query=query,
+ tenant_ids={"use_case_id": UseCaseID.TRANSACTIONS.value},
)
data = raw_snql_query(
request,
@@ -487,7 +491,10 @@ def __next__(self) -> ProjectTransactions:
.set_offset(self.offset)
)
request = Request(
- dataset=Dataset.PerformanceMetrics.value, app_id="dynamic_sampling", query=query
+ dataset=Dataset.PerformanceMetrics.value,
+ app_id="dynamic_sampling",
+ query=query,
+ tenant_ids={"use_case_id": UseCaseID.TRANSACTIONS.value},
)
data = raw_snql_query(
request,
diff --git a/src/sentry/dynamic_sampling/tasks/common.py b/src/sentry/dynamic_sampling/tasks/common.py
index ee0b9b4b55cf70..65f608a0d8175f 100644
--- a/src/sentry/dynamic_sampling/tasks/common.py
+++ b/src/sentry/dynamic_sampling/tasks/common.py
@@ -31,6 +31,7 @@
from sentry.dynamic_sampling.tasks.logging import log_extrapolated_monthly_volume, log_query_timeout
from sentry.dynamic_sampling.tasks.task_context import DynamicSamplingLogState, TaskContext
from sentry.sentry_metrics import indexer
+from sentry.sentry_metrics.use_case_id_registry import UseCaseID
from sentry.snuba.dataset import Dataset, EntityKey
from sentry.snuba.metrics.naming_layer.mri import TransactionMRI
from sentry.snuba.referrer import Referrer
@@ -236,7 +237,10 @@ def __next__(self) -> List[int]:
.set_offset(self.offset)
)
request = Request(
- dataset=Dataset.PerformanceMetrics.value, app_id="dynamic_sampling", query=query
+ dataset=Dataset.PerformanceMetrics.value,
+ app_id="dynamic_sampling",
+ query=query,
+ tenant_ids={"use_case_id": UseCaseID.TRANSACTIONS.value},
)
self.log_state.num_db_calls += 1
data = raw_snql_query(
@@ -420,7 +424,10 @@ def __next__(self) -> List[OrganizationDataVolume]:
.set_offset(self.offset)
)
request = Request(
- dataset=Dataset.PerformanceMetrics.value, app_id="dynamic_sampling", query=query
+ dataset=Dataset.PerformanceMetrics.value,
+ app_id="dynamic_sampling",
+ query=query,
+ tenant_ids={"use_case_id": UseCaseID.TRANSACTIONS.value},
)
self.log_state.num_db_calls += 1
data = raw_snql_query(
diff --git a/src/sentry/dynamic_sampling/tasks/sliding_window.py b/src/sentry/dynamic_sampling/tasks/sliding_window.py
index 8de005de173ea5..6a6d4ab4db92a0 100644
--- a/src/sentry/dynamic_sampling/tasks/sliding_window.py
+++ b/src/sentry/dynamic_sampling/tasks/sliding_window.py
@@ -41,6 +41,7 @@
from sentry.dynamic_sampling.tasks.task_context import TaskContext
from sentry.dynamic_sampling.tasks.utils import dynamic_sampling_task_with_context
from sentry.sentry_metrics import indexer
+from sentry.sentry_metrics.use_case_id_registry import UseCaseID
from sentry.silo import SiloMode
from sentry.snuba.dataset import Dataset, EntityKey
from sentry.snuba.metrics.naming_layer.mri import TransactionMRI
@@ -217,7 +218,10 @@ def fetch_projects_with_total_root_transactions_count(
)
request = Request(
- dataset=Dataset.PerformanceMetrics.value, app_id="dynamic_sampling", query=query
+ dataset=Dataset.PerformanceMetrics.value,
+ app_id="dynamic_sampling",
+ query=query,
+ tenant_ids={"use_case_id": UseCaseID.TRANSACTIONS.value},
)
data = raw_snql_query(
|
4c972826a633ec0074acd67f49c911783fb444e5
|
2017-11-14 04:35:35
|
Brett Hoerner
|
feat(tags): Add environment_id to tagstore create APIs (#6478)
| false
|
Add environment_id to tagstore create APIs (#6478)
|
feat
|
diff --git a/src/sentry/event_manager.py b/src/sentry/event_manager.py
index 5b82c4ab463698..4e55a273eb39bd 100644
--- a/src/sentry/event_manager.py
+++ b/src/sentry/event_manager.py
@@ -710,6 +710,7 @@ def save(self, project, raw=False):
organization_id=project.organization_id,
project_id=project.id,
group_id=group.id,
+ environment_id=environment.id,
event_id=event.id,
tags=tags,
)
diff --git a/src/sentry/models/project.py b/src/sentry/models/project.py
index c72824c73750b3..735435bcd30dbf 100644
--- a/src/sentry/models/project.py
+++ b/src/sentry/models/project.py
@@ -14,7 +14,6 @@
from bitfield import BitField
from django.conf import settings
from django.db import IntegrityError, models, transaction
-from django.db.models import F
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
@@ -166,20 +165,9 @@ def merge_to(self, project):
group_id=group.id,
).update(group_id=other.id)
- for obj in tagstore.get_group_tag_values(group_id=group.id):
- obj2, created = tagstore.get_or_create_group_tag_value(
- project_id=project.id,
- group_id=group.id,
- key=obj.key,
- value=obj.value,
- defaults={'times_seen': obj.times_seen}
- )
- if not created:
- obj2.update(times_seen=F('times_seen') + obj.times_seen)
-
- for fv in tagstore.get_tag_values(self.id):
- tagstore.get_or_create_tag_value(project_id=project.id, key=fv.key, value=fv.value)
- fv.delete()
+ tagstore.merge_group_tag_values_to_project(project.id, group.id)
+
+ tagstore.merge_tag_values_to_project(self.id, project.id)
self.delete()
def is_internal_project(self):
diff --git a/src/sentry/tagstore/base.py b/src/sentry/tagstore/base.py
index b5586a063b4d0c..c997dd1968a74d 100644
--- a/src/sentry/tagstore/base.py
+++ b/src/sentry/tagstore/base.py
@@ -77,6 +77,7 @@ class TagStorage(Service):
'get_group_tag_values_for_users',
'get_tags_for_search_filter',
'update_group_tag_key_values_seen',
+ 'merge_group_tag_values_to_project',
'get_tag_value_qs',
'get_group_tag_value_qs',
@@ -126,51 +127,52 @@ def get_tag_value_label(self, key, value):
return label
- def create_tag_key(self, project_id, key, **kwargs):
+ def create_tag_key(self, project_id, environment_id, key, **kwargs):
"""
- >>> create_tag_key(1, "key1")
+ >>> create_tag_key(1, 2, "key1")
"""
raise NotImplementedError
- def get_or_create_tag_key(self, project_id, key, **kwargs):
+ def get_or_create_tag_key(self, project_id, environment_id, key, **kwargs):
"""
- >>> get_or_create_tag_key(1, "key1")
+ >>> get_or_create_tag_key(1, 2, "key1")
"""
raise NotImplementedError
- def create_tag_value(self, project_id, key, value, **kwargs):
+ def create_tag_value(self, project_id, environment_id, key, value, **kwargs):
"""
- >>> create_tag_key(1, "key1", "value1")
+ >>> create_tag_key(1, 2, "key1", "value1")
"""
raise NotImplementedError
- def get_or_create_tag_value(self, project_id, key, value, **kwargs):
+ def get_or_create_tag_value(self, project_id, environment_id, key, value, **kwargs):
"""
- >>> get_or_create_tag_key(1, "key1", "value1")
+ >>> get_or_create_tag_key(1, 2, "key1", "value1")
"""
raise NotImplementedError
- def create_group_tag_key(self, project_id, group_id, key, **kwargs):
+ def create_group_tag_key(self, project_id, group_id, environment_id, key, **kwargs):
"""
- >>> create_group_tag_key(1, 2, "key1")
+ >>> create_group_tag_key(1, 2, 3, "key1")
"""
raise NotImplementedError
- def get_or_create_group_tag_key(self, project_id, group_id, key, **kwargs):
+ def get_or_create_group_tag_key(self, project_id, group_id, environment_id, key, **kwargs):
"""
- >>> get_or_create_group_tag_key(1, 2, "key1")
+ >>> get_or_create_group_tag_key(1, 2, 3, "key1")
"""
raise NotImplementedError
- def create_group_tag_value(self, project_id, group_id, key, value, **kwargs):
+ def create_group_tag_value(self, project_id, group_id, environment_id, key, value, **kwargs):
"""
- >>> create_group_tag_value(1, 2, "key1", "value1")
+ >>> create_group_tag_value(1, 2, 3, "key1", "value1")
"""
raise NotImplementedError
- def get_or_create_group_tag_value(self, project_id, group_id, key, value, **kwargs):
+ def get_or_create_group_tag_value(self, project_id, group_id,
+ environment_id, key, value, **kwargs):
"""
- >>> get_or_create_group_tag_value(1, 2, "key1", "value1")
+ >>> get_or_create_group_tag_value(1, 2, 3, "key1", "value1")
"""
raise NotImplementedError
@@ -280,6 +282,18 @@ def get_group_event_ids(self, project_id, group_id, tags):
"""
raise NotImplementedError
+ def merge_tag_values_to_project(self, source_project_id, target_project_id):
+ """
+ >>> merge_tag_values_to_project(1, 2)
+ """
+ raise NotImplementedError
+
+ def merge_group_tag_values_to_project(self, target_project_id, group_id):
+ """
+ >>> merge_group_tag_values_to_project(1, 2)
+ """
+ raise NotImplementedError
+
def get_tag_value_qs(self, project_id, key, query=None):
"""
>>> get_tag_value_qs(1, 'environment', query='prod')
diff --git a/src/sentry/tagstore/legacy/backend.py b/src/sentry/tagstore/legacy/backend.py
index 62d93f404b9375..d41395b6f05754 100644
--- a/src/sentry/tagstore/legacy/backend.py
+++ b/src/sentry/tagstore/legacy/backend.py
@@ -13,7 +13,7 @@
from collections import defaultdict
from datetime import timedelta
from django.db import connections, router, IntegrityError, transaction
-from django.db.models import Q, Sum
+from django.db.models import F, Q, Sum
from django.utils import timezone
from operator import or_
from six.moves import reduce
@@ -71,32 +71,33 @@ def setup(self):
GroupTagKey,
]
- def create_tag_key(self, project_id, key, **kwargs):
+ def create_tag_key(self, project_id, environment_id, key, **kwargs):
return TagKey.objects.create(project_id=project_id, key=key, **kwargs)
- def get_or_create_tag_key(self, project_id, key, **kwargs):
+ def get_or_create_tag_key(self, project_id, environment_id, key, **kwargs):
return TagKey.objects.get_or_create(project_id=project_id, key=key, **kwargs)
- def create_tag_value(self, project_id, key, value, **kwargs):
+ def create_tag_value(self, project_id, environment_id, key, value, **kwargs):
return TagValue.objects.create(project_id=project_id, key=key, value=value, **kwargs)
- def get_or_create_tag_value(self, project_id, key, value, **kwargs):
+ def get_or_create_tag_value(self, project_id, environment_id, key, value, **kwargs):
return TagValue.objects.get_or_create(
project_id=project_id, key=key, value=value, **kwargs)
- def create_group_tag_key(self, project_id, group_id, key, **kwargs):
+ def create_group_tag_key(self, project_id, group_id, environment_id, key, **kwargs):
return GroupTagKey.objects.create(project_id=project_id, group_id=group_id,
key=key, **kwargs)
- def get_or_create_group_tag_key(self, project_id, group_id, key, **kwargs):
+ def get_or_create_group_tag_key(self, project_id, group_id, environment_id, key, **kwargs):
return GroupTagKey.objects.get_or_create(project_id=project_id, group_id=group_id,
key=key, **kwargs)
- def create_group_tag_value(self, project_id, group_id, key, value, **kwargs):
+ def create_group_tag_value(self, project_id, group_id, environment_id, key, value, **kwargs):
return GroupTagValue.objects.create(
project_id=project_id, group_id=group_id, key=key, value=value, **kwargs)
- def get_or_create_group_tag_value(self, project_id, group_id, key, value, **kwargs):
+ def get_or_create_group_tag_value(self, project_id, group_id,
+ environment_id, key, value, **kwargs):
return GroupTagValue.objects.get_or_create(
project_id=project_id, group_id=group_id, key=key, value=value, **kwargs)
@@ -516,6 +517,29 @@ def update_group_tag_key_values_seen(self, group_ids):
).count(),
)
+ def merge_tag_values_to_project(self, source_project_id, target_project_id):
+ for tv in self.get_tag_values(source_project_id):
+ self.get_or_create_tag_value(
+ project_id=target_project_id,
+ environment_id=None,
+ key=tv.key,
+ value=tv.value)
+ tv.delete()
+
+ def merge_group_tag_values_to_project(self, target_project_id, group_id):
+ for gtv in self.get_group_tag_values(group_id=group_id):
+ gtv2, created = self.get_or_create_group_tag_value(
+ project_id=target_project_id,
+ group_id=group_id,
+ environment_id=None,
+ key=gtv.key,
+ value=gtv.value,
+ defaults={'times_seen': gtv.times_seen},
+ )
+
+ if not created:
+ gtv2.update(times_seen=F('times_seen') + gtv.times_seen)
+
def get_tag_value_qs(self, project_id, key, query=None):
queryset = TagValue.objects.filter(
project_id=project_id,
diff --git a/src/sentry/tasks/post_process.py b/src/sentry/tasks/post_process.py
index 832b65049cc5e5..71fd9d94988ec9 100644
--- a/src/sentry/tasks/post_process.py
+++ b/src/sentry/tasks/post_process.py
@@ -136,7 +136,8 @@ def plugin_post_process_group(plugin_slug, event, **kwargs):
@instrumented_task(
name='sentry.tasks.index_event_tags', default_retry_delay=60 * 5, max_retries=None
)
-def index_event_tags(organization_id, project_id, event_id, tags, group_id=None, **kwargs):
+def index_event_tags(organization_id, project_id, event_id, tags,
+ group_id=None, environment_id=None, **kwargs):
from sentry import tagstore
Raven.tags_context({
@@ -144,8 +145,8 @@ def index_event_tags(organization_id, project_id, event_id, tags, group_id=None,
})
for key, value in tags:
- tagkey, _ = tagstore.get_or_create_tag_key(project_id, key)
- tagvalue, _ = tagstore.get_or_create_tag_value(project_id, key, value)
+ tagkey, _ = tagstore.get_or_create_tag_key(project_id, environment_id, key)
+ tagvalue, _ = tagstore.get_or_create_tag_value(project_id, environment_id, key, value)
tagstore.create_event_tag(
project_id=project_id,
diff --git a/src/sentry/tasks/unmerge.py b/src/sentry/tasks/unmerge.py
index 103ea8d20e0375..da99b9a509e27f 100644
--- a/src/sentry/tasks/unmerge.py
+++ b/src/sentry/tasks/unmerge.py
@@ -267,7 +267,8 @@ def collect_tag_data(events):
results = {}
for event in events:
- tags = results.setdefault(event.group_id, {})
+ environment = get_environment_name(event)
+ tags = results.setdefault((event.group_id, environment), {})
for key, value in event.get_tags():
values = tags.setdefault(key, {})
@@ -282,11 +283,16 @@ def collect_tag_data(events):
def repair_tag_data(caches, project, events):
- for group_id, keys in collect_tag_data(events).items():
+ for (group_id, env_name), keys in collect_tag_data(events).items():
+ environment = caches['Environment'](
+ project.organization_id,
+ env_name,
+ )
for key, values in keys.items():
tagstore.get_or_create_group_tag_key(
project_id=project.id,
group_id=group_id,
+ environment_id=environment.id,
key=key,
)
@@ -297,6 +303,7 @@ def repair_tag_data(caches, project, events):
instance, created = tagstore.get_or_create_group_tag_value(
project_id=project.id,
group_id=group_id,
+ environment_id=environment.id,
key=key,
value=value,
defaults={
diff --git a/src/sentry/testutils/fixtures.py b/src/sentry/testutils/fixtures.py
index d415f830bc7914..e71e7fb436a69c 100644
--- a/src/sentry/testutils/fixtures.py
+++ b/src/sentry/testutils/fixtures.py
@@ -21,7 +21,7 @@
from django.utils import timezone
from sentry.models import (
- Activity, Event, EventError, EventMapping, Group, Organization, OrganizationMember,
+ Activity, Environment, Event, EventError, EventMapping, Group, Organization, OrganizationMember,
OrganizationMemberTeam, Project, Team, User, UserEmail, Release, Commit, ReleaseCommit,
CommitAuthor, Repository, CommitFileChange
)
@@ -192,6 +192,13 @@ def project(self):
team=self.team,
)
+ @fixture
+ def environment(self):
+ return self.create_environment(
+ name='development',
+ project=self.project,
+ )
+
@fixture
def group(self):
return self.create_group(message=u'\u3053\u3093\u306b\u3061\u306f')
@@ -249,6 +256,14 @@ def create_team(self, **kwargs):
return Team.objects.create(**kwargs)
+ def create_environment(self, **kwargs):
+ project = kwargs.get('project', self.project)
+ name = kwargs.get('name', petname.Generate(1, ' ', letters=10))
+ return Environment.get_or_create(
+ project=project,
+ name=name
+ )
+
def create_project(self, **kwargs):
if not kwargs.get('name'):
kwargs['name'] = petname.Generate(2, ' ', letters=10).title()
diff --git a/tests/sentry/api/endpoints/test_group_details.py b/tests/sentry/api/endpoints/test_group_details.py
index b2e0032cd2e6d7..c4296e4a89f9c3 100644
--- a/tests/sentry/api/endpoints/test_group_details.py
+++ b/tests/sentry/api/endpoints/test_group_details.py
@@ -38,6 +38,7 @@ def test_with_first_release(self):
tagstore.create_group_tag_value(
group_id=group.id,
project_id=group.project_id,
+ environment_id=self.environment.id,
key='sentry:release',
value=release.version,
)
diff --git a/tests/sentry/api/endpoints/test_group_events.py b/tests/sentry/api/endpoints/test_group_events.py
index 46f855bc3e8230..d6403ba050531c 100644
--- a/tests/sentry/api/endpoints/test_group_events.py
+++ b/tests/sentry/api/endpoints/test_group_events.py
@@ -33,11 +33,29 @@ def test_tags(self):
event_1 = self.create_event('a' * 32, group=group)
event_2 = self.create_event('b' * 32, group=group)
- tagkey_1 = tagstore.create_tag_key(project_id=group.project_id, key='foo')
- tagkey_2 = tagstore.create_tag_key(project_id=group.project_id, key='bar')
- tagvalue_1 = tagstore.create_tag_value(project_id=group.project_id, key='foo', value='baz')
- tagvalue_2 = tagstore.create_tag_value(project_id=group.project_id, key='bar', value='biz')
- tagvalue_3 = tagstore.create_tag_value(project_id=group.project_id, key='bar', value='buz')
+ tagkey_1 = tagstore.create_tag_key(
+ project_id=group.project_id,
+ environment_id=self.environment.id,
+ key='foo')
+ tagkey_2 = tagstore.create_tag_key(
+ project_id=group.project_id,
+ environment_id=self.environment.id,
+ key='bar')
+ tagvalue_1 = tagstore.create_tag_value(
+ project_id=group.project_id,
+ environment_id=self.environment.id,
+ key='foo',
+ value='baz')
+ tagvalue_2 = tagstore.create_tag_value(
+ project_id=group.project_id,
+ environment_id=self.environment.id,
+ key='bar',
+ value='biz')
+ tagvalue_3 = tagstore.create_tag_value(
+ project_id=group.project_id,
+ environment_id=self.environment.id,
+ key='bar',
+ value='buz')
tagstore.create_event_tag(
project_id=group.project_id,
diff --git a/tests/sentry/api/endpoints/test_group_tagkey_details.py b/tests/sentry/api/endpoints/test_group_tagkey_details.py
index 2f760695fb33e0..45c921c4be840e 100644
--- a/tests/sentry/api/endpoints/test_group_tagkey_details.py
+++ b/tests/sentry/api/endpoints/test_group_tagkey_details.py
@@ -15,11 +15,13 @@ def test_simple(self):
key, value = group.data['tags'][0]
tagkey = tagstore.create_tag_key(
project_id=group.project_id,
+ environment_id=self.environment.id,
key=key,
values_seen=2
)
tagstore.create_tag_value(
project_id=group.project_id,
+ environment_id=self.environment.id,
key=key,
value=value,
times_seen=4
@@ -28,12 +30,14 @@ def test_simple(self):
tagstore.create_group_tag_key(
project_id=group.project_id,
group_id=group.id,
+ environment_id=self.environment.id,
key=key,
values_seen=1,
)
tagstore.create_group_tag_value(
project_id=group.project_id,
group_id=group.id,
+ environment_id=self.environment.id,
key=key,
value=value,
times_seen=3,
diff --git a/tests/sentry/api/endpoints/test_group_tagkey_values.py b/tests/sentry/api/endpoints/test_group_tagkey_values.py
index 7f1250e35af1ae..25b057f28d3af4 100644
--- a/tests/sentry/api/endpoints/test_group_tagkey_values.py
+++ b/tests/sentry/api/endpoints/test_group_tagkey_values.py
@@ -11,15 +11,17 @@ def test_simple(self):
project = self.create_project()
group = self.create_group(project=project)
- tagstore.create_tag_key(project_id=project.id, key=key)
+ tagstore.create_tag_key(project_id=project.id, environment_id=self.environment.id, key=key)
tagstore.create_tag_value(
project_id=project.id,
+ environment_id=self.environment.id,
key=key,
value=value,
)
tagstore.create_group_tag_value(
project_id=project.id,
group_id=group.id,
+ environment_id=self.environment.id,
key=key,
value=value,
)
@@ -47,16 +49,19 @@ def test_user_tag(self):
)
tagstore.create_tag_key(
project_id=project.id,
+ environment_id=self.environment.id,
key='sentry:user',
)
tagstore.create_tag_value(
project_id=project.id,
+ environment_id=self.environment.id,
key='sentry:user',
value=euser.tag_value,
)
tagstore.create_group_tag_value(
project_id=project.id,
group_id=group.id,
+ environment_id=self.environment.id,
key='sentry:user',
value=euser.tag_value,
)
diff --git a/tests/sentry/api/endpoints/test_group_tags.py b/tests/sentry/api/endpoints/test_group_tags.py
index 2075b0498655ec..62234d0bcae7c0 100644
--- a/tests/sentry/api/endpoints/test_group_tags.py
+++ b/tests/sentry/api/endpoints/test_group_tags.py
@@ -18,21 +18,25 @@ def test_simple(self):
for key, value in group.data['tags']:
tagstore.create_tag_key(
project_id=group.project_id,
+ environment_id=self.environment.id,
key=key,
)
tagstore.create_tag_value(
project_id=group.project_id,
+ environment_id=self.environment.id,
key=key,
value=value,
)
tagstore.create_group_tag_key(
project_id=group.project_id,
group_id=group.id,
+ environment_id=self.environment.id,
key=key,
)
tagstore.create_group_tag_value(
project_id=group.project_id,
group_id=group.id,
+ environment_id=self.environment.id,
key=key,
value=value,
)
diff --git a/tests/sentry/api/endpoints/test_organization_user_issues.py b/tests/sentry/api/endpoints/test_organization_user_issues.py
index 277d03c533d414..315a977473aaaa 100644
--- a/tests/sentry/api/endpoints/test_organization_user_issues.py
+++ b/tests/sentry/api/endpoints/test_organization_user_issues.py
@@ -37,19 +37,22 @@ def setUp(self):
key='sentry:user',
value=self.euser1.tag_value,
group_id=self.group1.id,
- project_id=self.project1.id
+ project_id=self.project1.id,
+ environment_id=self.environment.id,
)
tagstore.create_group_tag_value(
key='sentry:user',
value=self.euser2.tag_value,
group_id=self.group1.id,
- project_id=self.project1.id
+ project_id=self.project1.id,
+ environment_id=self.environment.id,
)
tagstore.create_group_tag_value(
key='sentry:user',
value=self.euser3.tag_value,
group_id=self.group2.id,
- project_id=self.project2.id
+ project_id=self.project2.id,
+ environment_id=self.environment.id,
)
self.path = reverse(
'sentry-api-0-organization-user-issues', args=[
diff --git a/tests/sentry/api/endpoints/test_organization_user_issues_search.py b/tests/sentry/api/endpoints/test_organization_user_issues_search.py
index 0f4d34b8bee20b..e259d7ab23bff8 100644
--- a/tests/sentry/api/endpoints/test_organization_user_issues_search.py
+++ b/tests/sentry/api/endpoints/test_organization_user_issues_search.py
@@ -34,18 +34,21 @@ def setUp(self):
key='sentry:user',
value='email:[email protected]',
group_id=group1.id,
+ environment_id=self.environment.id,
project_id=self.project1.id
)
tagstore.create_group_tag_value(
key='sentry:user',
value='email:[email protected]',
group_id=group1.id,
+ environment_id=self.environment.id,
project_id=self.project1.id
)
tagstore.create_group_tag_value(
key='sentry:user',
value='email:[email protected]',
group_id=group2.id,
+ environment_id=self.environment.id,
project_id=self.project2.id
)
diff --git a/tests/sentry/api/endpoints/test_project_group_index.py b/tests/sentry/api/endpoints/test_project_group_index.py
index a16f7070d4d6d4..778085bb3badfc 100644
--- a/tests/sentry/api/endpoints/test_project_group_index.py
+++ b/tests/sentry/api/endpoints/test_project_group_index.py
@@ -248,11 +248,13 @@ def test_lookup_by_release(self):
group = self.create_group(checksum='a' * 32, project=project)
group2 = self.create_group(checksum='b' * 32, project=project2)
tagstore.create_group_tag_value(
- project_id=project.id, group_id=group.id, key='sentry:release', value=release.version
+ project_id=project.id, group_id=group.id, environment_id=self.environment.id,
+ key='sentry:release', value=release.version
)
tagstore.create_group_tag_value(
- project_id=project2.id, group_id=group2.id, key='sentry:release', value=release.version
+ project_id=project2.id, group_id=group2.id, environment_id=self.environment.id,
+ key='sentry:release', value=release.version
)
url = '%s?query=%s' % (self.path, quote('release:"%s"' % release.version))
@@ -923,6 +925,7 @@ def test_snooze_user_count(self):
tagstore.create_group_tag_key(
group.project_id,
group.id,
+ self.environment.id,
'sentry:user',
values_seen=100,
)
diff --git a/tests/sentry/api/endpoints/test_project_tagkey_details.py b/tests/sentry/api/endpoints/test_project_tagkey_details.py
index 3b9862be6f6896..a08618df3c0f80 100644
--- a/tests/sentry/api/endpoints/test_project_tagkey_details.py
+++ b/tests/sentry/api/endpoints/test_project_tagkey_details.py
@@ -15,6 +15,7 @@ def test_simple(self):
project = self.create_project()
tagkey = tagstore.create_tag_key(
project_id=project.id,
+ environment_id=self.environment.id,
key='foo',
values_seen=16
)
@@ -41,7 +42,10 @@ class ProjectTagKeyDeleteTest(APITestCase):
@mock.patch('sentry.tagstore.legacy.tasks.delete_tag_key')
def test_simple(self, mock_delete_tag_key):
project = self.create_project()
- tagkey = tagstore.create_tag_key(project_id=project.id, key='foo')
+ tagkey = tagstore.create_tag_key(
+ project_id=project.id,
+ environment_id=self.environment.id,
+ key='foo')
self.login_as(user=self.user)
diff --git a/tests/sentry/api/endpoints/test_project_tagkey_values.py b/tests/sentry/api/endpoints/test_project_tagkey_values.py
index 152ffd9a2294e1..217edfd97d5c99 100644
--- a/tests/sentry/api/endpoints/test_project_tagkey_values.py
+++ b/tests/sentry/api/endpoints/test_project_tagkey_values.py
@@ -9,8 +9,15 @@
class ProjectTagKeyValuesTest(APITestCase):
def test_simple(self):
project = self.create_project()
- tagkey = tagstore.create_tag_key(project_id=project.id, key='foo')
- tagstore.create_tag_value(project_id=project.id, key='foo', value='bar')
+ tagkey = tagstore.create_tag_key(
+ project_id=project.id,
+ environment_id=self.environment.id,
+ key='foo')
+ tagstore.create_tag_value(
+ project_id=project.id,
+ environment_id=self.environment.id,
+ key='foo',
+ value='bar')
self.login_as(user=self.user)
@@ -32,8 +39,15 @@ def test_simple(self):
def test_query(self):
project = self.create_project()
- tagkey = tagstore.create_tag_key(project_id=project.id, key='foo')
- tagstore.create_tag_value(project_id=project.id, key='foo', value='bar')
+ tagkey = tagstore.create_tag_key(
+ project_id=project.id,
+ environment_id=self.environment.id,
+ key='foo')
+ tagstore.create_tag_value(
+ project_id=project.id,
+ environment_id=self.environment.id,
+ key='foo',
+ value='bar')
self.login_as(user=self.user)
diff --git a/tests/sentry/api/endpoints/test_project_tags.py b/tests/sentry/api/endpoints/test_project_tags.py
index 5d7f7e894a89c6..b17df2b99cff90 100644
--- a/tests/sentry/api/endpoints/test_project_tags.py
+++ b/tests/sentry/api/endpoints/test_project_tags.py
@@ -13,6 +13,7 @@ def test_simple(self):
for key in ('foo', 'bar'):
tagstore.create_tag_key(
project_id=project.id,
+ environment_id=self.environment.id,
key=key,
)
diff --git a/tests/sentry/api/serializers/test_grouptagkey.py b/tests/sentry/api/serializers/test_grouptagkey.py
index d09aedb56cd711..c22d496d307bdc 100644
--- a/tests/sentry/api/serializers/test_grouptagkey.py
+++ b/tests/sentry/api/serializers/test_grouptagkey.py
@@ -13,11 +13,13 @@ def test(self):
project = self.create_project()
tagkey = tagstore.create_tag_key(
project_id=project.id,
+ environment_id=self.environment.id,
key='key'
)
grouptagkey = tagstore.create_group_tag_key(
project_id=project.id,
group_id=self.create_group(project=project).id,
+ environment_id=self.environment.id,
key=tagkey.key
)
diff --git a/tests/sentry/api/serializers/test_grouptagvalue.py b/tests/sentry/api/serializers/test_grouptagvalue.py
index 8042b30bff8ab7..00a7c4b832663b 100644
--- a/tests/sentry/api/serializers/test_grouptagvalue.py
+++ b/tests/sentry/api/serializers/test_grouptagvalue.py
@@ -20,12 +20,14 @@ def test_with_user(self):
)
tagvalue = tagstore.create_tag_value(
project_id=project.id,
+ environment_id=self.environment.id,
key='sentry:user',
value=euser.tag_value,
)
grouptagvalue = tagstore.create_group_tag_value(
project_id=project.id,
group_id=self.create_group(project=project).id,
+ environment_id=self.environment.id,
key=tagvalue.key,
value=tagvalue.value,
)
diff --git a/tests/sentry/api/serializers/test_release.py b/tests/sentry/api/serializers/test_release.py
index 3243c0c023d455..121ee5187a10c8 100644
--- a/tests/sentry/api/serializers/test_release.py
+++ b/tests/sentry/api/serializers/test_release.py
@@ -41,6 +41,7 @@ def test_simple(self):
value = release.version
tagstore.create_tag_value(
project_id=project.id,
+ environment_id=self.environment.id,
key=key,
value=value,
first_seen=timezone.now(),
@@ -49,6 +50,7 @@ def test_simple(self):
)
tagstore.create_tag_value(
project_id=project2.id,
+ environment_id=self.environment.id,
key=key,
value=value,
first_seen=timezone.now() - datetime.timedelta(days=2),
diff --git a/tests/sentry/api/serializers/test_tagvalue.py b/tests/sentry/api/serializers/test_tagvalue.py
index c19b52c9ec7d7c..28a32e13b49d6d 100644
--- a/tests/sentry/api/serializers/test_tagvalue.py
+++ b/tests/sentry/api/serializers/test_tagvalue.py
@@ -20,6 +20,7 @@ def test_with_user(self):
)
tagvalue = tagstore.create_tag_value(
project_id=project.id,
+ environment_id=self.environment.id,
key='sentry:user',
value=euser.tag_value,
)
@@ -35,6 +36,7 @@ def test_basic(self):
project = self.create_project()
tagvalue = tagstore.create_tag_value(
project_id=project.id,
+ environment_id=self.environment.id,
key='sentry:user',
value='email:[email protected]',
)
@@ -50,6 +52,7 @@ def test_release(self):
project = self.create_project()
tagvalue = tagstore.create_tag_value(
project_id=project.id,
+ environment_id=self.environment.id,
key='sentry:release',
value='df84bccbb23ca15f2868be1f2a5f7c7a6464fadd',
)
diff --git a/tests/sentry/deletions/test_tagkey.py b/tests/sentry/deletions/test_tagkey.py
index 3294a2927fc3f4..0a8802ced83cb8 100644
--- a/tests/sentry/deletions/test_tagkey.py
+++ b/tests/sentry/deletions/test_tagkey.py
@@ -13,11 +13,22 @@ def test_simple(self):
group = self.create_group(project=project)
key = 'foo'
value = 'bar'
- tk = tagstore.create_tag_key(key=key, project_id=project.id)
- tagstore.create_tag_value(key=key, value=value, project_id=project.id)
- tagstore.create_group_tag_key(key=key, group_id=group.id, project_id=project.id)
+ tk = tagstore.create_tag_key(
+ key=key,
+ project_id=project.id,
+ environment_id=self.environment.id)
+ tagstore.create_tag_value(
+ key=key,
+ value=value,
+ project_id=project.id,
+ environment_id=self.environment.id)
+ tagstore.create_group_tag_key(
+ key=key,
+ group_id=group.id,
+ project_id=project.id,
+ environment_id=self.environment.id)
tagstore.create_group_tag_value(
- key=key, value=value, group_id=group.id, project_id=project.id
+ key=key, value=value, group_id=group.id, project_id=project.id, environment_id=self.environment.id
)
tagstore.create_event_tag(
key_id=tk.id,
@@ -29,10 +40,14 @@ def test_simple(self):
project2 = self.create_project(team=team, name='test2')
group2 = self.create_group(project=project2)
- tk2 = tagstore.create_tag_key(project2.id, key)
- tagstore.create_group_tag_key(key=key, group_id=group2.id, project_id=project2.id)
+ tk2 = tagstore.create_tag_key(project2.id, self.environment.id, key)
+ tagstore.create_group_tag_key(
+ key=key,
+ group_id=group2.id,
+ project_id=project2.id,
+ environment_id=self.environment.id)
tagstore.create_group_tag_value(
- key=key, value=value, group_id=group2.id, project_id=project2.id
+ key=key, value=value, group_id=group2.id, project_id=project2.id, environment_id=self.environment.id
)
tagstore.create_event_tag(
key_id=tk2.id,
diff --git a/tests/sentry/models/test_group.py b/tests/sentry/models/test_group.py
index 6442d18433bb7c..32cbcd1407c60b 100644
--- a/tests/sentry/models/test_group.py
+++ b/tests/sentry/models/test_group.py
@@ -180,7 +180,8 @@ def test_first_last_release(self):
)
tagstore.create_group_tag_value(
- project_id=project.id, group_id=group.id, key='sentry:release', value=release.version
+ project_id=project.id, group_id=group.id, environment_id=self.environment.id,
+ key='sentry:release', value=release.version
)
assert group.first_release == release
@@ -200,7 +201,8 @@ def test_first_release_from_tag(self):
)
tagstore.create_group_tag_value(
- project_id=project.id, group_id=group.id, key='sentry:release', value=release.version
+ project_id=project.id, group_id=group.id, environment_id=self.environment.id,
+ key='sentry:release', value=release.version
)
assert group.first_release is None
diff --git a/tests/sentry/models/test_groupsnooze.py b/tests/sentry/models/test_groupsnooze.py
index 95ee112c22e421..01dc02511f9b0b 100644
--- a/tests/sentry/models/test_groupsnooze.py
+++ b/tests/sentry/models/test_groupsnooze.py
@@ -71,6 +71,7 @@ def test_user_delta_reached(self):
tagstore.create_group_tag_key(
project_id=self.group.project_id,
group_id=self.group.id,
+ environment_id=self.environment.id,
key='sentry:user',
values_seen=100,
)
diff --git a/tests/sentry/receivers/test_releases.py b/tests/sentry/receivers/test_releases.py
index 957d14048868d1..a2465059ead7f1 100644
--- a/tests/sentry/receivers/test_releases.py
+++ b/tests/sentry/receivers/test_releases.py
@@ -17,6 +17,7 @@ class EnsureReleaseExistsTest(TestCase):
def test_simple(self):
tv = tagstore.create_tag_value(
project_id=self.project.id,
+ environment_id=self.environment.id,
key='sentry:release',
value='1.0',
)
diff --git a/tests/sentry/search/django/tests.py b/tests/sentry/search/django/tests.py
index 9bf7f3ef7516df..cf3acf34a20333 100644
--- a/tests/sentry/search/django/tests.py
+++ b/tests/sentry/search/django/tests.py
@@ -20,8 +20,10 @@ def create_backend(self):
def setUp(self):
self.backend = self.create_backend()
- self.project1 = self.create_project(name='foo')
- self.project2 = self.create_project(name='bar')
+ self.project1 = self.create_project(name='project1')
+ self.env1 = self.create_environment(project=self.project1, name='env1')
+ self.project2 = self.create_project(name='project2')
+ self.env2 = self.create_environment(project=self.project2, name='env2')
self.group1 = self.create_group(
project=self.project1,
@@ -75,6 +77,7 @@ def setUp(self):
tagstore.create_group_tag_value(
project_id=self.group1.project_id,
group_id=self.group1.id,
+ environment_id=self.env1.id,
key=key,
value=value,
)
@@ -82,6 +85,7 @@ def setUp(self):
tagstore.create_group_tag_value(
project_id=self.group2.project_id,
group_id=self.group2.id,
+ environment_id=self.env2.id,
key=key,
value=value,
)
diff --git a/tests/sentry/tasks/post_process/tests.py b/tests/sentry/tasks/post_process/tests.py
index 13b95a6cee9312..fb149a1926a47c 100644
--- a/tests/sentry/tasks/post_process/tests.py
+++ b/tests/sentry/tasks/post_process/tests.py
@@ -120,6 +120,7 @@ def test_simple(self):
event_id=event.id,
group_id=group.id,
project_id=self.project.id,
+ environment_id=self.environment.id,
organization_id=self.project.organization_id,
tags=[('foo', 'bar'), ('biz', 'baz')],
)
@@ -157,6 +158,7 @@ def test_simple(self):
event_id=event.id,
group_id=group.id,
project_id=self.project.id,
+ environment_id=self.environment.id,
organization_id=self.project.organization_id,
tags=[('foo', 'bar'), ('biz', 'baz')],
)
diff --git a/tests/sentry/tasks/test_deletion.py b/tests/sentry/tasks/test_deletion.py
index 25c371a2eee15d..adb3f9fd4f0139 100644
--- a/tests/sentry/tasks/test_deletion.py
+++ b/tests/sentry/tasks/test_deletion.py
@@ -191,11 +191,22 @@ def test_simple(self):
group = self.create_group(project=project)
key = 'foo'
value = 'bar'
- tk = tagstore.create_tag_key(key=key, project_id=project.id)
- tagstore.create_tag_value(key=key, value=value, project_id=project.id)
- tagstore.create_group_tag_key(key=key, group_id=group.id, project_id=project.id)
+ tk = tagstore.create_tag_key(
+ key=key,
+ project_id=project.id,
+ environment_id=self.environment.id)
+ tagstore.create_tag_value(
+ key=key,
+ value=value,
+ project_id=project.id,
+ environment_id=self.environment.id)
+ tagstore.create_group_tag_key(
+ key=key,
+ group_id=group.id,
+ project_id=project.id,
+ environment_id=self.environment.id)
tagstore.create_group_tag_value(
- key=key, value=value, group_id=group.id, project_id=project.id
+ key=key, value=value, group_id=group.id, project_id=project.id, environment_id=self.environment.id
)
tagstore.create_event_tag(
key_id=tk.id,
@@ -207,10 +218,15 @@ def test_simple(self):
project2 = self.create_project(team=team, name='test2')
group2 = self.create_group(project=project2)
- tk2 = tagstore.create_tag_key(key=key, project_id=project2.id)
- tagstore.create_group_tag_key(key=key, group_id=group2.id, project_id=project2.id)
+ tk2 = tagstore.create_tag_key(key=key, project_id=project2.id,
+ environment_id=self.environment.id)
+ tagstore.create_group_tag_key(
+ key=key,
+ group_id=group2.id,
+ project_id=project2.id,
+ environment_id=self.environment.id)
tagstore.create_group_tag_value(
- key=key, value=value, group_id=group2.id, project_id=project2.id
+ key=key, value=value, group_id=group2.id, project_id=project2.id, environment_id=self.environment.id
)
tagstore.create_event_tag(
key_id=tk2.id,
diff --git a/tests/sentry/tasks/test_merge.py b/tests/sentry/tasks/test_merge.py
index 536e65cc4f3aeb..1f971bf26a41b4 100644
--- a/tests/sentry/tasks/test_merge.py
+++ b/tests/sentry/tasks/test_merge.py
@@ -103,6 +103,7 @@ def test_merge_updates_tag_values_seen(self):
tagstore.create_group_tag_key(
project_id=project.id,
group_id=group.id,
+ environment_id=self.environment.id,
key=key,
values_seen=values_seen,
)
@@ -111,6 +112,7 @@ def test_merge_updates_tag_values_seen(self):
tagstore.create_group_tag_value(
project_id=project.id,
group_id=group.id,
+ environment_id=self.environment.id,
key=key,
value=value,
times_seen=times_seen,
diff --git a/tests/sentry/web/frontend/test_group_tag_export.py b/tests/sentry/web/frontend/test_group_tag_export.py
index f6c8524c18bae4..beab30d0528dda 100644
--- a/tests/sentry/web/frontend/test_group_tag_export.py
+++ b/tests/sentry/web/frontend/test_group_tag_export.py
@@ -16,15 +16,17 @@ def test_simple(self):
project = self.create_project()
group = self.create_group(project=project)
- tagstore.create_tag_key(project_id=project.id, key=key)
+ tagstore.create_tag_key(project_id=project.id, environment_id=self.environment.id, key=key)
tagstore.create_tag_value(
project_id=project.id,
+ environment_id=self.environment.id,
key=key,
value=value,
)
group_tag_value = tagstore.create_group_tag_value(
project_id=project.id,
group_id=group.id,
+ environment_id=self.environment.id,
key=key,
value=value,
times_seen=1,
diff --git a/tests/sentry/web/frontend/test_project_tags.py b/tests/sentry/web/frontend/test_project_tags.py
index fc1a990b639ff6..dc9d8e7ad5593a 100644
--- a/tests/sentry/web/frontend/test_project_tags.py
+++ b/tests/sentry/web/frontend/test_project_tags.py
@@ -18,9 +18,18 @@ def test_requires_authentication(self):
self.assertRequiresAuthentication(self.path)
def test_simple(self):
- tagstore.create_tag_key(project_id=self.project.id, key='site')
- tagstore.create_tag_key(project_id=self.project.id, key='url')
- tagstore.create_tag_key(project_id=self.project.id, key='os')
+ tagstore.create_tag_key(
+ project_id=self.project.id,
+ environment_id=self.environment.id,
+ key='site')
+ tagstore.create_tag_key(
+ project_id=self.project.id,
+ environment_id=self.environment.id,
+ key='url')
+ tagstore.create_tag_key(
+ project_id=self.project.id,
+ environment_id=self.environment.id,
+ key='os')
self.login_as(self.user)
|
63464d6941e2b7c186df6fd162a572daf34ddf6d
|
2018-05-22 23:42:50
|
Jess MacQueen
|
fix(api): Allow users who aren't owners of orgs to delete their accounts (#8486)
| false
|
Allow users who aren't owners of orgs to delete their accounts (#8486)
|
fix
|
diff --git a/src/sentry/api/endpoints/user_details.py b/src/sentry/api/endpoints/user_details.py
index 2ce464037ca826..ea0abe57919db4 100644
--- a/src/sentry/api/endpoints/user_details.py
+++ b/src/sentry/api/endpoints/user_details.py
@@ -100,7 +100,7 @@ class Meta:
class OrganizationsSerializer(serializers.Serializer):
- organizations = ListField(child=serializers.CharField(), required=True)
+ organizations = ListField(child=serializers.CharField(required=False), required=True)
class UserDetailsEndpoint(UserEndpoint):
diff --git a/src/sentry/api/serializers/rest_framework/list.py b/src/sentry/api/serializers/rest_framework/list.py
index 003dbb1a44a96a..79a34d5ed4b32d 100644
--- a/src/sentry/api/serializers/rest_framework/list.py
+++ b/src/sentry/api/serializers/rest_framework/list.py
@@ -44,7 +44,9 @@ def format_child_errors(self):
return ', '.join(errors)
def validate(self, value):
- if not value and self.required:
+ # Allow empty lists when required=True unless child is also marked as required
+ if (value is None and self.required) or \
+ (not value and self.required and self.child and self.child.required):
raise ValidationError(self.error_messages['required'])
if not isinstance(value, list):
diff --git a/tests/sentry/api/endpoints/test_user_details.py b/tests/sentry/api/endpoints/test_user_details.py
index 122560e23294e9..bed8dcd2ca578c 100644
--- a/tests/sentry/api/endpoints/test_user_details.py
+++ b/tests/sentry/api/endpoints/test_user_details.py
@@ -240,3 +240,41 @@ def test_close_account(self):
assert Organization.objects.get(id=not_owned_org.id).status == OrganizationStatus.ACTIVE
assert response.status_code == 204
+
+ def test_close_account_no_orgs(self):
+ self.login_as(user=self.user)
+ org_single_owner = self.create_organization(name="A", owner=self.user)
+ user2 = self.create_user(email="[email protected]")
+ org_with_other_owner = self.create_organization(name="B", owner=self.user)
+ org_as_other_owner = self.create_organization(name="C", owner=user2)
+ not_owned_org = self.create_organization(name="D", owner=user2)
+
+ self.create_member(
+ user=user2,
+ organization=org_with_other_owner,
+ role='owner',
+ )
+
+ self.create_member(
+ user=self.user,
+ organization=org_as_other_owner,
+ role='owner',
+ )
+
+ url = reverse(
+ 'sentry-api-0-user-details', kwargs={
+ 'user_id': self.user.id,
+ }
+ )
+
+ response = self.client.delete(url, data={
+ 'organizations': []
+ })
+ assert response.status_code == 204
+
+ # deletes org_single_owner even though it wasn't specified in array
+ # because it has a single owner
+ assert Organization.objects.get(
+ id=org_single_owner.id).status == OrganizationStatus.PENDING_DELETION
+ # should NOT delete `not_owned_org`
+ assert Organization.objects.get(id=not_owned_org.id).status == OrganizationStatus.ACTIVE
|
77d5d87dbecb21925b8f49f2d0be75df314d0e0d
|
2019-01-17 01:22:57
|
Lyn Nagara
|
ref(issues): Refactor group similarity components (#11539)
| false
|
Refactor group similarity components (#11539)
|
ref
|
diff --git a/src/sentry/static/sentry/app/routes.jsx b/src/sentry/static/sentry/app/routes.jsx
index d00a5815ea9952..fd1d75ac5c4f1d 100644
--- a/src/sentry/static/sentry/app/routes.jsx
+++ b/src/sentry/static/sentry/app/routes.jsx
@@ -7,7 +7,7 @@ import ProjectGroupDetails from 'app/views/groupDetails/project/index';
import ProjectGroupEvents from 'app/views/groupDetails/project/groupEvents';
import ProjectGroupEventDetails from 'app/views/groupDetails/project/groupEventDetails';
import ProjectGroupMergedView from 'app/views/groupDetails/shared/groupMerged';
-import ProjectGroupSimilarView from 'app/views/groupDetails/project/groupSimilar';
+import ProjectGroupSimilarView from 'app/views/groupDetails/shared/groupSimilar';
import ProjectGroupTagValues from 'app/views/groupDetails/project/groupTagValues';
import ProjectGroupTags from 'app/views/groupDetails/project/groupTags';
import ProjectGroupUserFeedback from 'app/views/groupDetails/project/groupUserFeedback';
diff --git a/src/sentry/static/sentry/app/views/groupDetails/project/groupSimilar/index.jsx b/src/sentry/static/sentry/app/views/groupDetails/shared/groupSimilar/index.jsx
similarity index 86%
rename from src/sentry/static/sentry/app/views/groupDetails/project/groupSimilar/index.jsx
rename to src/sentry/static/sentry/app/views/groupDetails/shared/groupSimilar/index.jsx
index 5749f66795d91d..db82de1ee340c4 100644
--- a/src/sentry/static/sentry/app/views/groupDetails/project/groupSimilar/index.jsx
+++ b/src/sentry/static/sentry/app/views/groupDetails/shared/groupSimilar/index.jsx
@@ -5,12 +5,12 @@ import Reflux from 'reflux';
import createReactClass from 'create-react-class';
import queryString from 'query-string';
+import SentryTypes from 'app/sentryTypes';
import {t} from 'app/locale';
import GroupingActions from 'app/actions/groupingActions';
import GroupingStore from 'app/stores/groupingStore';
import LoadingError from 'app/components/loadingError';
import LoadingIndicator from 'app/components/loadingIndicator';
-import ProjectState from 'app/mixins/projectState';
import SimilarList from './similarList';
@@ -18,10 +18,11 @@ const GroupGroupingView = createReactClass({
displayName: 'GroupGroupingView',
propTypes: {
+ project: SentryTypes.Project,
query: PropTypes.string,
},
- mixins: [ProjectState, Reflux.listenTo(GroupingStore, 'onGroupingUpdate')],
+ mixins: [Reflux.listenTo(GroupingStore, 'onGroupingUpdate')],
getInitialState() {
return {
@@ -65,9 +66,10 @@ const GroupGroupingView = createReactClass({
} else if (mergedParent && mergedParent !== this.props.params.groupId) {
let {params} = this.props;
// Merge success, since we can't specify target, we need to redirect to new parent
- browserHistory.push(
- `/${params.orgId}/${params.projectId}/issues/${mergedParent}/similar/`
- );
+ let baseUrl = params.projectId
+ ? `/${params.orgId}/${params.projectId}/issues/`
+ : `/organizations/${params.orgId}/issues/`;
+ browserHistory.push(`${baseUrl}${mergedParent}/similar/`);
}
},
@@ -77,12 +79,15 @@ const GroupGroupingView = createReactClass({
...this.props.location.query,
limit: 50,
};
+
return `/issues/${params.groupId}/${type}/?${queryString.stringify(queryParams)}`;
},
- fetchData() {
- let projectFeatures = this.getProjectFeatures();
+ hasSimilarityFeature() {
+ return new Set(this.props.project.features).has('similarity-view');
+ },
+ fetchData() {
this.setState({
loading: true,
error: false,
@@ -90,7 +95,7 @@ const GroupGroupingView = createReactClass({
let reqs = [];
- if (projectFeatures.has('similarity-view')) {
+ if (this.hasSimilarityFeature()) {
reqs.push({
endpoint: this.getEndpoint('similar'),
dataKey: 'similar',
@@ -113,13 +118,12 @@ const GroupGroupingView = createReactClass({
},
render() {
- let {orgId, projectId, groupId} = this.props.params;
+ let {orgId, groupId} = this.props.params;
let isLoading = this.state.loading;
let isError = this.state.error && !isLoading;
let isLoadedSuccessfully = !isError && !isLoading;
- let projectFeatures = this.getProjectFeatures();
let hasSimilarItems =
- projectFeatures.has('similarity-view') &&
+ this.hasSimilarityFeature() &&
(this.state.similarItems.length >= 0 ||
this.state.filteredSimilarItems.length >= 0) &&
isLoadedSuccessfully;
@@ -147,7 +151,6 @@ const GroupGroupingView = createReactClass({
filteredItems={this.state.filteredSimilarItems}
onMerge={this.handleMerge}
orgId={orgId}
- projectId={projectId}
groupId={groupId}
pageLinks={this.state.similarLinks}
/>
diff --git a/src/sentry/static/sentry/app/views/groupDetails/project/groupSimilar/similarItem.jsx b/src/sentry/static/sentry/app/views/groupDetails/shared/groupSimilar/similarItem.jsx
similarity index 100%
rename from src/sentry/static/sentry/app/views/groupDetails/project/groupSimilar/similarItem.jsx
rename to src/sentry/static/sentry/app/views/groupDetails/shared/groupSimilar/similarItem.jsx
diff --git a/src/sentry/static/sentry/app/views/groupDetails/project/groupSimilar/similarList.jsx b/src/sentry/static/sentry/app/views/groupDetails/shared/groupSimilar/similarList.jsx
similarity index 97%
rename from src/sentry/static/sentry/app/views/groupDetails/project/groupSimilar/similarList.jsx
rename to src/sentry/static/sentry/app/views/groupDetails/shared/groupSimilar/similarList.jsx
index 007db8d23970b1..27ff1447ea6514 100644
--- a/src/sentry/static/sentry/app/views/groupDetails/project/groupSimilar/similarList.jsx
+++ b/src/sentry/static/sentry/app/views/groupDetails/shared/groupSimilar/similarList.jsx
@@ -22,9 +22,7 @@ const SimilarItemPropType = PropTypes.shape({
class SimilarList extends React.Component {
static propTypes = {
- orgId: PropTypes.string.isRequired,
groupId: PropTypes.string.isRequired,
- projectId: PropTypes.string.isRequired,
onMerge: PropTypes.func.isRequired,
pageLinks: PropTypes.string,
items: PropTypes.arrayOf(SimilarItemPropType),
diff --git a/src/sentry/static/sentry/app/views/groupDetails/project/groupSimilar/similarToolbar.jsx b/src/sentry/static/sentry/app/views/groupDetails/shared/groupSimilar/similarToolbar.jsx
similarity index 100%
rename from src/sentry/static/sentry/app/views/groupDetails/project/groupSimilar/similarToolbar.jsx
rename to src/sentry/static/sentry/app/views/groupDetails/shared/groupSimilar/similarToolbar.jsx
diff --git a/tests/js/spec/views/groupDetails/__snapshots__/groupSimilar.spec.jsx.snap b/tests/js/spec/views/groupDetails/__snapshots__/groupSimilar.spec.jsx.snap
index 74956a3aead997..21f173bb0d7e49 100644
--- a/tests/js/spec/views/groupDetails/__snapshots__/groupSimilar.spec.jsx.snap
+++ b/tests/js/spec/views/groupDetails/__snapshots__/groupSimilar.spec.jsx.snap
@@ -26,6 +26,21 @@ exports[`Issues Similar View renders with mocked data 1`] = `
"projectId": "project-slug",
}
}
+ project={
+ Object {
+ "features": Array [
+ "similarity-view",
+ ],
+ "hasAccess": true,
+ "id": "2",
+ "isBookmarked": false,
+ "isMember": true,
+ "name": "Project Name",
+ "slug": "project-slug",
+ "teams": Array [],
+ }
+ }
+ query=""
>
<div>
<div
@@ -281,7 +296,6 @@ exports[`Issues Similar View renders with mocked data 1`] = `
}
onMerge={[Function]}
orgId="org-slug"
- projectId="project-slug"
>
<div
className="similar-list-container"
diff --git a/tests/js/spec/views/groupDetails/groupSimilar.spec.jsx b/tests/js/spec/views/groupDetails/groupSimilar.spec.jsx
index 21915d19879c42..f67f01b570f10c 100644
--- a/tests/js/spec/views/groupDetails/groupSimilar.spec.jsx
+++ b/tests/js/spec/views/groupDetails/groupSimilar.spec.jsx
@@ -3,14 +3,11 @@ import React from 'react';
import {mount, shallow} from 'enzyme';
-import GroupSimilarView from 'app/views/groupDetails/project/groupSimilar';
+import GroupSimilar from 'app/views/groupDetails/shared/groupSimilar';
import issues from 'app-test/mocks/issues';
-jest.mock('app/mixins/projectState', () => {
- return {
- getFeatures: () => new Set([]),
- getProjectFeatures: () => new Set(['similarity-view']),
- };
+const project = TestStubs.Project({
+ features: ['similarity-view'],
});
const routerContext = TestStubs.routerContext([
@@ -47,7 +44,7 @@ describe('Issues Similar View', function() {
it('renders initially with loading component', function() {
let component = shallow(
- <GroupSimilarView params={{groupId: 'group-id'}} location={{}} />,
+ <GroupSimilar project={project} params={{groupId: 'group-id'}} location={{}} />,
routerContext
);
@@ -56,7 +53,9 @@ describe('Issues Similar View', function() {
it('renders with mocked data', async function() {
let wrapper = mount(
- <GroupSimilarView
+ <GroupSimilar
+ project={project}
+ query={''}
params={{orgId: 'org-slug', projectId: 'project-slug', groupId: 'group-id'}}
location={{}}
/>,
@@ -72,7 +71,8 @@ describe('Issues Similar View', function() {
it('can merge and redirect to new parent', async function() {
let wrapper = mount(
- <GroupSimilarView
+ <GroupSimilar
+ project={project}
params={{orgId: 'org-slug', projectId: 'project-slug', groupId: 'group-id'}}
location={{}}
/>,
|
746c20250f419a227bed0d174791e9c9b75daa13
|
2022-10-14 22:36:48
|
Armen Zambrano G
|
feat(github): Log Github integration errors (#39993)
| false
|
Log Github integration errors (#39993)
|
feat
|
diff --git a/src/sentry/integrations/github/webhook.py b/src/sentry/integrations/github/webhook.py
index cbdc1008dfb027..7bee3f156b988e 100644
--- a/src/sentry/integrations/github/webhook.py
+++ b/src/sentry/integrations/github/webhook.py
@@ -69,6 +69,7 @@ def __call__(self, event: Mapping[str, Any], host: str | None = None) -> None:
"external_id": str(external_id),
},
)
+ logger.exception("Integration does not exist.")
return
if "repository" in event:
@@ -137,6 +138,7 @@ def __call__(self, event: Mapping[str, Any], host: str | None = None) -> None:
"external_id": str(external_id),
},
)
+ logger.exception("Installation is missing.")
def _handle_delete(self, event: Mapping[str, Any], integration: Integration) -> None:
organizations = integration.organizations.all()
@@ -237,8 +239,8 @@ def _handle(
else:
try:
gh_user = client.get_user(gh_username)
- except ApiError as exc:
- logger.exception(str(exc))
+ except ApiError:
+ logger.exception("Github user is missing.")
else:
# even if we can't find a user, set to none so we
# don't re-query
@@ -469,6 +471,7 @@ def handle(self, request: Request) -> HttpResponse:
handler = self.get_handler(request.META["HTTP_X_GITHUB_EVENT"])
except KeyError:
logger.error("github.webhook.missing-event", extra=self.get_logging_data())
+ logger.exception("Missing Github event in webhook.")
return HttpResponse(status=400)
if not handler:
@@ -478,6 +481,7 @@ def handle(self, request: Request) -> HttpResponse:
method, signature = request.META["HTTP_X_HUB_SIGNATURE"].split("=", 1)
except (KeyError, IndexError):
logger.error("github.webhook.missing-signature", extra=self.get_logging_data())
+ logger.exception("Missing webhook secret.")
return HttpResponse(status=400)
if not self.is_valid_signature(method, body, secret, signature):
@@ -490,6 +494,7 @@ def handle(self, request: Request) -> HttpResponse:
logger.error(
"github.webhook.invalid-json", extra=self.get_logging_data(), exc_info=True
)
+ logger.exception("Invalid JSON.")
return HttpResponse(status=400)
handler()(event)
diff --git a/src/sentry/integrations/gitlab/webhooks.py b/src/sentry/integrations/gitlab/webhooks.py
index 699bba2e6770f2..30d97a52855d9d 100644
--- a/src/sentry/integrations/gitlab/webhooks.py
+++ b/src/sentry/integrations/gitlab/webhooks.py
@@ -10,7 +10,6 @@
from django.views.generic import View
from rest_framework.request import Request
from rest_framework.response import Response
-from sentry_sdk import capture_exception
from sentry.models import Commit, CommitAuthor, Integration, PullRequest, Repository
from sentry.plugins.providers import IntegrationRepositoryProvider
@@ -37,6 +36,7 @@ def get_repo(self, integration, organization, event):
logger.info(
"gitlab.webhook.missing-projectid", extra={"integration_id": integration.id}
)
+ logger.exception("Missing project ID.")
raise Http404()
external_id = "{}:{}".format(integration.metadata["instance"], project_id)
@@ -101,6 +101,7 @@ def __call__(self, integration, organization, event):
"gitlab.webhook.invalid-merge-data",
extra={"integration_id": integration.id, "error": str(e)},
)
+ logger.exception("Invalid merge data.")
# TODO(mgaeta): This try/catch is full of reportUnboundVariable errors.
return
@@ -211,20 +212,20 @@ def post(self, request: Request) -> Response:
# e.g. "example.gitlab.com:group-x:webhook_secret_from_sentry_integration_table"
instance, group_path, secret = token.split(":")
external_id = f"{instance}:{group_path}"
- except KeyError as e:
+ except KeyError:
logger.info("gitlab.webhook.missing-gitlab-token")
extra["reason"] = "The customer needs to set a Secret Token in their webhook."
- capture_exception(e)
+ logger.exception(extra["reason"])
return HttpResponse(status=400, reason=extra["reason"])
- except ValueError as e:
+ except ValueError:
logger.info("gitlab.webhook.malformed-gitlab-token", extra=extra)
extra["reason"] = "The customer's Secret Token is malformed."
- capture_exception(e)
+ logger.exception(extra["reason"])
return HttpResponse(status=400, reason=extra["reason"])
- except Exception as e:
+ except Exception:
logger.info("gitlab.webhook.invalid-token", extra=extra)
extra["reason"] = "Generic catch-all error."
- capture_exception(e)
+ logger.exception(extra["reason"])
return HttpResponse(status=400, reason=extra["reason"])
try:
@@ -253,42 +254,44 @@ def post(self, request: Request) -> Response:
"slugs": ",".join(map(lambda x: x.slug, integration.organizations.all())),
},
}
- except Integration.DoesNotExist as e:
+ except Integration.DoesNotExist:
logger.info("gitlab.webhook.invalid-organization", extra=extra)
extra["reason"] = "There is no integration that matches your organization."
- capture_exception(e)
+ logger.exception(extra["reason"])
return HttpResponse(status=400, reason=extra["reason"])
try:
if not constant_time_compare(secret, integration.metadata["webhook_secret"]):
+ # Summary and potential workaround mentioned here:
+ # https://github.com/getsentry/sentry/issues/34903#issuecomment-1262754478
# This forces a stack trace to be produced
raise Exception("The webhook secrets do not match.")
- except Exception as e:
+ except Exception:
logger.info("gitlab.webhook.invalid-token-secret", extra=extra)
extra[
"reason"
] = "Gitlab's webhook secret does not match. Refresh token (or re-install the integration) by following this https://docs.sentry.io/product/integrations/integration-platform/public-integration/#refreshing-tokens."
- capture_exception(e)
+ logger.exception(extra["reason"])
return HttpResponse(status=400, reason=extra["reason"])
try:
event = json.loads(request.body.decode("utf-8"))
- except json.JSONDecodeError as e:
+ except json.JSONDecodeError:
logger.info("gitlab.webhook.invalid-json", extra=extra)
extra["reason"] = "Data received is not JSON."
- capture_exception(e)
+ logger.exception(extra["reason"])
return HttpResponse(status=400, reason=extra["reason"])
try:
handler = self._handlers[request.META["HTTP_X_GITLAB_EVENT"]]
- except KeyError as e:
+ except KeyError:
logger.info("gitlab.webhook.wrong-event-type", extra=extra)
supported_events = ", ".join(sorted(self._handlers.keys()))
logger.info(f"We only support these kinds of events: {supported_events}")
extra[
"reason"
] = "The customer has edited the webhook in Gitlab to include other types of events."
- capture_exception(e)
+ logger.exception(extra["reason"])
return HttpResponse(status=400, reason=extra["reason"])
for organization in integration.organizations.all():
|
57367022f65ada2323fb40147b38e795f869f148
|
2022-07-14 13:03:25
|
josh
|
test: upgrade responses to latest (#36597)
| false
|
upgrade responses to latest (#36597)
|
test
|
diff --git a/requirements-dev-frozen.txt b/requirements-dev-frozen.txt
index c35170ac9b2b8d..c1dbbc085a6517 100644
--- a/requirements-dev-frozen.txt
+++ b/requirements-dev-frozen.txt
@@ -135,7 +135,7 @@ redis==3.4.1
redis-py-cluster==2.1.0
requests==2.25.1
requests-oauthlib==1.2.0
-responses==0.10.12
+responses==0.21.0
rfc3339-validator==0.1.2
rfc3986-validator==0.1.1
rsa==4.8
diff --git a/requirements-dev-only-frozen.txt b/requirements-dev-only-frozen.txt
index 5b98a0d8f9d08e..77ae34b40cf3f1 100644
--- a/requirements-dev-only-frozen.txt
+++ b/requirements-dev-only-frozen.txt
@@ -61,7 +61,7 @@ python-dateutil==2.8.2
pyupgrade==2.32.0
pyyaml==6.0
requests==2.27.1
-responses==0.10.12
+responses==0.21.0
sentry-sdk==1.6.0
six==1.16.0
tokenize-rt==4.2.1
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 572291ae013ff7..db735019978a2f 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -10,7 +10,7 @@ pytest-django>=4.4.0
pytest-rerunfailures>=9.1.1
pytest-sentry>=0.1.9
pytest-xdist
-responses>=0.10.12
+responses>=0.21.0
msgpack-types>=0.2.0
# pre-commit dependencies
diff --git a/tests/sentry/api/endpoints/test_sentry_app_installation_external_requests.py b/tests/sentry/api/endpoints/test_sentry_app_installation_external_requests.py
index 8ac00ed22a84f1..fee4bba64dbda4 100644
--- a/tests/sentry/api/endpoints/test_sentry_app_installation_external_requests.py
+++ b/tests/sentry/api/endpoints/test_sentry_app_installation_external_requests.py
@@ -1,6 +1,7 @@
import responses
from django.urls import reverse
from django.utils.http import urlencode
+from responses.matchers import query_string_matcher
from sentry.testutils import APITestCase
from sentry.utils import json
@@ -30,11 +31,15 @@ def test_makes_external_request(self):
options = [{"label": "Project Name", "value": "1234"}]
responses.add(
method=responses.GET,
- url=f"https://example.com/get-projects?projectSlug={self.project.slug}&installationId={self.install.uuid}&query=proj",
+ url="https://example.com/get-projects",
+ match=[
+ query_string_matcher(
+ f"projectSlug={self.project.slug}&installationId={self.install.uuid}&query=proj"
+ )
+ ],
json=options,
status=200,
content_type="application/json",
- match_querystring=True,
)
url = self.url + f"?projectId={self.project.id}&uri=/get-projects&query=proj"
response = self.client.get(url, format="json")
@@ -45,27 +50,31 @@ def test_makes_external_request(self):
def test_makes_external_request_with_dependent_data(self):
self.login_as(user=self.user)
options = [{"label": "Project Name", "value": "1234"}]
- query = {
- "projectSlug": self.project.slug,
- "installationId": self.install.uuid,
- "query": "proj",
- "dependentData": json.dumps({"org_id": "A"}),
- }
+ qs = urlencode(
+ {
+ "projectSlug": self.project.slug,
+ "installationId": self.install.uuid,
+ "query": "proj",
+ "dependentData": json.dumps({"org_id": "A"}),
+ }
+ )
responses.add(
method=responses.GET,
- url="https://example.com/get-projects?%s" % urlencode(query),
+ url="https://example.com/get-projects",
+ match=[query_string_matcher(qs)],
json=options,
status=200,
content_type="application/json",
- match_querystring=True,
)
- query = {
- "projectId": self.project.id,
- "uri": "/get-projects",
- "query": "proj",
- "dependentData": json.dumps({"org_id": "A"}),
- }
- url = f"{self.url}?{urlencode(query)}"
+ qs = urlencode(
+ {
+ "projectId": self.project.id,
+ "uri": "/get-projects",
+ "query": "proj",
+ "dependentData": json.dumps({"org_id": "A"}),
+ }
+ )
+ url = f"{self.url}?{qs}"
response = self.client.get(url, format="json")
assert response.status_code == 200
assert response.data == {"choices": [["1234", "Project Name"]]}
diff --git a/tests/sentry/integrations/github_enterprise/test_integration.py b/tests/sentry/integrations/github_enterprise/test_integration.py
index ff5da0149216eb..72360132dc3c70 100644
--- a/tests/sentry/integrations/github_enterprise/test_integration.py
+++ b/tests/sentry/integrations/github_enterprise/test_integration.py
@@ -98,7 +98,6 @@ def assert_setup_flow(
responses.GET,
self.base_url + "/user/installations",
json={"installations": [{"id": installation_id}]},
- match_querystring=True,
)
resp = self.client.get(
diff --git a/tests/sentry/integrations/gitlab/test_search.py b/tests/sentry/integrations/gitlab/test_search.py
index e4b1c5e924d1ee..e189b4fe66639f 100644
--- a/tests/sentry/integrations/gitlab/test_search.py
+++ b/tests/sentry/integrations/gitlab/test_search.py
@@ -107,7 +107,6 @@ def request_callback(request):
responses.GET,
"https://example.gitlab.com/api/v4/groups/1/projects",
callback=request_callback,
- match_querystring=False,
)
resp = self.client.get(self.url, data={"field": "project", "query": "GetSentry"})
diff --git a/tests/sentry/integrations/jira/test_client.py b/tests/sentry/integrations/jira/test_client.py
index cc9dc20cf06cbc..c191cd71402d73 100644
--- a/tests/sentry/integrations/jira/test_client.py
+++ b/tests/sentry/integrations/jira/test_client.py
@@ -1,6 +1,7 @@
from unittest import mock
import responses
+from responses.matchers import query_string_matcher
from sentry.integrations.jira.client import JiraCloud
from sentry.models import Integration
@@ -37,11 +38,11 @@ def test_get_field_autocomplete_for_non_customfield(self):
body = {"results": [{"value": "ISSUE-1", "displayName": "My Issue (ISSUE-1)"}]}
responses.add(
method=responses.GET,
- url="https://example.atlassian.net/rest/api/2/jql/autocompletedata/suggestions?fieldName=my_field&fieldValue=abc&jwt=my-jwt-token",
+ url="https://example.atlassian.net/rest/api/2/jql/autocompletedata/suggestions",
+ match=[query_string_matcher("fieldName=my_field&fieldValue=abc&jwt=my-jwt-token")],
body=json.dumps(body),
status=200,
content_type="application/json",
- match_querystring=True,
)
res = self.client.get_field_autocomplete("my_field", "abc")
assert res == body
@@ -51,11 +52,11 @@ def test_get_field_autocomplete_for_customfield(self):
body = {"results": [{"value": "ISSUE-1", "displayName": "My Issue (ISSUE-1)"}]}
responses.add(
method=responses.GET,
- url="https://example.atlassian.net/rest/api/2/jql/autocompletedata/suggestions?fieldName=cf[0123]&fieldValue=abc&jwt=my-jwt-token",
+ url="https://example.atlassian.net/rest/api/2/jql/autocompletedata/suggestions",
+ match=[query_string_matcher("fieldName=cf[0123]&fieldValue=abc&jwt=my-jwt-token")],
body=json.dumps(body),
status=200,
content_type="application/json",
- match_querystring=True,
)
res = self.client.get_field_autocomplete("customfield_0123", "abc")
assert res == body
diff --git a/tests/sentry/integrations/jira/test_integration.py b/tests/sentry/integrations/jira/test_integration.py
index 7f6f216459dadb..934bd2bf9befeb 100644
--- a/tests/sentry/integrations/jira/test_integration.py
+++ b/tests/sentry/integrations/jira/test_integration.py
@@ -421,7 +421,6 @@ def test_get_create_issue_config__no_projects(self):
responses.GET,
"https://example.atlassian.net/rest/api/2/project",
content_type="json",
- match_querystring=False,
body="{}",
)
with pytest.raises(IntegrationError):
@@ -439,7 +438,6 @@ def test_get_create_issue_config__no_issue_config(self):
responses.GET,
"https://example.atlassian.net/rest/api/2/project",
content_type="json",
- match_querystring=False,
body="""[
{"id": "10000", "key": "SAMP"}
]""",
@@ -449,7 +447,6 @@ def test_get_create_issue_config__no_issue_config(self):
responses.GET,
"https://example.atlassian.net/rest/api/2/issue/createmeta",
content_type="json",
- match_querystring=False,
status=401,
body="",
)
@@ -500,14 +497,12 @@ def test_create_issue_labels_and_option(self):
"https://example.atlassian.net/rest/api/2/issue/createmeta",
body=StubService.get_stub_json("jira", "createmeta_response.json"),
content_type="json",
- match_querystring=False,
)
responses.add(
responses.GET,
"https://example.atlassian.net/rest/api/2/issue/APP-123",
body=StubService.get_stub_json("jira", "get_issue_response.json"),
content_type="json",
- match_querystring=False,
)
def responder(request):
@@ -524,7 +519,6 @@ def responder(request):
responses.POST,
"https://example.atlassian.net/rest/api/2/issue",
callback=responder,
- match_querystring=False,
)
result = installation.create_issue(
@@ -582,9 +576,8 @@ def test_sync_assignee_outbound_case_insensitive(self):
responses.GET,
"https://example.atlassian.net/rest/api/2/user/assignable/search",
json=[{"accountId": "deadbeef123", "emailAddress": "[email protected]"}],
- match_querystring=False,
)
- responses.add(responses.PUT, assign_issue_url, json={}, match_querystring=False)
+ responses.add(responses.PUT, assign_issue_url, json={})
installation.sync_assignee_outbound(external_issue, self.user)
assert len(responses.calls) == 2
@@ -607,7 +600,6 @@ def test_sync_assignee_outbound_no_email(self):
responses.GET,
"https://example.atlassian.net/rest/api/2/user/assignable/search",
json=[{"accountId": "deadbeef123", "displayName": "Dead Beef"}],
- match_querystring=False,
)
installation.sync_assignee_outbound(external_issue, self.user)
@@ -628,16 +620,14 @@ def test_sync_assignee_outbound_use_email_api(self):
responses.GET,
"https://example.atlassian.net/rest/api/2/user/assignable/search",
json=[{"accountId": "deadbeef123", "displayName": "Dead Beef", "emailAddress": ""}],
- match_querystring=False,
)
responses.add(
responses.GET,
"https://example.atlassian.net/rest/api/3/user/email",
json={"accountId": "deadbeef123", "email": "[email protected]"},
- match_querystring=False,
)
- responses.add(responses.PUT, assign_issue_url, json={}, match_querystring=False)
+ responses.add(responses.PUT, assign_issue_url, json={})
installation.sync_assignee_outbound(external_issue, self.user)
diff --git a/tests/sentry/integrations/jira/test_notify_action.py b/tests/sentry/integrations/jira/test_notify_action.py
index 514912b0439a93..fc10777967e20a 100644
--- a/tests/sentry/integrations/jira/test_notify_action.py
+++ b/tests/sentry/integrations/jira/test_notify_action.py
@@ -33,7 +33,6 @@ def test_creates_issue(self):
"https://example.atlassian.net/rest/api/2/project",
body=StubService.get_stub_json("jira", "project_list_response.json"),
content_type="application/json",
- match_querystring=False,
)
responses.add(
@@ -41,7 +40,6 @@ def test_creates_issue(self):
"https://example.atlassian.net/rest/api/2/issue/createmeta",
body=StubService.get_stub_json("jira", "createmeta_response.json"),
content_type="json",
- match_querystring=False,
)
jira_rule = self.get_rule(
data={
@@ -76,7 +74,6 @@ def test_creates_issue(self):
"https://example.atlassian.net/rest/api/2/issue/APP-123",
body=StubService.get_stub_json("jira", "get_issue_response.json"),
content_type="application/json",
- match_querystring=False,
)
results = list(jira_rule.after(event=event, state=self.get_state()))
diff --git a/tests/sentry/integrations/jira/test_search_endpoint.py b/tests/sentry/integrations/jira/test_search_endpoint.py
index 4b684c4c8d6ca4..1ab829adce8e45 100644
--- a/tests/sentry/integrations/jira/test_search_endpoint.py
+++ b/tests/sentry/integrations/jira/test_search_endpoint.py
@@ -32,7 +32,6 @@ def test_issue_search_text(self):
"https://example.atlassian.net/rest/api/2/search/",
body=StubService.get_stub_json("jira", "search_response.json"),
content_type="json",
- match_querystring=False,
)
org = self.organization
self.login_as(self.user)
@@ -55,7 +54,6 @@ def responder(request):
responses.GET,
"https://example.atlassian.net/rest/api/2/search/",
callback=responder,
- match_querystring=False,
)
org = self.organization
self.login_as(self.user)
@@ -77,7 +75,6 @@ def test_issue_search_error(self):
"https://example.atlassian.net/rest/api/2/search/",
status=500,
body="Totally broken",
- match_querystring=False,
)
org = self.organization
self.login_as(self.user)
@@ -97,7 +94,6 @@ def test_assignee_search(self):
responses.GET,
"https://example.atlassian.net/rest/api/2/project",
json=[{"key": "HSP", "id": "10000"}],
- match_querystring=False,
)
def responder(request):
@@ -112,7 +108,6 @@ def responder(request):
"https://example.atlassian.net/rest/api/2/user/assignable/search",
callback=responder,
content_type="json",
- match_querystring=False,
)
org = self.organization
self.login_as(self.user)
@@ -129,14 +124,12 @@ def test_assignee_search_error(self):
responses.GET,
"https://example.atlassian.net/rest/api/2/project",
json=[{"key": "HSP", "id": "10000"}],
- match_querystring=False,
)
responses.add(
responses.GET,
"https://example.atlassian.net/rest/api/2/user/assignable/search",
status=500,
body="Bad things",
- match_querystring=False,
)
org = self.organization
self.login_as(self.user)
@@ -159,7 +152,6 @@ def responder(request):
"https://example.atlassian.net/rest/api/2/jql/autocompletedata/suggestions",
callback=responder,
content_type="application/json",
- match_querystring=False,
)
org = self.organization
self.login_as(self.user)
@@ -177,7 +169,6 @@ def test_customfield_search_error(self):
"https://example.atlassian.net/rest/api/2/jql/autocompletedata/suggestions",
status=500,
body="Totally broken",
- match_querystring=False,
)
org = self.organization
self.login_as(self.user)
diff --git a/tests/sentry/integrations/jira/test_webhooks.py b/tests/sentry/integrations/jira/test_webhooks.py
index 1096624bb2aa60..e4f8d59d99439c 100644
--- a/tests/sentry/integrations/jira/test_webhooks.py
+++ b/tests/sentry/integrations/jira/test_webhooks.py
@@ -49,7 +49,6 @@ def test_assign_use_email_api(self, mock_sync_group_assignee_inbound):
responses.GET,
"https://example.atlassian.net/rest/api/3/user/email",
json={"accountId": "deadbeef123", "email": self.user.email},
- match_querystring=False,
)
with patch(
@@ -69,7 +68,6 @@ def test_assign_use_email_api_error(self):
responses.GET,
"https://example.atlassian.net/rest/api/3/user/email",
status=500,
- match_querystring=False,
)
with patch(
diff --git a/tests/sentry/integrations/jira_server/test_search.py b/tests/sentry/integrations/jira_server/test_search.py
index b1555ed6ed2d56..9579caa8ea6380 100644
--- a/tests/sentry/integrations/jira_server/test_search.py
+++ b/tests/sentry/integrations/jira_server/test_search.py
@@ -82,7 +82,6 @@ def test_assignee_search(self):
responses.GET,
"https://jira.example.org/rest/api/2/project",
json=[{"key": "HSP", "id": "10000"}],
- match_querystring=False,
)
def responder(request):
@@ -96,7 +95,6 @@ def responder(request):
"https://jira.example.org/rest/api/2/user/assignable/search",
callback=responder,
content_type="json",
- match_querystring=False,
)
org = self.organization
self.login_as(self.user)
@@ -113,14 +111,12 @@ def test_assignee_search_error(self):
responses.GET,
"https://jira.example.org/rest/api/2/project",
json=[{"key": "HSP", "id": "10000"}],
- match_querystring=False,
)
responses.add(
responses.GET,
"https://jira.example.org/rest/api/2/user/assignable/search",
status=500,
body="Bad things",
- match_querystring=False,
)
org = self.organization
self.login_as(self.user)
diff --git a/tests/sentry/integrations/slack/test_integration.py b/tests/sentry/integrations/slack/test_integration.py
index 4e1bf246cfb370..4bb90b69af576b 100644
--- a/tests/sentry/integrations/slack/test_integration.py
+++ b/tests/sentry/integrations/slack/test_integration.py
@@ -1,6 +1,7 @@
from urllib.parse import parse_qs, urlencode, urlparse
import responses
+from responses.matchers import query_string_matcher
from sentry import audit_log
from sentry.integrations.slack import SlackIntegration, SlackIntegrationProvider
@@ -57,8 +58,8 @@ def assert_setup_flow(
responses.add(
method=responses.GET,
- url=f"https://slack.com/api/users.list?limit={SLACK_GET_USERS_PAGE_SIZE}",
- match_querystring=True,
+ url="https://slack.com/api/users.list",
+ match=[query_string_matcher(f"limit={SLACK_GET_USERS_PAGE_SIZE}")],
json={
"ok": True,
"members": [
@@ -224,8 +225,8 @@ def setUp(self):
responses.add(
method=responses.GET,
- url=f"https://slack.com/api/users.list?limit={SLACK_GET_USERS_PAGE_SIZE}",
- match_querystring=True,
+ url="https://slack.com/api/users.list",
+ match=[query_string_matcher(f"limit={SLACK_GET_USERS_PAGE_SIZE}")],
json={
"ok": True,
"members": [
diff --git a/tests/sentry/integrations/vsts/test_issues.py b/tests/sentry/integrations/vsts/test_issues.py
index bce510c664b1e7..76006fae66a07b 100644
--- a/tests/sentry/integrations/vsts/test_issues.py
+++ b/tests/sentry/integrations/vsts/test_issues.py
@@ -4,6 +4,7 @@
import responses
from django.test import RequestFactory
from exam import fixture
+from responses.matchers import query_string_matcher
from fixtures.vsts import (
GET_PROJECTS_RESPONSE,
@@ -230,14 +231,13 @@ def test_sync_assignee_outbound_with_paging(self):
]
},
headers={"X-MS-ContinuationToken": "continuation-token"},
- match_querystring=True,
)
responses.add(
responses.GET,
- "https://fabrikam-fiber-inc.vssps.visualstudio.com/_apis/graph/users?continuationToken=continuation-token",
+ "https://fabrikam-fiber-inc.vssps.visualstudio.com/_apis/graph/users",
+ match=[query_string_matcher("continuationToken=continuation-token")],
body=GET_USERS_RESPONSE,
content_type="application/json",
- match_querystring=True,
)
user = self.create_user("[email protected]")
diff --git a/tests/sentry/utils/appleconnect/test_appstore_connect.py b/tests/sentry/utils/appleconnect/test_appstore_connect.py
index 12583050eafb10..3e1d58ad61e58b 100644
--- a/tests/sentry/utils/appleconnect/test_appstore_connect.py
+++ b/tests/sentry/utils/appleconnect/test_appstore_connect.py
@@ -12,7 +12,7 @@
import pytest
import requests
-import responses as responses_mod # type: ignore
+import responses as responses_mod
from sentry.lang.native.appconnect import NoDsymUrl
from sentry.utils import json
diff --git a/tests/sentry_plugins/gitlab/test_plugin.py b/tests/sentry_plugins/gitlab/test_plugin.py
index 7b352ce962dc80..d7bea9aa7f06c0 100644
--- a/tests/sentry_plugins/gitlab/test_plugin.py
+++ b/tests/sentry_plugins/gitlab/test_plugin.py
@@ -80,7 +80,6 @@ def test_link_issue(self):
responses.GET,
"https://gitlab.com/api/v4/projects/getsentry%2Fsentry/issues/1",
body='{"iid": 1, "id": "10", "title": "Hello world"}',
- match_querystring=True,
)
responses.add(
responses.POST,
|
c1c64c2924f9c816febbd6b4ca489de022ba57d2
|
2024-07-25 05:10:12
|
Malachi Willey
|
feat(query-builder): Add feature flags for enabling in other surfaces (#74919)
| false
|
Add feature flags for enabling in other surfaces (#74919)
|
feat
|
diff --git a/src/sentry/features/temporary.py b/src/sentry/features/temporary.py
index e955f77d1bca67..fee7a2adf2d756 100644
--- a/src/sentry/features/temporary.py
+++ b/src/sentry/features/temporary.py
@@ -161,6 +161,18 @@ def register_temporary_features(manager: FeatureManager):
manager.add("organizations:issue-search-snuba", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=False)
# Enable the new issue stream search bar UI
manager.add("organizations:issue-stream-search-query-builder", OrganizationFeature, FeatureHandlerStrategy.REMOTE, api_expose=True)
+ # Enable the new search bar UI in other pages
+ manager.add("organizations:search-query-builder-releases", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
+ manager.add("organizations:search-query-builder-traces", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
+ manager.add("organizations:search-query-builder-metrics", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
+ manager.add("organizations:search-query-builder-profiles", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
+ manager.add("organizations:search-query-builder-replays", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
+ manager.add("organizations:search-query-builder-discover", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
+ manager.add("organizations:search-query-builder-user-feedback", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
+ manager.add("organizations:search-query-builder-dashboards", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
+ manager.add("organizations:search-query-builder-project-details", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
+ manager.add("organizations:search-query-builder-alerts", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
+ manager.add("organizations:search-query-builder-performance", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
manager.add("organizations:large-debug-files", OrganizationFeature, FeatureHandlerStrategy.INTERNAL, api_expose=False)
# Enable v8 support for the Loader Script
manager.add("organizations:js-sdk-loader-v8", OrganizationFeature, FeatureHandlerStrategy.REMOTE, api_expose=False)
|
499d81c3902d5f434baa72fac38cf70debb320c5
|
2024-07-01 18:09:46
|
Ogi
|
ref(on-demand-metrics): remove alert spec limit default (#73567)
| false
|
remove alert spec limit default (#73567)
|
ref
|
diff --git a/src/sentry/relay/config/metric_extraction.py b/src/sentry/relay/config/metric_extraction.py
index f818ccffa7edb5..553c44d65e5f9f 100644
--- a/src/sentry/relay/config/metric_extraction.py
+++ b/src/sentry/relay/config/metric_extraction.py
@@ -63,10 +63,6 @@
# Version of the metric extraction config.
_METRIC_EXTRACTION_VERSION = 4
-# Maximum number of custom metrics that can be extracted for alerts and widgets with
-# advanced filter expressions.
-_MAX_ON_DEMAND_ALERTS = 50
-
# TTL for cardinality check
_WIDGET_QUERY_CARDINALITY_TTL = 3600 * 24 # 24h
_WIDGET_QUERY_CARDINALITY_SOFT_DEADLINE_TTL = 3600 * 0.5 # 30m
@@ -205,7 +201,7 @@ def _get_alert_metric_specs(
)
specs.append(spec)
- max_alert_specs = options.get("on_demand.max_alert_specs") or _MAX_ON_DEMAND_ALERTS
+ max_alert_specs = options.get("on_demand.max_alert_specs")
(specs, _) = _trim_if_above_limit(specs, max_alert_specs, project, "alerts")
return specs
|
b1c046d55184a4b0b26d551ec5806d5bfbef6189
|
2024-02-27 01:13:22
|
Yash Kamothi
|
feat(integrations): Reply in threads for notifications (#65557)
| false
|
Reply in threads for notifications (#65557)
|
feat
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index 2b072f88d644b6..79cbe39e664926 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -1872,6 +1872,8 @@ def custom_parameter_sort(parameter: dict) -> tuple[str, int]:
"organizations:slack-block-kit": False,
# Improvements to Slack messages using Block Kit
"organizations:slack-block-kit-improvements": False,
+ # Send Slack notifications to threads
+ "organizations:slack-thread": False,
# Enable basic SSO functionality, providing configurable single sign on
# using services like GitHub / Google. This is *not* the same as the signup
# and login with Github / Azure DevOps that sentry.io provides.
diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py
index 876f13be043160..b46d5d78407c8c 100644
--- a/src/sentry/features/__init__.py
+++ b/src/sentry/features/__init__.py
@@ -250,6 +250,7 @@
default_manager.add("organizations:set-grouping-config", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
default_manager.add("organizations:settings-legal-tos-ui", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:slack-block-kit", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
+default_manager.add("organizations:slack-thread", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:slack-block-kit-improvements", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
default_manager.add("organizations:slack-overage-notifications", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:source-maps-debugger-blue-thunder-edition", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
diff --git a/src/sentry/integrations/repository/__init__.py b/src/sentry/integrations/repository/__init__.py
new file mode 100644
index 00000000000000..e95f34601d5ab2
--- /dev/null
+++ b/src/sentry/integrations/repository/__init__.py
@@ -0,0 +1,22 @@
+"""
+The repository classes are responsible for the interactions with the data store for the NotificationMessage data model.
+The classes help separate the query interface with the actual data store for the NotificationMessage data model.
+
+If we scale quickly, the current NotificationMessage data model will have to shift from django postgres to
+snuba clickhouse, and these classes will help keep the changes consolidated to here.
+For self-hosted, if the user wants to utilize another datastore, they are able to do so.
+
+What we query from an interface level won't change, simply how we query will change, and these classes should be the
+only thing that need to change after we make the migration.
+"""
+from sentry.integrations.repository.metric_alert import MetricAlertNotificationMessageRepository
+
+_default_metric_alert_repository = None
+
+
+def get_default_metric_alert_repository() -> MetricAlertNotificationMessageRepository:
+ global _default_metric_alert_repository
+ if _default_metric_alert_repository is None:
+ _default_metric_alert_repository = MetricAlertNotificationMessageRepository.default()
+
+ return _default_metric_alert_repository
diff --git a/src/sentry/integrations/repository/base.py b/src/sentry/integrations/repository/base.py
new file mode 100644
index 00000000000000..6e49524e20f9d1
--- /dev/null
+++ b/src/sentry/integrations/repository/base.py
@@ -0,0 +1,32 @@
+from dataclasses import dataclass
+from datetime import datetime
+from typing import Any
+
+
+@dataclass(frozen=True)
+class BaseNotificationMessage:
+ """
+ This dataclass represents a notification message domain object.
+ The data in this instance should not change, as it is populated from a datastore,
+ which is why it's a frozen data set.
+ """
+
+ id: int
+ date_added: datetime
+ error_details: dict[str, Any] | None = None
+ error_code: int | None = None
+ message_identifier: str | None = None
+ parent_notification_message_id: int | None = None
+
+
+@dataclass
+class BaseNewNotificationMessage:
+ """
+ This dataclass represents a new, outgoing, notification message domain object that will get reflected in the
+ datastore. The caller can define what that data looks like and which fields should be populated.
+ """
+
+ error_details: dict[str, Any] | None = None
+ error_code: int | None = None
+ message_identifier: str | None = None
+ parent_notification_message_id: int | None = None
diff --git a/src/sentry/integrations/repository/issue_alert.py b/src/sentry/integrations/repository/issue_alert.py
new file mode 100644
index 00000000000000..3c9cd8361fa802
--- /dev/null
+++ b/src/sentry/integrations/repository/issue_alert.py
@@ -0,0 +1,23 @@
+from __future__ import annotations
+
+from logging import Logger, getLogger
+
+from sentry.models.notificationmessage import NotificationMessage
+
+_default_logger: Logger = getLogger(__name__)
+
+
+class IssueAlertNotificationMessageRepository:
+ """
+ Repository class that is responsible for querying the data store for notification messages in relation to issue
+ alerts.
+ """
+
+ _model = NotificationMessage
+
+ def __init__(self, logger: Logger) -> None:
+ self._logger: Logger = logger
+
+ @classmethod
+ def default(cls) -> IssueAlertNotificationMessageRepository:
+ return cls(logger=_default_logger)
diff --git a/src/sentry/integrations/repository/metric_alert.py b/src/sentry/integrations/repository/metric_alert.py
new file mode 100644
index 00000000000000..21bd2b7339680d
--- /dev/null
+++ b/src/sentry/integrations/repository/metric_alert.py
@@ -0,0 +1,145 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from logging import Logger, getLogger
+
+from sentry.incidents.models import AlertRuleTriggerAction, Incident
+from sentry.integrations.repository.base import BaseNewNotificationMessage, BaseNotificationMessage
+from sentry.models.notificationmessage import NotificationMessage
+
+_default_logger: Logger = getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class MetricAlertNotificationMessage(BaseNotificationMessage):
+ incident: Incident | None = None
+ trigger_action: AlertRuleTriggerAction | None = None
+
+ @classmethod
+ def from_model(cls, instance: NotificationMessage) -> MetricAlertNotificationMessage:
+ return MetricAlertNotificationMessage(
+ id=instance.id,
+ error_code=instance.error_code,
+ error_details=instance.error_details,
+ message_identifier=instance.message_identifier,
+ parent_notification_message_id=instance.parent_notification_message.id
+ if instance.parent_notification_message
+ else None,
+ incident=instance.incident,
+ trigger_action=instance.trigger_action,
+ date_added=instance.date_added,
+ )
+
+
+class NewMetricAlertNotificationMessageValidationError(Exception):
+ pass
+
+
+class IncidentAndTriggerActionValidationError(NewMetricAlertNotificationMessageValidationError):
+ message = "both incident and trigger action need to exist together with a reference"
+
+
+class MessageIdentifierWithErrorValidationError(NewMetricAlertNotificationMessageValidationError):
+ message = (
+ "cannot create a new notification message with message identifier when an error exists"
+ )
+
+
+@dataclass
+class NewMetricAlertNotificationMessage(BaseNewNotificationMessage):
+ incident_id: int | None = None
+ trigger_action_id: int | None = None
+
+ def get_validation_error(self) -> Exception | None:
+ """
+ Helper method for getting any potential validation errors based on the state of the data.
+ There are particular restrictions about the various fields, and this is to help the user check before
+ trying to instantiate a new instance in the datastore.
+ """
+ if self.message_identifier is not None:
+ if self.error_code is not None or self.error_details is not None:
+ return MessageIdentifierWithErrorValidationError()
+
+ if self.incident_id is None or self.trigger_action_id is None:
+ return IncidentAndTriggerActionValidationError()
+
+ incident_exists_without_trigger = (
+ self.incident_id is not None and self.trigger_action_id is None
+ )
+ trigger_exists_without_incident = (
+ self.incident_id is None and self.trigger_action_id is not None
+ )
+ if incident_exists_without_trigger or trigger_exists_without_incident:
+ return IncidentAndTriggerActionValidationError()
+
+ return None
+
+
+class MetricAlertNotificationMessageRepository:
+ """
+ Repository class that is responsible for querying the data store for notification messages in relation to metric
+ alerts.
+ """
+
+ _model = NotificationMessage
+
+ def __init__(self, logger: Logger) -> None:
+ self._logger: Logger = logger
+
+ @classmethod
+ def default(cls) -> MetricAlertNotificationMessageRepository:
+ return cls(logger=_default_logger)
+
+ def get_parent_notification_message(
+ self, alert_rule_id: int, incident_id: int, trigger_action_id: int
+ ) -> MetricAlertNotificationMessage | None:
+ """
+ Returns the parent notification message for a metric rule if it exists, otherwise returns None.
+ Will raise an exception if the query fails and logs the error with associated data.
+ """
+ try:
+ instance: NotificationMessage = self._model.objects.get(
+ incident__alert_rule__id=alert_rule_id,
+ incident__id=incident_id,
+ trigger_action__id=trigger_action_id,
+ parent_notification_message__isnull=True,
+ error_code__isnull=True,
+ )
+ return MetricAlertNotificationMessage.from_model(instance=instance)
+ except NotificationMessage.DoesNotExist:
+ return None
+ except Exception as e:
+ self._logger.exception(
+ "Failed to get parent notification for metric rule",
+ exc_info=e,
+ extra={
+ "incident_id": incident_id,
+ "alert_rule_id": alert_rule_id,
+ "trigger_action_id": trigger_action_id,
+ },
+ )
+ raise
+
+ def create_notification_message(
+ self, data: NewMetricAlertNotificationMessage
+ ) -> MetricAlertNotificationMessage:
+ if (error := data.get_validation_error()) is not None:
+ raise error
+
+ try:
+ new_instance = self._model.objects.create(
+ error_details=data.error_details,
+ error_code=data.error_code,
+ message_identifier=data.message_identifier,
+ parent_notification_message_id=data.parent_notification_message_id,
+ incident_id=data.incident_id,
+ trigger_action_id=data.trigger_action_id,
+ )
+ return MetricAlertNotificationMessage.from_model(instance=new_instance)
+ except Exception as e:
+ self._logger.exception(
+ "failed to create new metric alert notification alert",
+ exc_info=e,
+ extra=data.__dict__,
+ )
+ raise
diff --git a/src/sentry/integrations/slack/utils/notifications.py b/src/sentry/integrations/slack/utils/notifications.py
index 1a77b15a7882d0..ad1c13dec03c80 100644
--- a/src/sentry/integrations/slack/utils/notifications.py
+++ b/src/sentry/integrations/slack/utils/notifications.py
@@ -9,11 +9,17 @@
from sentry.constants import ObjectStatus
from sentry.incidents.charts import build_metric_alert_chart
from sentry.incidents.models import AlertRuleTriggerAction, Incident, IncidentStatus
+from sentry.integrations.repository import get_default_metric_alert_repository
+from sentry.integrations.repository.metric_alert import (
+ MetricAlertNotificationMessageRepository,
+ NewMetricAlertNotificationMessage,
+)
from sentry.integrations.slack.client import SlackClient
from sentry.integrations.slack.message_builder.incidents import SlackIncidentsMessageBuilder
from sentry.models.integrations.integration import Integration
from sentry.services.hybrid_cloud.integration import integration_service
from sentry.shared_integrations.exceptions import ApiError
+from sentry.shared_integrations.response import BaseApiResponse, MappingApiResponse
from sentry.utils import json
from . import logger
@@ -34,11 +40,12 @@ def send_incident_alert_notification(
# Integration removed, but rule is still active.
return False
+ organization = incident.organization
chart_url = None
if features.has("organizations:metric-alert-chartcuterie", incident.organization):
try:
chart_url = build_metric_alert_chart(
- organization=incident.organization,
+ organization=organization,
alert_rule=incident.alert_rule,
selected_incident=incident,
)
@@ -62,13 +69,81 @@ def send_incident_alert_notification(
"unfurl_media": False,
}
+ repository: MetricAlertNotificationMessageRepository = get_default_metric_alert_repository()
+ parent_notification_message = None
+ if features.has("organizations:slack-thread", organization):
+ try:
+ parent_notification_message = repository.get_parent_notification_message(
+ alert_rule_id=incident.alert_rule_id,
+ incident_id=incident.id,
+ trigger_action_id=action.id,
+ )
+ except Exception:
+ # if there's an error trying to grab a parent notification, don't let that error block this flow
+ pass
+
+ new_notification_message_object = NewMetricAlertNotificationMessage(
+ incident_id=incident.id,
+ trigger_action_id=action.id,
+ )
+
+ # Only reply and use threads if the organization is enabled in the FF
+ if features.has("organizations:slack-thread", organization):
+ # If a parent notification exists for this rule and action, then we can reply in a thread
+ if parent_notification_message is not None:
+ # Make sure we track that this reply will be in relation to the parent row
+ new_notification_message_object.parent_notification_message_id = (
+ parent_notification_message.id
+ )
+ # To reply to a thread, use the specific key in the payload as referenced by the docs
+ # https://api.slack.com/methods/chat.postMessage#arg_thread_ts
+ payload["thread_ts"] = parent_notification_message.message_identifier
+
client = SlackClient(integration_id=integration.id)
+ success = False
try:
- client.post("/chat.postMessage", data=payload, timeout=5)
- return True
- except ApiError:
+ response = client.post("/chat.postMessage", data=payload, timeout=5)
+ # response should include a "ts" key that represents the unique identifier for the message
+ # referenced at https://api.slack.com/methods/chat.postMessage#examples
+ except ApiError as e:
+ # Record the error code and details from the exception
+ new_notification_message_object.error_code = e.code
+ new_notification_message_object.error_details = {
+ "url": e.url,
+ "host": e.host,
+ "path": e.path,
+ "data": e.json if e.json else e.text,
+ }
logger.info("rule.fail.slack_post", exc_info=True)
- return False
+ else:
+ success = True
+ # Slack will always send back a ts identifier https://api.slack.com/methods/chat.postMessage#examples
+ # on a successful message
+ ts = None
+ # This is a workaround for typing, and the dynamic nature of the return value
+ if isinstance(response, BaseApiResponse):
+ ts = response.json.get("ts")
+ elif isinstance(response, MappingApiResponse):
+ ts = response.get("ts")
+ else:
+ logger.info(
+ "failed to get ts from slack response",
+ extra={
+ "response_type": type(response).__name__,
+ },
+ )
+ new_notification_message_object.message_identifier = str(ts) if ts is not None else None
+
+ if features.has("organizations:slack-thread", organization):
+ # Save the notification message we just sent with the response id or error we received
+ try:
+ repository.create_notification_message(data=new_notification_message_object)
+ except Exception:
+ # If we had an unexpected error with saving a record to our datastore,
+ # do not let the error bubble up, nor block this flow from finishing
+ pass
+
+ return success
def send_slack_response(
diff --git a/tests/sentry/integrations/repository/__init__.py b/tests/sentry/integrations/repository/__init__.py
new file mode 100644
index 00000000000000..e69de29bb2d1d6
diff --git a/tests/sentry/integrations/repository/metric_alert/__init__.py b/tests/sentry/integrations/repository/metric_alert/__init__.py
new file mode 100644
index 00000000000000..e69de29bb2d1d6
diff --git a/tests/sentry/integrations/repository/metric_alert/test_metric_alert_notification_message_repository.py b/tests/sentry/integrations/repository/metric_alert/test_metric_alert_notification_message_repository.py
new file mode 100644
index 00000000000000..c77cd52ea3cd80
--- /dev/null
+++ b/tests/sentry/integrations/repository/metric_alert/test_metric_alert_notification_message_repository.py
@@ -0,0 +1,100 @@
+from sentry.integrations.repository.metric_alert import (
+ MetricAlertNotificationMessage,
+ MetricAlertNotificationMessageRepository,
+ NewMetricAlertNotificationMessage,
+)
+from sentry.models.notificationmessage import NotificationMessage
+from sentry.testutils.cases import TestCase
+
+
+class TestGetParentNotificationMessage(TestCase):
+ def setUp(self) -> None:
+ self.incident = self.create_incident()
+ self.trigger_action = self.create_alert_rule_trigger_action()
+ self.parent_notification_message = NotificationMessage.objects.create(
+ incident=self.incident,
+ trigger_action=self.trigger_action,
+ message_identifier="123abc",
+ )
+ self.repository = MetricAlertNotificationMessageRepository.default()
+
+ def test_returns_parent_notification_message(self) -> None:
+ instance = self.repository.get_parent_notification_message(
+ alert_rule_id=self.incident.alert_rule.id,
+ incident_id=self.incident.id,
+ trigger_action_id=self.trigger_action.id,
+ )
+
+ assert instance is not None
+ assert instance == MetricAlertNotificationMessage.from_model(
+ self.parent_notification_message
+ )
+
+ def test_returns_none_when_filter_does_not_exist(self) -> None:
+ instance = self.repository.get_parent_notification_message(
+ alert_rule_id=9999,
+ incident_id=self.incident.id,
+ trigger_action_id=self.trigger_action.id,
+ )
+
+ assert instance is None
+
+ def test_when_parent_has_child(self) -> None:
+ child = NotificationMessage.objects.create(
+ incident=self.incident,
+ trigger_action=self.trigger_action,
+ message_identifier="456abc",
+ parent_notification_message=self.parent_notification_message,
+ )
+
+ assert child.id != self.parent_notification_message.id
+
+ instance = self.repository.get_parent_notification_message(
+ alert_rule_id=self.incident.alert_rule.id,
+ incident_id=self.incident.id,
+ trigger_action_id=self.trigger_action.id,
+ )
+
+ assert instance is not None
+ assert instance == MetricAlertNotificationMessage.from_model(
+ self.parent_notification_message
+ )
+
+
+class TestCreateNotificationMessage(TestCase):
+ def setUp(self):
+ self.incident = self.create_incident()
+ self.trigger_action = self.create_alert_rule_trigger_action()
+ self.repository = MetricAlertNotificationMessageRepository.default()
+
+ def test_simple(self) -> None:
+ message_identifier = "1a2b3c"
+ data = NewMetricAlertNotificationMessage(
+ incident_id=self.incident.id,
+ trigger_action_id=self.trigger_action.id,
+ message_identifier=message_identifier,
+ )
+
+ result = self.repository.create_notification_message(data=data)
+ assert result is not None
+ assert result.message_identifier == message_identifier
+
+ def test_with_error_details(self) -> None:
+ error_detail = {
+ "message": "message",
+ "some_nested_obj": {
+ "some_nested_key": "some_nested_value",
+ "some_array": ["some_array"],
+ "int": 203,
+ },
+ }
+ data = NewMetricAlertNotificationMessage(
+ incident_id=self.incident.id,
+ trigger_action_id=self.trigger_action.id,
+ error_code=405,
+ error_details=error_detail,
+ )
+
+ result = self.repository.create_notification_message(data=data)
+ assert result is not None
+ assert result.error_details == error_detail
diff --git a/tests/sentry/integrations/repository/metric_alert/test_new_metric_alert_notification_message.py b/tests/sentry/integrations/repository/metric_alert/test_new_metric_alert_notification_message.py
new file mode 100644
index 00000000000000..2b6e2284b12aad
--- /dev/null
+++ b/tests/sentry/integrations/repository/metric_alert/test_new_metric_alert_notification_message.py
@@ -0,0 +1,74 @@
+import pytest
+
+from sentry.integrations.repository.metric_alert import (
+ IncidentAndTriggerActionValidationError,
+ MessageIdentifierWithErrorValidationError,
+ NewMetricAlertNotificationMessage,
+)
+
+
+class TestGetValidationError:
+ @classmethod
+ def _raises_error_for_obj(
+ cls, obj: NewMetricAlertNotificationMessage, expected_error: type[Exception]
+ ) -> None:
+ error = obj.get_validation_error()
+ assert error is not None
+ with pytest.raises(expected_error):
+ raise error
+
+ def test_returns_error_when_message_identifier_has_error_code(self) -> None:
+ obj = NewMetricAlertNotificationMessage(
+ message_identifier="abc",
+ error_code=400,
+ )
+ self._raises_error_for_obj(obj, MessageIdentifierWithErrorValidationError)
+
+ def test_returns_error_when_message_identifier_has_error_details(self) -> None:
+ obj = NewMetricAlertNotificationMessage(
+ message_identifier="abc",
+ error_details={"some_key": 123},
+ )
+ self._raises_error_for_obj(obj, MessageIdentifierWithErrorValidationError)
+
+ def test_returns_error_when_message_identifier_has_error(self) -> None:
+ obj = NewMetricAlertNotificationMessage(
+ message_identifier="abc",
+ error_code=400,
+ error_details={"some_key": 123},
+ )
+ self._raises_error_for_obj(obj, MessageIdentifierWithErrorValidationError)
+
+ def test_returns_error_when_message_identifier_does_not_have_incident(self) -> None:
+ obj = NewMetricAlertNotificationMessage(
+ message_identifier="abc",
+ trigger_action_id=123,
+ )
+ self._raises_error_for_obj(obj, IncidentAndTriggerActionValidationError)
+
+ def test_returns_error_when_message_identifier_does_not_have_trigger_action(self) -> None:
+ obj = NewMetricAlertNotificationMessage(
+ message_identifier="abc",
+ incident_id=123,
+ )
+ self._raises_error_for_obj(obj, IncidentAndTriggerActionValidationError)
+
+ def test_returns_error_when_trigger_action_is_missing(self) -> None:
+ obj = NewMetricAlertNotificationMessage(
+ incident_id=123,
+ )
+ self._raises_error_for_obj(obj, IncidentAndTriggerActionValidationError)
+
+ def test_returns_error_when_incident_is_missing(self) -> None:
+ obj = NewMetricAlertNotificationMessage(
+ trigger_action_id=123,
+ )
+ self._raises_error_for_obj(obj, IncidentAndTriggerActionValidationError)
+
+ def test_simple(self) -> None:
+ obj = NewMetricAlertNotificationMessage(
+ incident_id=123,
+ trigger_action_id=123,
+ )
+ error = obj.get_validation_error()
+ assert error is None
|
efa8a4619c8d0bb407fe16f640cc8a21f8d351d0
|
2022-06-14 22:41:00
|
Vu Luong
|
ref(addDashboardWidgetModal): Use SelectControl's tooltip prop (#35547)
| false
|
Use SelectControl's tooltip prop (#35547)
|
ref
|
diff --git a/static/app/components/modals/addDashboardWidgetModal.tsx b/static/app/components/modals/addDashboardWidgetModal.tsx
index 297f5ea12efeae..f7977c3277073d 100644
--- a/static/app/components/modals/addDashboardWidgetModal.tsx
+++ b/static/app/components/modals/addDashboardWidgetModal.tsx
@@ -1,6 +1,5 @@
import {Component, Fragment} from 'react';
import {browserHistory} from 'react-router';
-import {OptionProps} from 'react-select';
import {css} from '@emotion/react';
import styled from '@emotion/styled';
import cloneDeep from 'lodash/cloneDeep';
@@ -67,9 +66,6 @@ import WidgetCard from 'sentry/views/dashboardsV2/widgetCard';
import {WidgetTemplate} from 'sentry/views/dashboardsV2/widgetLibrary/data';
import {generateFieldOptions} from 'sentry/views/eventsV2/utils';
-import Option from '../forms/selectOption';
-import Tooltip from '../tooltip';
-
import {TAB, TabsButtonBar} from './dashboardWidgetLibraryModal/tabsButtonBar';
export type DashboardWidgetModalOptions = {
@@ -568,6 +564,12 @@ class AddDashboardWidgetModal extends Component<Props, State> {
label: d.title,
value: d.id,
isDisabled: d.widgetDisplay.length >= MAX_WIDGETS,
+ tooltip:
+ d.widgetDisplay.length >= MAX_WIDGETS &&
+ tct('Max widgets ([maxWidgets]) per dashboard reached.', {
+ maxWidgets: MAX_WIDGETS,
+ }),
+ tooltipOptions: {position: 'right'},
};
});
return (
@@ -594,20 +596,6 @@ class AddDashboardWidgetModal extends Component<Props, State> {
]}
onChange={(option: SelectValue<string>) => this.handleDashboardChange(option)}
disabled={loading}
- components={{
- Option: ({label, data, ...optionProps}: OptionProps<any>) => (
- <Tooltip
- disabled={!!!data.isDisabled}
- title={tct('Max widgets ([maxWidgets]) per dashboard reached.', {
- maxWidgets: MAX_WIDGETS,
- })}
- containerDisplayMode="block"
- position="right"
- >
- <Option label={label} data={data} {...(optionProps as any)} />
- </Tooltip>
- ),
- }}
/>
</Field>
</Fragment>
diff --git a/static/app/components/modals/widgetBuilder/addToDashboardModal.tsx b/static/app/components/modals/widgetBuilder/addToDashboardModal.tsx
index 53da99abda47e7..9dd52f40d7fdf7 100644
--- a/static/app/components/modals/widgetBuilder/addToDashboardModal.tsx
+++ b/static/app/components/modals/widgetBuilder/addToDashboardModal.tsx
@@ -1,6 +1,5 @@
import {Fragment, useEffect, useState} from 'react';
import {InjectedRouter} from 'react-router';
-import {OptionProps} from 'react-select';
import {css} from '@emotion/react';
import styled from '@emotion/styled';
import {Query} from 'history';
@@ -15,8 +14,6 @@ import {ModalRenderProps} from 'sentry/actionCreators/modal';
import Button from 'sentry/components/button';
import ButtonBar from 'sentry/components/buttonBar';
import SelectControl from 'sentry/components/forms/selectControl';
-import SelectOption from 'sentry/components/forms/selectOption';
-import Tooltip from 'sentry/components/tooltip';
import {t, tct} from 'sentry/locale';
import space from 'sentry/styles/space';
import {DateString, Organization, PageFilters, SelectValue} from 'sentry/types';
@@ -146,6 +143,12 @@ function AddToDashboardModal({
label: title,
value: id,
isDisabled: widgetDisplay.length >= MAX_WIDGETS,
+ tooltip:
+ widgetDisplay.length >= MAX_WIDGETS &&
+ tct('Max widgets ([maxWidgets]) per dashboard reached.', {
+ maxWidgets: MAX_WIDGETS,
+ }),
+ tooltipOptions: {position: 'right'},
})),
]
}
@@ -155,20 +158,6 @@ function AddToDashboardModal({
}
setSelectedDashboardId(option.value);
}}
- components={{
- Option: ({label, data, ...optionProps}: OptionProps<any>) => (
- <Tooltip
- disabled={!!!data.isDisabled}
- title={tct('Max widgets ([maxWidgets]) per dashboard reached.', {
- maxWidgets: MAX_WIDGETS,
- })}
- containerDisplayMode="block"
- position="right"
- >
- <SelectOption label={label} data={data} {...(optionProps as any)} />
- </Tooltip>
- ),
- }}
/>
</SelectControlWrapper>
{t('This is a preview of how the widget will appear in your dashboard.')}
diff --git a/tests/js/spec/components/modals/addDashboardWidgetModal.spec.jsx b/tests/js/spec/components/modals/addDashboardWidgetModal.spec.jsx
index 0a52ddb95f84e1..e990bc1c672e99 100644
--- a/tests/js/spec/components/modals/addDashboardWidgetModal.spec.jsx
+++ b/tests/js/spec/components/modals/addDashboardWidgetModal.spec.jsx
@@ -222,9 +222,9 @@ describe('Modals -> AddDashboardWidgetModal', function () {
openMenu(wrapper, {name: 'dashboard', control: true});
const input = wrapper.find('SelectControl[name="dashboard"]');
- expect(input.find('Option Option')).toHaveLength(2);
- expect(input.find('Option Option').at(0).props().isDisabled).toBe(false);
- expect(input.find('Option Option').at(1).props().isDisabled).toBe(true);
+ expect(input.find('Option')).toHaveLength(2);
+ expect(input.find('Option').at(0).props().isDisabled).toBe(false);
+ expect(input.find('Option').at(1).props().isDisabled).toBe(true);
wrapper.unmount();
});
|
2a4ad742847f1c16f00fcdab6c697902623d5489
|
2025-02-20 02:38:28
|
Katie Byers
|
ref(grouping): Make grouping component `description` a cached property (#85481)
| false
|
Make grouping component `description` a cached property (#85481)
|
ref
|
diff --git a/src/sentry/grouping/component.py b/src/sentry/grouping/component.py
index cfca678fe3a0e3..6e6892108b0634 100644
--- a/src/sentry/grouping/component.py
+++ b/src/sentry/grouping/component.py
@@ -3,6 +3,7 @@
from abc import ABC, abstractmethod
from collections import Counter
from collections.abc import Generator, Iterator, Sequence
+from functools import cached_property
from typing import Any, Self
from sentry.grouping.utils import hash_from_values
@@ -66,7 +67,7 @@ def id(self) -> str: ...
def name(self) -> str | None:
return KNOWN_MAJOR_COMPONENT_NAMES.get(self.id)
- @property
+ @cached_property
def description(self) -> str:
"""
Build the component description by walking its component tree and collecting the names of
|
68034969a16f50c52a3e065f1cefb1fdeb27131c
|
2024-03-20 06:44:57
|
Jonas
|
fix(trace): sync colors (#67302)
| false
|
sync colors (#67302)
|
fix
|
diff --git a/static/app/views/performance/newTraceDetails/trace.tsx b/static/app/views/performance/newTraceDetails/trace.tsx
index 067f5ffd1ed1bd..861cb5ec8546a3 100644
--- a/static/app/views/performance/newTraceDetails/trace.tsx
+++ b/static/app/views/performance/newTraceDetails/trace.tsx
@@ -809,7 +809,7 @@ function RenderRow(props: {
<AutogroupedTraceBar
virtualized_index={virtualized_index}
manager={props.manager}
- color={props.theme.blue300}
+ color={makeTraceNodeBarColor(props.theme, props.node)}
entire_space={props.node.space}
node_spaces={props.node.autogroupedSegments}
errors={props.node.errors}
diff --git a/static/app/views/performance/newTraceDetails/traceDrawer/details/error.tsx b/static/app/views/performance/newTraceDetails/traceDrawer/details/error.tsx
index d7b5cc4e46d765..6cb5e2a78be0c8 100644
--- a/static/app/views/performance/newTraceDetails/traceDrawer/details/error.tsx
+++ b/static/app/views/performance/newTraceDetails/traceDrawer/details/error.tsx
@@ -1,4 +1,5 @@
import {useMemo} from 'react';
+import {useTheme} from '@emotion/react';
import styled from '@emotion/styled';
import type {Location} from 'history';
@@ -17,7 +18,7 @@ import {useApiQuery} from 'sentry/utils/queryClient';
import {getTraceTabTitle} from 'sentry/views/performance/newTraceDetails/traceTabs';
import {Row, Tags} from 'sentry/views/performance/traceDetails/styles';
-import type {TraceTree, TraceTreeNode} from '../../traceTree';
+import {makeTraceNodeBarColor, type TraceTree, type TraceTreeNode} from '../../traceTree';
import {IssueList} from './issues/issues';
import {TraceDrawerComponents} from './styles';
@@ -52,6 +53,7 @@ export function ErrorNodeDetails({
return null;
}, [data]);
+ const theme = useTheme();
const parentTransaction = node.parent_transaction;
return isLoading ? (
@@ -60,8 +62,10 @@ export function ErrorNodeDetails({
<TraceDrawerComponents.DetailContainer>
<TraceDrawerComponents.HeaderContainer>
<TraceDrawerComponents.Title>
- <TraceDrawerComponents.IconBorder errored>
- <IconFire color="errorText" size="md" />
+ <TraceDrawerComponents.IconBorder
+ backgroundColor={makeTraceNodeBarColor(theme, node)}
+ >
+ <IconFire size="md" />
</TraceDrawerComponents.IconBorder>
<div>
<div>{t('error')}</div>
diff --git a/static/app/views/performance/newTraceDetails/traceDrawer/details/missingInstrumentation.tsx b/static/app/views/performance/newTraceDetails/traceDrawer/details/missingInstrumentation.tsx
index 6b120b06fed62f..6b4bbc90867b62 100644
--- a/static/app/views/performance/newTraceDetails/traceDrawer/details/missingInstrumentation.tsx
+++ b/static/app/views/performance/newTraceDetails/traceDrawer/details/missingInstrumentation.tsx
@@ -1,10 +1,17 @@
+import {useTheme} from '@emotion/react';
+
import {IconSpan} from 'sentry/icons';
import {t} from 'sentry/locale';
import {getDuration} from 'sentry/utils/formatters';
import {getTraceTabTitle} from 'sentry/views/performance/newTraceDetails/traceTabs';
import {Row} from 'sentry/views/performance/traceDetails/styles';
-import type {MissingInstrumentationNode, TraceTree, TraceTreeNode} from '../../traceTree';
+import {
+ makeTraceNodeBarColor,
+ type MissingInstrumentationNode,
+ type TraceTree,
+ type TraceTreeNode,
+} from '../../traceTree';
import {TraceDrawerComponents} from './styles';
@@ -15,13 +22,16 @@ export function MissingInstrumentationNodeDetails({
node: MissingInstrumentationNode;
onParentClick: (node: TraceTreeNode<TraceTree.NodeValue>) => void;
}) {
+ const theme = useTheme();
const parentTransaction = node.parent_transaction;
return (
<TraceDrawerComponents.DetailContainer>
<TraceDrawerComponents.IconTitleWrapper>
- <TraceDrawerComponents.IconBorder>
- <IconSpan color="blue300" size="md" />
+ <TraceDrawerComponents.IconBorder
+ backgroundColor={makeTraceNodeBarColor(theme, node)}
+ >
+ <IconSpan size="md" />
</TraceDrawerComponents.IconBorder>
<div style={{fontWeight: 'bold'}}>{t('Missing Instrumentation')}</div>
</TraceDrawerComponents.IconTitleWrapper>
diff --git a/static/app/views/performance/newTraceDetails/traceDrawer/details/parentAutogroup.tsx b/static/app/views/performance/newTraceDetails/traceDrawer/details/parentAutogroup.tsx
index 4155e394f7b7af..8993f22ebbcf09 100644
--- a/static/app/views/performance/newTraceDetails/traceDrawer/details/parentAutogroup.tsx
+++ b/static/app/views/performance/newTraceDetails/traceDrawer/details/parentAutogroup.tsx
@@ -1,4 +1,5 @@
import {useMemo} from 'react';
+import {useTheme} from '@emotion/react';
import {IconGroup} from 'sentry/icons';
import {t} from 'sentry/locale';
@@ -6,7 +7,12 @@ import type {Organization} from 'sentry/types';
import {getTraceTabTitle} from 'sentry/views/performance/newTraceDetails/traceTabs';
import {Row} from 'sentry/views/performance/traceDetails/styles';
-import type {ParentAutogroupNode, TraceTree, TraceTreeNode} from '../../traceTree';
+import {
+ makeTraceNodeBarColor,
+ type ParentAutogroupNode,
+ type TraceTree,
+ type TraceTreeNode,
+} from '../../traceTree';
import {IssueList} from './issues/issues';
import {TraceDrawerComponents} from './styles';
@@ -20,6 +26,7 @@ export function ParentAutogroupNodeDetails({
onParentClick: (node: TraceTreeNode<TraceTree.NodeValue>) => void;
organization: Organization;
}) {
+ const theme = useTheme();
const issues = useMemo(() => {
return [...node.errors, ...node.performance_issues];
}, [node.errors, node.performance_issues]);
@@ -29,8 +36,10 @@ export function ParentAutogroupNodeDetails({
return (
<TraceDrawerComponents.DetailContainer>
<TraceDrawerComponents.IconTitleWrapper>
- <TraceDrawerComponents.IconBorder>
- <IconGroup color="blue300" size="md" />
+ <TraceDrawerComponents.IconBorder
+ backgroundColor={makeTraceNodeBarColor(theme, node)}
+ >
+ <IconGroup size="md" />
</TraceDrawerComponents.IconBorder>
<div style={{fontWeight: 'bold'}}>{t('Autogroup')}</div>
</TraceDrawerComponents.IconTitleWrapper>
diff --git a/static/app/views/performance/newTraceDetails/traceDrawer/details/siblingAutogroup.tsx b/static/app/views/performance/newTraceDetails/traceDrawer/details/siblingAutogroup.tsx
index 4f9e14963b94c2..0b882bbd584205 100644
--- a/static/app/views/performance/newTraceDetails/traceDrawer/details/siblingAutogroup.tsx
+++ b/static/app/views/performance/newTraceDetails/traceDrawer/details/siblingAutogroup.tsx
@@ -1,4 +1,5 @@
import {useMemo} from 'react';
+import {useTheme} from '@emotion/react';
import {IconGroup} from 'sentry/icons';
import {t, tct} from 'sentry/locale';
@@ -6,7 +7,12 @@ import type {Organization} from 'sentry/types';
import {getTraceTabTitle} from 'sentry/views/performance/newTraceDetails/traceTabs';
import {Row} from 'sentry/views/performance/traceDetails/styles';
-import type {SiblingAutogroupNode, TraceTree, TraceTreeNode} from '../../traceTree';
+import {
+ makeTraceNodeBarColor,
+ type SiblingAutogroupNode,
+ type TraceTree,
+ type TraceTreeNode,
+} from '../../traceTree';
import {IssueList} from './issues/issues';
import {TraceDrawerComponents} from './styles';
@@ -20,6 +26,7 @@ export function SiblingAutogroupNodeDetails({
onParentClick: (node: TraceTreeNode<TraceTree.NodeValue>) => void;
organization: Organization;
}) {
+ const theme = useTheme();
const issues = useMemo(() => {
return [...node.errors, ...node.performance_issues];
}, [node.errors, node.performance_issues]);
@@ -29,8 +36,10 @@ export function SiblingAutogroupNodeDetails({
return (
<TraceDrawerComponents.DetailContainer>
<TraceDrawerComponents.IconTitleWrapper>
- <TraceDrawerComponents.IconBorder>
- <IconGroup color="blue300" />
+ <TraceDrawerComponents.IconBorder
+ backgroundColor={makeTraceNodeBarColor(theme, node)}
+ >
+ <IconGroup />
</TraceDrawerComponents.IconBorder>
<div style={{fontWeight: 'bold'}}>{t('Autogroup')}</div>
</TraceDrawerComponents.IconTitleWrapper>
diff --git a/static/app/views/performance/newTraceDetails/traceDrawer/details/styles.tsx b/static/app/views/performance/newTraceDetails/traceDrawer/details/styles.tsx
index 81b389adaf0eba..ca2380ed5f38fd 100644
--- a/static/app/views/performance/newTraceDetails/traceDrawer/details/styles.tsx
+++ b/static/app/views/performance/newTraceDetails/traceDrawer/details/styles.tsx
@@ -51,8 +51,8 @@ const IconTitleWrapper = styled(FlexBox)`
gap: ${space(1)};
`;
-const IconBorder = styled('div')<{errored?: boolean}>`
- background-color: ${p => (p.errored ? p.theme.error : p.theme.blue300)};
+const IconBorder = styled('div')<{backgroundColor: string; errored?: boolean}>`
+ background-color: ${p => p.backgroundColor};
border-radius: ${p => p.theme.borderRadius};
padding: 0;
display: flex;
|
252a96e041a19d7c4c6ee41604f7e4676294eceb
|
2025-01-23 21:34:02
|
Rohan Agarwal
|
chore(autofix): Add fallback profile fetching logic (#83841)
| false
|
Add fallback profile fetching logic (#83841)
|
chore
|
diff --git a/src/sentry/api/endpoints/group_ai_autofix.py b/src/sentry/api/endpoints/group_ai_autofix.py
index 577153acf0da4a..765fb231ea294b 100644
--- a/src/sentry/api/endpoints/group_ai_autofix.py
+++ b/src/sentry/api/endpoints/group_ai_autofix.py
@@ -107,6 +107,28 @@ def _get_profile_for_event(
if not profile_id and results: # fallback to a similar transaction in the trace
profile_matches_event = False
profile_id = results[0].data.get("contexts", {}).get("profile", {}).get("profile_id")
+ if (
+ not profile_id
+ ): # fallback to any profile in that kind of transaction, not just the same trace
+ event_filter = eventstore.Filter(
+ project_ids=[project.id],
+ conditions=[
+ ["transaction", "=", transaction_name],
+ ["profile_id", "IS NOT NULL", None],
+ ],
+ )
+ results = eventstore.backend.get_events(
+ filter=event_filter,
+ dataset=Dataset.Transactions,
+ referrer=Referrer.API_GROUP_AI_AUTOFIX,
+ tenant_ids={"organization_id": project.organization_id},
+ limit=1,
+ )
+ if results:
+ profile_id = (
+ results[0].data.get("contexts", {}).get("profile", {}).get("profile_id")
+ )
+
if not profile_id:
return None
diff --git a/tests/sentry/api/endpoints/test_group_ai_autofix.py b/tests/sentry/api/endpoints/test_group_ai_autofix.py
index 1bfc6ed0023d6e..9fd070a4124bf1 100644
--- a/tests/sentry/api/endpoints/test_group_ai_autofix.py
+++ b/tests/sentry/api/endpoints/test_group_ai_autofix.py
@@ -713,3 +713,178 @@ def test_get_profile_for_event_profile_service_error(self, mock_get_from_profili
# Verify no profile is returned on service error
assert profile is None
+
+ @patch("sentry.api.endpoints.group_ai_autofix.get_from_profiling_service")
+ def test_get_profile_for_event_fallback_profile(self, mock_get_from_profiling_service):
+ # Create a test event with transaction and trace data
+ data = load_data("python", timestamp=before_now(minutes=1))
+ event = self.store_event(
+ data={
+ **data,
+ "transaction": "test_transaction",
+ "contexts": {
+ "trace": {
+ "trace_id": "a" * 32,
+ "span_id": "a" * 16, # Different span_id than the transaction event
+ }
+ },
+ },
+ project_id=self.project.id,
+ )
+
+ # Mock the profile service response
+ mock_get_from_profiling_service.return_value.status = 200
+ mock_get_from_profiling_service.return_value.data = b"""{
+ "profile": {
+ "frames": [
+ {
+ "function": "main",
+ "module": "app.main",
+ "filename": "main.py",
+ "lineno": 10,
+ "in_app": true
+ }
+ ],
+ "stacks": [[0]],
+ "samples": [{"stack_id": 0, "thread_id": "1"}],
+ "thread_metadata": {"1": {"name": "MainThread"}}
+ }
+ }"""
+
+ timestamp = before_now(minutes=1)
+ profile_id = "0" * 32
+ # Create a transaction event with profile_id but different span_id
+ self.store_event(
+ data={
+ "type": "transaction",
+ "transaction": "test_transaction",
+ "contexts": {
+ "trace": {
+ "trace_id": "a" * 32,
+ "span_id": "b" * 16, # Different span_id than the error event
+ },
+ "profile": {"profile_id": profile_id},
+ },
+ "spans": [
+ {
+ "span_id": "c"
+ * 16, # Different span_id than both error event and transaction
+ "trace_id": "a" * 32,
+ "op": "test",
+ "description": "test span",
+ "start_timestamp": timestamp.timestamp(),
+ "timestamp": (timestamp + timedelta(seconds=1)).timestamp(),
+ }
+ ],
+ "start_timestamp": timestamp.timestamp(),
+ "timestamp": (timestamp + timedelta(seconds=1)).timestamp(),
+ },
+ project_id=self.project.id,
+ )
+
+ profile = GroupAutofixEndpoint()._get_profile_for_event(event, self.project)
+
+ # Verify profile was fetched and processed correctly
+ assert profile is not None
+ # Should indicate that this is a fallback profile that doesn't exactly match the error
+ assert profile["profile_matches_issue"] is False
+ assert len(profile["execution_tree"]) == 1
+ assert profile["execution_tree"][0]["function"] == "main"
+ assert profile["execution_tree"][0]["module"] == "app.main"
+ assert profile["execution_tree"][0]["filename"] == "main.py"
+ assert profile["execution_tree"][0]["lineno"] == 10
+
+ # Verify profiling service was called with correct parameters
+ mock_get_from_profiling_service.assert_called_once_with(
+ "GET",
+ f"/organizations/{self.project.organization_id}/projects/{self.project.id}/profiles/{profile_id}",
+ params={"format": "sample"},
+ )
+
+ @patch("sentry.api.endpoints.group_ai_autofix.get_from_profiling_service")
+ def test_get_profile_for_event_fallback_to_transaction_name(
+ self, mock_get_from_profiling_service
+ ):
+ # Create a test event with transaction and trace data
+ data = load_data("python", timestamp=before_now(minutes=1))
+ event = self.store_event(
+ data={
+ **data,
+ "transaction": "test_transaction",
+ "contexts": {
+ "trace": {
+ "trace_id": "a" * 32, # Different trace_id than the transaction event
+ "span_id": "a" * 16,
+ }
+ },
+ },
+ project_id=self.project.id,
+ )
+
+ # Mock the profile service response
+ mock_get_from_profiling_service.return_value.status = 200
+ mock_get_from_profiling_service.return_value.data = b"""{
+ "profile": {
+ "frames": [
+ {
+ "function": "main",
+ "module": "app.main",
+ "filename": "main.py",
+ "lineno": 10,
+ "in_app": true
+ }
+ ],
+ "stacks": [[0]],
+ "samples": [{"stack_id": 0, "thread_id": "1"}],
+ "thread_metadata": {"1": {"name": "MainThread"}}
+ }
+ }"""
+
+ timestamp = before_now(minutes=1)
+ profile_id = "0" * 32
+ # Create a transaction event with profile_id but different trace_id
+ self.store_event(
+ data={
+ "type": "transaction",
+ "transaction": "test_transaction", # Same transaction name
+ "contexts": {
+ "trace": {
+ "trace_id": "b" * 32, # Different trace_id than the error event
+ "span_id": "b" * 16,
+ },
+ "profile": {"profile_id": profile_id},
+ },
+ "spans": [
+ {
+ "span_id": "c" * 16,
+ "trace_id": "b" * 32,
+ "op": "test",
+ "description": "test span",
+ "start_timestamp": timestamp.timestamp(),
+ "timestamp": (timestamp + timedelta(seconds=1)).timestamp(),
+ }
+ ],
+ "start_timestamp": timestamp.timestamp(),
+ "timestamp": (timestamp + timedelta(seconds=1)).timestamp(),
+ },
+ project_id=self.project.id,
+ )
+
+ profile = GroupAutofixEndpoint()._get_profile_for_event(event, self.project)
+
+ # Verify profile was fetched and processed correctly
+ assert profile is not None
+ # Should indicate that this is a fallback profile that doesn't exactly match the error
+ assert profile["profile_matches_issue"] is False
+ assert len(profile["execution_tree"]) == 1
+ assert profile["execution_tree"][0]["function"] == "main"
+ assert profile["execution_tree"][0]["module"] == "app.main"
+ assert profile["execution_tree"][0]["filename"] == "main.py"
+ assert profile["execution_tree"][0]["lineno"] == 10
+
+ # Verify profiling service was called with correct parameters
+ mock_get_from_profiling_service.assert_called_once_with(
+ "GET",
+ f"/organizations/{self.project.organization_id}/projects/{self.project.id}/profiles/{profile_id}",
+ params={"format": "sample"},
+ )
|
7ec5d8b17f9e97c3570ae4396f8b6612f6d268dc
|
2022-04-28 19:49:02
|
Tony Xiao
|
fix(profiling): Better error message on flamegraph (#34024)
| false
|
Better error message on flamegraph (#34024)
|
fix
|
diff --git a/static/app/views/profiling/flamegraph.tsx b/static/app/views/profiling/flamegraph.tsx
index e7ab5e34e5e9b8..167744c5cd1ac0 100644
--- a/static/app/views/profiling/flamegraph.tsx
+++ b/static/app/views/profiling/flamegraph.tsx
@@ -20,7 +20,21 @@ import {Profile} from 'sentry/utils/profiling/profile/profile';
import useApi from 'sentry/utils/useApi';
import useOrganization from 'sentry/utils/useOrganization';
-type RequestState = 'initial' | 'loading' | 'resolved' | 'errored';
+type InitialState = {type: 'initial'};
+
+type LoadingState = {type: 'loading'};
+
+type ResolvedState<T> = {
+ data: T;
+ type: 'resolved';
+};
+
+type ErroredState = {
+ error: string;
+ type: 'errored';
+};
+
+type RequestState<T> = InitialState | LoadingState | ResolvedState<T> | ErroredState;
function fetchFlamegraphs(
api: Client,
@@ -58,24 +72,25 @@ function FlamegraphView(props: FlamegraphViewProps): React.ReactElement {
const api = useApi();
const organization = useOrganization();
- const [profiles, setProfiles] = useState<ProfileGroup | null>(null);
- const [requestState, setRequestState] = useState<RequestState>('initial');
+ const [requestState, setRequestState] = useState<RequestState<ProfileGroup>>({
+ type: 'initial',
+ });
useEffect(() => {
if (!props.params.eventId || !props.params.projectId) {
return undefined;
}
- setRequestState('loading');
+ setRequestState({type: 'loading'});
fetchFlamegraphs(api, props.params.eventId, props.params.projectId, organization)
.then(importedFlamegraphs => {
- setProfiles(importedFlamegraphs);
- setRequestState('resolved');
+ setRequestState({type: 'resolved', data: importedFlamegraphs});
})
.catch(err => {
+ const message = err.toString() || t('Error: Unable to load profiles');
+ setRequestState({type: 'errored', error: message});
Sentry.captureException(err);
- setRequestState('errored');
});
return () => {
@@ -96,7 +111,8 @@ function FlamegraphView(props: FlamegraphViewProps): React.ReactElement {
{
type: 'flamegraph',
payload: {
- interactionName: profiles?.name ?? '',
+ interactionName:
+ requestState.type === 'resolved' ? requestState.data.name : '',
profileId: props.params.eventId ?? '',
projectSlug: props.params.projectId ?? '',
},
@@ -108,19 +124,19 @@ function FlamegraphView(props: FlamegraphViewProps): React.ReactElement {
<FlamegraphStateProvider>
<FlamegraphThemeProvider>
<FlamegraphContainer>
- {requestState === 'errored' ? (
+ {requestState.type === 'errored' ? (
<Alert type="error" showIcon>
- {t('Unable to load profiles')}
+ {requestState.error}
</Alert>
- ) : requestState === 'loading' ? (
+ ) : requestState.type === 'loading' ? (
<Fragment>
<Flamegraph profiles={LoadingGroup} />
<LoadingIndicatorContainer>
<LoadingIndicator />
</LoadingIndicatorContainer>
</Fragment>
- ) : requestState === 'resolved' && profiles ? (
- <Flamegraph profiles={profiles} />
+ ) : requestState.type === 'resolved' ? (
+ <Flamegraph profiles={requestState.data} />
) : null}
</FlamegraphContainer>
</FlamegraphThemeProvider>
|
381f96ba31fa3397d1aa12e30cab0895ab813088
|
2023-04-29 03:53:23
|
Seiji Chew
|
fix(api): Fix comment typo (#48217)
| false
|
Fix comment typo (#48217)
|
fix
|
diff --git a/src/sentry/api/bases/team.py b/src/sentry/api/bases/team.py
index 50a6c67969f67a..7a7974aa712429 100644
--- a/src/sentry/api/bases/team.py
+++ b/src/sentry/api/bases/team.py
@@ -25,7 +25,7 @@ def has_object_permission(self, request: Request, view, team):
has_org_scope = super().has_object_permission(request, view, team.organization)
if has_org_scope:
# Org-admin has "team:admin", but they can only act on their teams
- # Org-owners and Org-owners has no restrictions due to team memberships
+ # Org-owners and Org-managers have no restrictions due to team memberships
return request.access.has_team_access(team)
return has_team_permission(request, team, self.scope_map)
|
d28a8c08da865f98b63d793b0a182dd4e4adf027
|
2024-11-04 12:37:50
|
Priscila Oliveira
|
fix(quick-start): Add missing file import (#80169)
| false
|
Add missing file import (#80169)
|
fix
|
diff --git a/src/sentry/analytics/events/__init__.py b/src/sentry/analytics/events/__init__.py
index 839162585bb420..0f203c16bcb590 100644
--- a/src/sentry/analytics/events/__init__.py
+++ b/src/sentry/analytics/events/__init__.py
@@ -61,6 +61,7 @@
from .missing_members_nudge import * # noqa: F401,F403
from .monitor_mark_failed import * # noqa: F401,F403
from .notifications_settings_updated import * # noqa: F401,F403
+from .onboarding_complete import * # noqa: F401,F403
from .onboarding_continuation_sent import * # noqa: F401,F403
from .open_pr_comment import * # noqa: F401,F403
from .org_auth_token_created import * # noqa: F401,F403
|
eadcd2bb14bea3532f0c60e78aef3a06d81f57de
|
2021-09-30 23:48:31
|
Richard Ma
|
feat(idp-migration): Verified one-time-key and stored key in django sessions (#28775)
| false
|
Verified one-time-key and stored key in django sessions (#28775)
|
feat
|
diff --git a/src/sentry/auth/idpmigration.py b/src/sentry/auth/idpmigration.py
index 93a213fdf16b38..0dcdeb4752143e 100644
--- a/src/sentry/auth/idpmigration.py
+++ b/src/sentry/auth/idpmigration.py
@@ -1,12 +1,14 @@
import string
from datetime import timedelta
+from django.urls import reverse
from django.utils.crypto import get_random_string
from sentry import options
from sentry.models import Organization, OrganizationMember, User
from sentry.utils import redis
from sentry.utils.email import MessageBuilder
+from sentry.utils.http import absolute_uri
_REDIS_KEY = "verificationKeyStorage"
_TTL = timedelta(minutes=10)
@@ -15,10 +17,12 @@
def send_confirm_email(user: User, email: str, verification_key: str) -> None:
context = {
"user": user,
- # TODO left incase we want to have a clickable verification link for future
- # "url": absolute_uri(
- # reverse("sentry-account-confirm-email", args=[user.id, verification_key])
- # ),
+ "url": absolute_uri(
+ reverse(
+ "sentry-idp-email-verification",
+ args=[verification_key],
+ )
+ ),
"confirm_email": email,
"verification_key": verification_key,
}
@@ -34,7 +38,7 @@ def send_confirm_email(user: User, email: str, verification_key: str) -> None:
def send_one_time_account_confirm_link(
user: User, org: Organization, email: str, identity_id: str
-) -> None:
+) -> str:
"""Store and email a verification key for IdP migration.
Create a one-time verification key for a user whose SSO identity
@@ -45,6 +49,7 @@ def send_one_time_account_confirm_link(
:param user: the user profile to link
:param org: the organization whose SSO provider is being used
:param email: the email address associated with the SSO identity
+ :param identity_id: the SSO identity id
"""
cluster = redis.clusters.get("default").get_local_client_for_key(_REDIS_KEY)
member_id = OrganizationMember.objects.get(organization=org, user=user).id
@@ -62,8 +67,14 @@ def send_one_time_account_confirm_link(
send_confirm_email(user, email, verification_code)
+ return verification_code
-def verify_new_identity(user: User, org: Organization, key: str) -> bool:
+
+def get_redis_key(verification_key: str) -> str:
+ return f"auth:one-time-key:{verification_key}"
+
+
+def verify_account(key: str) -> bool:
"""Verify a key to migrate a user to a new IdP.
If the provided one-time key is valid, create a new auth identity
@@ -74,5 +85,11 @@ def verify_new_identity(user: User, org: Organization, key: str) -> bool:
:param key: the one-time verification key
:return: whether the key is valid
"""
- # user cluster.hgetall(key) to get from redis
- raise NotImplementedError # TODO
+ cluster = redis.clusters.get("default").get_local_client_for_key(_REDIS_KEY)
+
+ verification_key = get_redis_key(key)
+ verification_value_byte = cluster.hgetall(verification_key)
+ if not verification_value_byte:
+ return False
+
+ return True
diff --git a/src/sentry/templates/sentry/emails/idp_verification_email.html b/src/sentry/templates/sentry/emails/idp_verification_email.html
index ad5a6b6fcf9908..9c21d814ac6dfd 100644
--- a/src/sentry/templates/sentry/emails/idp_verification_email.html
+++ b/src/sentry/templates/sentry/emails/idp_verification_email.html
@@ -4,7 +4,7 @@
{% block main %}
<h3>Confirm Email</h3>
- <p>Please confirm your email ({{ confirm_email }}) by submitting the following code on the verification page: ({{ verification_key }}). This code will expire in 10 minutes.</p>
- <!-- below is if we want to add a clickable button to verify -->
- <!-- <a href="{{ url }}" class="btn">Confirm</a> -->
+ <p>Please confirm your email ({{ confirm_email }}) by clicking the link below. This link will expire in 10 minutes.</p>
+
+ <a href="{{ url }}" class="btn">Confirm</a>
{% endblock %}
diff --git a/src/sentry/templates/sentry/emails/idp_verification_email.txt b/src/sentry/templates/sentry/emails/idp_verification_email.txt
index 98cbf55f3a5d17..d71f3cfd581b7a 100644
--- a/src/sentry/templates/sentry/emails/idp_verification_email.txt
+++ b/src/sentry/templates/sentry/emails/idp_verification_email.txt
@@ -1,5 +1,5 @@
-Please confirm your email ({{ confirm_email }}) by submitting the following code on the verification page: ({{ verification_key }}).
+Please confirm your email ({{ confirm_email }}) by clicking the link below.
-This code will expire in 10 minutes.
+{{ url|safe }}
-If you did not make this request, you may simply ignore this email.
+This link will expire in 10 minutes.
diff --git a/src/sentry/web/frontend/idp_email_verification.py b/src/sentry/web/frontend/idp_email_verification.py
new file mode 100644
index 00000000000000..8f6ac6ab403973
--- /dev/null
+++ b/src/sentry/web/frontend/idp_email_verification.py
@@ -0,0 +1,18 @@
+from django.http.response import HttpResponseNotFound, HttpResponseRedirect
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from sentry.auth.idpmigration import get_redis_key, verify_account
+from sentry.utils.auth import get_login_url
+
+
+def idp_confirm_email(request: Request, key: str) -> Response:
+ verification_key = get_redis_key(key)
+ if verify_account(key):
+ request.session["confirm_account_verification_key"] = verification_key
+ # TODO Change so it redirects to a confirmation page that needs to be made: Simple page with a confirmation msg and redirect to login
+ login = get_login_url()
+ redirect = HttpResponseRedirect(login)
+ return redirect
+ # TODO add view that shows key not found
+ return HttpResponseNotFound()
diff --git a/src/sentry/web/urls.py b/src/sentry/web/urls.py
index fc4ca972b2d633..667b8c4e037bc8 100644
--- a/src/sentry/web/urls.py
+++ b/src/sentry/web/urls.py
@@ -21,6 +21,7 @@
from sentry.web.frontend.group_plugin_action import GroupPluginActionView
from sentry.web.frontend.group_tag_export import GroupTagExportView
from sentry.web.frontend.home import HomeView
+from sentry.web.frontend.idp_email_verification import idp_confirm_email
from sentry.web.frontend.js_sdk_loader import JavaScriptSdkLoader
from sentry.web.frontend.mailgun_inbound_webhook import MailgunInboundWebhookView
from sentry.web.frontend.oauth_authorize import OAuthAuthorizeView
@@ -211,6 +212,11 @@
accounts.confirm_email,
name="sentry-account-confirm-email",
),
+ url(
+ r"^user-confirm/(?P<key>[^\/]+)/$",
+ idp_confirm_email,
+ name="sentry-idp-email-verification",
+ ),
url(r"^recover/$", accounts.recover, name="sentry-account-recover"),
url(
r"^recover/confirm/(?P<user_id>[\d]+)/(?P<hash>[0-9a-zA-Z]+)/$",
diff --git a/tests/sentry/auth/test_idpmigration.py b/tests/sentry/auth/test_idpmigration.py
index 9782b48dddf834..8e393e0da7162b 100644
--- a/tests/sentry/auth/test_idpmigration.py
+++ b/tests/sentry/auth/test_idpmigration.py
@@ -1,3 +1,5 @@
+from django.urls import reverse
+
import sentry.auth.idpmigration as idpmigration
from sentry.models import OrganizationMember
from sentry.testutils import TestCase
@@ -6,7 +8,9 @@
class IDPMigrationTests(TestCase):
def setUp(self):
+ super().setUp()
self.user = self.create_user()
+ self.login_as(self.user)
self.email = "[email protected]"
self.org = self.create_organization()
OrganizationMember.objects.create(organization=self.org, user=self.user)
@@ -20,5 +24,29 @@ def test_send_one_time_account_confirm_link(self, send_confirm_email):
assert send_confirm_email.call_args.args[1] == self.email
assert len(send_confirm_email.call_args.args[2]) == 32
- # TODO
- # def test_verify_new_identity(self):
+ def test_verify_account(self):
+ verification_key = idpmigration.send_one_time_account_confirm_link(
+ self.user, self.org, self.email, "drgUQCLzOyfHxmTyVs0G"
+ )
+ path = reverse(
+ "sentry-idp-email-verification",
+ args=[verification_key],
+ )
+ response = self.client.get(path)
+ assert (
+ self.client.session["confirm_account_verification_key"]
+ == f"auth:one-time-key:{verification_key}"
+ )
+ assert response.status_code == 302
+ assert response.url == "/auth/login/"
+
+ def test_verify_account_wrong_key(self):
+ idpmigration.send_one_time_account_confirm_link(
+ self.user, self.org, self.email, "drgUQCLzOyfHxmTyVs0G"
+ )
+ path = reverse(
+ "sentry-idp-email-verification",
+ args=["d14Ja9N2eQfPfVzcydS6vzcxWecZJG2z2"],
+ )
+ response = self.client.get(path)
+ assert response.status_code == 404
|
2aedf1d3df0cfaa396601952eeb177bf86ecdf69
|
2024-02-13 00:31:56
|
anthony sottile
|
ref: prevent sentry.auth.authenticators.u2f from reading the database at import time (#64952)
| false
|
prevent sentry.auth.authenticators.u2f from reading the database at import time (#64952)
|
ref
|
diff --git a/src/sentry/auth/authenticators/u2f.py b/src/sentry/auth/authenticators/u2f.py
index beb1de9e1e132d..17ba3f90286dce 100644
--- a/src/sentry/auth/authenticators/u2f.py
+++ b/src/sentry/auth/authenticators/u2f.py
@@ -1,4 +1,5 @@
from base64 import urlsafe_b64encode
+from functools import cached_property
from time import time
from urllib.parse import urlparse
@@ -53,11 +54,20 @@ class U2fInterface(AuthenticatorInterface):
"Chrome)."
)
allow_multi_enrollment = True
- # rp is a relying party for webauthn, this would be sentry.io for SAAS
- # and the prefix for self-hosted / dev environments
- rp_id = urlparse(_get_url_prefix()).hostname
- rp = PublicKeyCredentialRpEntity(rp_id, "Sentry")
- webauthn_registration_server = Fido2Server(rp)
+
+ @cached_property
+ def rp_id(self) -> str | None:
+ # rp is a relying party for webauthn, this would be sentry.io for SAAS
+ # and the prefix for self-hosted / dev environments
+ return urlparse(_get_url_prefix()).hostname
+
+ @cached_property
+ def rp(self) -> PublicKeyCredentialRpEntity:
+ return PublicKeyCredentialRpEntity(self.rp_id, "Sentry")
+
+ @cached_property
+ def webauthn_registration_server(self) -> Fido2Server:
+ return Fido2Server(self.rp)
def __init__(self, authenticator=None, status=EnrollmentStatus.EXISTING):
super().__init__(authenticator, status)
|
da574ee915cd5d5731cd3fbdc9e52dd34e15cd6c
|
2020-08-27 23:49:01
|
Lyn Nagara
|
test(snuba): Run the new Snuba migration system in Travis (#20418)
| false
|
Run the new Snuba migration system in Travis (#20418)
|
test
|
diff --git a/.travis.yml b/.travis.yml
index e0e778efae033a..1cdc352d5ab64d 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -93,7 +93,7 @@ start_snuba: &start_snuba |-
-e CLICKHOUSE_PORT=9000 \
getsentry/snuba
- docker exec sentry_snuba snuba migrate
+ docker exec sentry_snuba snuba migrations migrate --force
script:
- make travis-test-$TEST_SUITE
|
761beec8b85304f6077d8370e81f201717c980f8
|
2022-11-16 23:40:17
|
Jonas
|
feat(profiling): remove release helper fn (#41451)
| false
|
remove release helper fn (#41451)
|
feat
|
diff --git a/static/app/components/profiling/FrameStack/profileDetails.tsx b/static/app/components/profiling/FrameStack/profileDetails.tsx
index 958b1126ba46f1..c9c5c23549a937 100644
--- a/static/app/components/profiling/FrameStack/profileDetails.tsx
+++ b/static/app/components/profiling/FrameStack/profileDetails.tsx
@@ -11,7 +11,7 @@ import {t} from 'sentry/locale';
import OrganizationsStore from 'sentry/stores/organizationsStore';
import {useLegacyStore} from 'sentry/stores/useLegacyStore';
import space from 'sentry/styles/space';
-import type {PageFilters} from 'sentry/types';
+import {formatVersion} from 'sentry/utils/formatters';
import {FlamegraphPreferences} from 'sentry/utils/profiling/flamegraph/flamegraphStateProvider/reducers/flamegraphPreferences';
import {useFlamegraphPreferences} from 'sentry/utils/profiling/flamegraph/hooks/useFlamegraphPreferences';
import {
@@ -20,11 +20,8 @@ import {
} from 'sentry/utils/profiling/hooks/useResizableDrawer';
import {ProfileGroup} from 'sentry/utils/profiling/profile/importProfile';
import {makeFormatter} from 'sentry/utils/profiling/units/units';
-import usePageFilters from 'sentry/utils/usePageFilters';
import useProjects from 'sentry/utils/useProjects';
-import {formatVersion} from '../../../utils/formatters';
-
import {ProfilingDetailsFrameTabs, ProfilingDetailsListItem} from './frameStack';
function renderValue(
@@ -48,36 +45,11 @@ function renderValue(
return value;
}
-function getReleaseProjectId(
- release: Profiling.Schema['metadata']['release'],
- selection: PageFilters
-) {
- if (!release || !release.projects) {
- return undefined;
- }
- // if a release has only one project
- if (release.projects.length === 1) {
- return release.projects[0].id;
- }
-
- // if only one project is selected in global header and release has it (second condition will prevent false positives like -1)
- if (
- selection.projects.length === 1 &&
- release.projects.map(p => p.id).includes(selection.projects[0])
- ) {
- return selection.projects[0];
- }
-
- // project selector on release detail page will pick it up
- return undefined;
-}
-
interface ProfileDetailsProps {
profileGroup: ProfileGroup;
}
export function ProfileDetails(props: ProfileDetailsProps) {
- const pageFilters = usePageFilters();
const [detailsTab, setDetailsTab] = useState<'device' | 'transaction'>('transaction');
const organizations = useLegacyStore(OrganizationsStore);
@@ -232,6 +204,16 @@ export function ProfileDetails(props: ProfileDetailsProps) {
props.profileGroup.metadata.release
) {
const release = props.profileGroup.metadata.release;
+ // If a release only contains a version key, then we cannot link to it and
+ // fallback to just displaying the raw version value.
+ if (Object.keys(release).length <= 1 && release.version) {
+ return (
+ <DetailsRow key={key}>
+ <strong>{label}:</strong>
+ <span>{formatVersion(release.version)}</span>
+ </DetailsRow>
+ );
+ }
return (
<DetailsRow key={key}>
<strong>{label}:</strong>
@@ -241,7 +223,7 @@ export function ProfileDetails(props: ProfileDetailsProps) {
organization.slug
}/releases/${encodeURIComponent(release.version)}/`,
query: {
- project: getReleaseProjectId(release, pageFilters.selection),
+ project: props.profileGroup.metadata.projectID,
},
}}
>
|
aa5417455cd6e36984aacc79b96b26801b0384c1
|
2023-12-08 04:28:00
|
Ryan Albrecht
|
docs(stories): Add a story for the <Confirm> component (#61375)
| false
|
Add a story for the <Confirm> component (#61375)
|
docs
|
diff --git a/static/app/components/confirm.stories.tsx b/static/app/components/confirm.stories.tsx
new file mode 100644
index 00000000000000..f6232252ab3273
--- /dev/null
+++ b/static/app/components/confirm.stories.tsx
@@ -0,0 +1,186 @@
+/* eslint-disable no-console */
+
+import {Fragment, useState} from 'react';
+import styled from '@emotion/styled';
+
+import {Button} from 'sentry/components/button';
+import Confirm, {openConfirmModal} from 'sentry/components/confirm';
+import Link from 'sentry/components/links/link';
+import JSXNode from 'sentry/components/stories/jsxNode';
+import JSXProperty from 'sentry/components/stories/jsxProperty';
+import Matrix from 'sentry/components/stories/matrix';
+import SideBySide from 'sentry/components/stories/sideBySide';
+import storyBook from 'sentry/stories/storyBook';
+import {space} from 'sentry/styles/space';
+
+export default storyBook(Confirm, story => {
+ story('Triggers', () => (
+ <Fragment>
+ <p>
+ There are two way to use <JSXNode name="Confirm" />, either as a wrapper around a
+ trigger, or by calling <code>openConfirmModal()</code> in a callback.
+ </p>
+ <p>
+ It's recommended to call <code>openConfirmModal()</code>.
+ </p>
+ <SideBySide>
+ <Button onClick={() => openConfirmModal({})}>
+ <code>{'onClick={() => openConfirmModal({})}'}</code>
+ </Button>
+ <Confirm>
+ <Button>
+ Button is wrapped with <JSXNode name="Confirm" />
+ </Button>
+ </Confirm>
+ </SideBySide>
+ </Fragment>
+ ));
+
+ story('Labels', () => (
+ <Fragment>
+ <p>
+ You must implement at least <JSXProperty name="message" value={String} />, but
+ have the option of implementing{' '}
+ <JSXProperty name="renderMessage" value={Function} /> instead.
+ </p>
+ <SideBySide>
+ <Button
+ onClick={() =>
+ openConfirmModal({
+ header: 'Are you sure?',
+ message: 'You are about to delete everything.',
+ cancelText: 'No thanks',
+ confirmText: 'Just do it!',
+ priority: 'danger',
+ })
+ }
+ >
+ With String Labels
+ </Button>
+ <Button
+ onClick={() =>
+ openConfirmModal({
+ renderMessage: _props => (
+ <span>
+ You are about to delete <em>Everything!</em>
+ </span>
+ ),
+ renderCancelButton: ({closeModal}) => (
+ <Link
+ to="#"
+ onClick={e => {
+ closeModal();
+ e.stopPropagation();
+ }}
+ >
+ Nevermind
+ </Link>
+ ),
+ renderConfirmButton: ({defaultOnClick}) => (
+ <Button onClick={defaultOnClick}>Just do it</Button>
+ ),
+ })
+ }
+ >
+ With ReactNode Labels
+ </Button>
+ </SideBySide>
+ </Fragment>
+ ));
+
+ story('Callbacks & bypass={true}', () => {
+ const [callbacks, setCallbacks] = useState<string[]>([]);
+ return (
+ <Fragment>
+ <p>
+ There is also a prop called <JSXProperty name="bypass" value={Boolean} />. This
+ can help to skip the Confirm dialog, for example if not enough items are
+ selected in a bulk-change operation, and directly run the{' '}
+ <JSXProperty name="onConfirm" value={Function} /> callback.
+ </p>
+ <SideBySide>
+ <Button
+ onClick={() =>
+ openConfirmModal({
+ bypass: false,
+ onRender: () => setCallbacks(prev => prev.concat('onRender')),
+ onConfirming: () => setCallbacks(prev => prev.concat('onConfirming')),
+ onCancel: () => setCallbacks(prev => prev.concat('onCancel')),
+ onConfirm: () => setCallbacks(prev => prev.concat('onConfirm')),
+ onClose: () => setCallbacks(prev => prev.concat('onClose')),
+ })
+ }
+ >
+ With callbacks (bypass = false)
+ </Button>
+ <Button
+ onClick={() =>
+ openConfirmModal({
+ bypass: true,
+ onRender: () => setCallbacks(prev => prev.concat('onRender')),
+ onConfirming: () => setCallbacks(prev => prev.concat('onConfirming')),
+ onCancel: () => setCallbacks(prev => prev.concat('onCancel')),
+ onConfirm: () => setCallbacks(prev => prev.concat('onConfirm')),
+ onClose: () => setCallbacks(prev => prev.concat('onClose')),
+ })
+ }
+ >
+ With callbacks (bypass = true)
+ </Button>
+ </SideBySide>
+ <p>
+ <label>
+ Callback debugger:
+ <br />
+ <textarea rows={4} value={callbacks.join('\n')} />
+ <br />
+ <button onClick={() => setCallbacks([])}>Reset</button>
+ </label>
+ </p>
+ </Fragment>
+ );
+ });
+
+ story('<Confirm> child render func', () => (
+ <Fragment>
+ <p>
+ Here's an example where <JSXProperty name="children" value={Function} /> is a
+ render function:
+ </p>
+ <Confirm>{({open}) => <Button onClick={open}>Open the modal</Button>}</Confirm>
+ </Fragment>
+ ));
+
+ story('<Confirm> specific props', () => {
+ const [clicks, setClicks] = useState(0);
+
+ return (
+ <Fragment>
+ <p>
+ We can see how <JSXProperty name="disabled" value={Boolean} /> and
+ <JSXProperty name="stopPropagation" value={Boolean} /> work in combination.
+ </p>
+ <p>Button clicks: {clicks} </p>
+ <Matrix
+ propMatrix={{
+ disabled: [false, true],
+ stopPropagation: [false, true],
+ }}
+ render={props => (
+ <Button onClick={() => setClicks(prev => prev + 1)}>
+ <Confirm {...props}>
+ <ModalTrigger>Click the green area to open modal</ModalTrigger>
+ </Confirm>
+ </Button>
+ )}
+ selectedProps={['disabled', 'stopPropagation']}
+ />
+ </Fragment>
+ );
+ });
+});
+
+const ModalTrigger = styled('span')`
+ background: ${p => p.theme.green200};
+ padding: ${space(1)};
+`;
|
dc18d59c992c9688c29fa4aac476f6be902cd0dd
|
2023-09-19 18:41:40
|
Nar Saynorath
|
feat(stat-detectors): Add param to fetch all tags (#56434)
| false
|
Add param to fetch all tags (#56434)
|
feat
|
diff --git a/src/sentry/api/endpoints/organization_events_facets.py b/src/sentry/api/endpoints/organization_events_facets.py
index 5cd234fb207e5b..1587c8bb6ef2d0 100644
--- a/src/sentry/api/endpoints/organization_events_facets.py
+++ b/src/sentry/api/endpoints/organization_events_facets.py
@@ -82,6 +82,9 @@ def data_fn(offset, limit):
return list(resp.values())
+ if request.GET.get("includeAll"):
+ return Response(data_fn(0, 10000))
+
return self.paginate(
request=request,
paginator=GenericOffsetPaginator(data_fn=data_fn),
diff --git a/tests/snuba/api/endpoints/test_organization_events_facets.py b/tests/snuba/api/endpoints/test_organization_events_facets.py
index 7be4e33f706f8a..bbccd2b78b7d32 100644
--- a/tests/snuba/api/endpoints/test_organization_events_facets.py
+++ b/tests/snuba/api/endpoints/test_organization_events_facets.py
@@ -912,3 +912,21 @@ def test_multiple_pages_with_multiple_projects(self):
assert response.status_code == 200, response.content
assert links[1]["results"] == "false" # There should be no more tags to fetch
assert len(response.data) == 4 # 4 because projects and levels were added to the base 22
+
+ def test_get_all_tags(self):
+ test_project = self.create_project()
+ test_tags = {str(i): str(i) for i in range(22)}
+
+ self.store_event(
+ data={"event_id": uuid4().hex, "timestamp": self.min_ago_iso, "tags": test_tags},
+ project_id=test_project.id,
+ )
+
+ # Test the default query fetches the first 10 results
+ with self.feature(self.features):
+ response = self.client.get(
+ self.url, format="json", data={"project": test_project.id, "includeAll": True}
+ )
+
+ assert response.status_code == 200, response.content
+ assert len(response.data) == 23
|
d5b3c258e3fa89c32a5c0694514928bb9cea2e69
|
2020-02-14 22:16:06
|
Billy Vong
|
feat(workflow): Update Alert email with correct environments (#17033)
| false
|
Update Alert email with correct environments (#17033)
|
feat
|
diff --git a/src/sentry/incidents/action_handlers.py b/src/sentry/incidents/action_handlers.py
index cc880ed41d514c..b99f26415fcbc6 100644
--- a/src/sentry/incidents/action_handlers.py
+++ b/src/sentry/incidents/action_handlers.py
@@ -109,6 +109,10 @@ def generate_email_context(self, status):
# if resolve threshold and threshold type is *BELOW* then show '>'
# we can simplify this to be the below statement
show_greater_than_string = is_active == is_threshold_type_above
+ environments = list(alert_rule.environment.all())
+ environment_string = (
+ ", ".join(sorted([env.name for env in environments])) if len(environments) else "All"
+ )
return {
"link": absolute_uri(
@@ -131,8 +135,7 @@ def generate_email_context(self, status):
)
),
"incident_name": self.incident.title,
- # TODO(alerts): Add environment
- "environment": "All",
+ "environment": environment_string,
"time_window": format_duration(alert_rule.time_window),
"triggered_at": trigger.date_added,
"aggregate": self.query_aggregations_display[QueryAggregations(alert_rule.aggregation)],
diff --git a/src/sentry/testutils/factories.py b/src/sentry/testutils/factories.py
index 44bc86da930193..fe68a3ea338222 100644
--- a/src/sentry/testutils/factories.py
+++ b/src/sentry/testutils/factories.py
@@ -748,6 +748,7 @@ def create_incident(
date_closed=None,
groups=None,
seen_by=None,
+ alert_rule=None,
):
if not title:
title = petname.Generate(2, " ", letters=10).title()
@@ -758,6 +759,7 @@ def create_incident(
status=status,
title=title,
query=query,
+ alert_rule=alert_rule,
date_started=date_started or timezone.now(),
date_detected=date_detected or timezone.now(),
date_closed=date_closed or timezone.now(),
@@ -788,6 +790,7 @@ def create_alert_rule(
time_window=10,
threshold_period=1,
include_all_projects=False,
+ environment=None,
excluded_projects=None,
date_added=None,
):
@@ -802,6 +805,7 @@ def create_alert_rule(
aggregation,
time_window,
threshold_period,
+ environment=environment,
include_all_projects=include_all_projects,
excluded_projects=excluded_projects,
)
diff --git a/tests/sentry/incidents/test_action_handlers.py b/tests/sentry/incidents/test_action_handlers.py
index 3e6ec41eaf77ae..dd20d5af03a260 100644
--- a/tests/sentry/incidents/test_action_handlers.py
+++ b/tests/sentry/incidents/test_action_handlers.py
@@ -122,6 +122,19 @@ def test(self):
}
assert expected == handler.generate_email_context(status)
+ def test_environment(self):
+ status = TriggerStatus.ACTIVE
+ environments = [
+ self.create_environment(project=self.project, name="prod"),
+ self.create_environment(project=self.project, name="dev"),
+ ]
+ alert_rule = self.create_alert_rule(environment=environments)
+ alert_rule_trigger = self.create_alert_rule_trigger(alert_rule=alert_rule)
+ action = self.create_alert_rule_trigger_action(alert_rule_trigger=alert_rule_trigger)
+ incident = self.create_incident()
+ handler = EmailActionHandler(action, incident, self.project)
+ assert "dev, prod" == handler.generate_email_context(status).get("environment")
+
@freeze_time()
class EmailActionHandlerFireTest(TestCase):
|
a50398b5f23c64ca05794ef80d9a18e7fb94d656
|
2024-03-07 23:59:35
|
Richard Roggenkemper
|
chore(inbound-filters): Allow for turning on specific filters (#66477)
| false
|
Allow for turning on specific filters (#66477)
|
chore
|
diff --git a/src/sentry/api/helpers/default_inbound_filters.py b/src/sentry/api/helpers/default_inbound_filters.py
index 57706593a0260c..ecb0085f2c4a39 100644
--- a/src/sentry/api/helpers/default_inbound_filters.py
+++ b/src/sentry/api/helpers/default_inbound_filters.py
@@ -3,13 +3,16 @@
# Turns on certain inbound filters by default for project.
-def set_default_inbound_filters(project, organization):
- filters = [
+def set_default_inbound_filters(
+ project,
+ organization,
+ filters=(
"browser-extensions",
"legacy-browsers",
"web-crawlers",
"filtered-transaction",
- ]
+ ),
+):
if features.has("organizations:legacy-browser-update", organization):
browser_subfilters = [
"ie",
|
05f270b4d44c83d7d26fba3988f6f0d8046a075f
|
2018-04-03 04:50:02
|
Max Bittker
|
chore(hooks): don't format snapshots in commit hook (#7884)
| false
|
don't format snapshots in commit hook (#7884)
|
chore
|
diff --git a/src/sentry/lint/engine.py b/src/sentry/lint/engine.py
index d1d136c600c1a8..ec668023748f3c 100644
--- a/src/sentry/lint/engine.py
+++ b/src/sentry/lint/engine.py
@@ -78,12 +78,17 @@ def get_files_for_list(file_list):
return sorted(set(files_to_check))
-def get_js_files(file_list=None):
+def get_js_files(file_list=None, snapshots=False):
+ if snapshots:
+ extensions = ('.js', '.jsx', '.jsx.snap', '.js.snap')
+ else:
+ extensions = ('.js', '.jsx')
+
if file_list is None:
file_list = ['tests/js', 'src/sentry/static/sentry/app']
return [
x for x in get_files_for_list(file_list)
- if x.endswith(('.js', '.jsx', '.jsx.snap', '.js.snap'))
+ if x.endswith(extensions)
]
@@ -123,7 +128,7 @@ def js_lint(file_list=None, parseable=False, format=False):
echo('!! Skipping JavaScript linting because eslint is not installed.')
return False
- js_file_list = get_js_files(file_list)
+ js_file_list = get_js_files(file_list, snapshots=True)
has_errors = False
if js_file_list:
|
8e726d29016b7a32375b7008c899691fc334d05a
|
2018-04-10 02:50:14
|
Billy Vong
|
fix(ui): Fix redirect after inviting member to Org (#7959)
| false
|
Fix redirect after inviting member to Org (#7959)
|
fix
|
diff --git a/src/sentry/static/sentry/app/views/inviteMember/inviteMember.jsx b/src/sentry/static/sentry/app/views/inviteMember/inviteMember.jsx
index b624d8bca1e4ce..7e6d6189129a34 100644
--- a/src/sentry/static/sentry/app/views/inviteMember/inviteMember.jsx
+++ b/src/sentry/static/sentry/app/views/inviteMember/inviteMember.jsx
@@ -1,11 +1,11 @@
-import {browserHistory} from 'react-router';
+import {withRouter} from 'react-router';
+import PropTypes from 'prop-types';
import React from 'react';
-import createReactClass from 'create-react-class';
import classNames from 'classnames';
-import PropTypes from 'prop-types';
+import createReactClass from 'create-react-class';
-import {t} from '../../locale';
-import AlertActions from '../../actions/alertActions';
+import {addErrorMessage, addSuccessMessage} from '../../actionCreators/indicator';
+import {t, tct} from '../../locale';
import ApiMixin from '../../mixins/apiMixin';
import Button from '../../components/buttons/button';
import ConfigStore from '../../stores/configStore';
@@ -16,7 +16,7 @@ import SettingsPageHeader from '../settings/components/settingsPageHeader';
import TeamSelect from './teamSelect';
import TextBlock from '../settings/components/text/textBlock';
import TextField from '../../components/forms/textField';
-import recreateRoute from '../../utils/recreateRoute';
+import replaceRouterParams from '../../utils/replaceRouterParams';
// These don't have allowed and are only used for superusers. superceded by server result of allowed roles
const STATIC_ROLE_LIST = [
@@ -49,7 +49,7 @@ const STATIC_ROLE_LIST = [
const InviteMember = createReactClass({
displayName: 'InviteMember',
propTypes: {
- routes: PropTypes.array,
+ router: PropTypes.object,
},
mixins: [ApiMixin, OrganizationState],
@@ -114,12 +114,13 @@ const InviteMember = createReactClass({
redirectToMemberPage() {
// Get path to parent route (`/organizations/${slug}/members/`)
- let pathToParentRoute = recreateRoute('', {
- params: this.props.params,
- routes: this.props.routes,
- stepBack: -1,
- });
- browserHistory.push(pathToParentRoute);
+ // `recreateRoute` fucks up because of getsentry hooks
+ let {params, router} = this.props;
+ let isNewSettings = /^settings/.test(router.location.pathname);
+ let pathToParentRoute = isNewSettings
+ ? '/settings/:orgId/members/'
+ : '/organizations/:orgId/members/';
+ router.history.push(replaceRouterParams(pathToParentRoute, params));
},
splitEmails(text) {
@@ -144,25 +145,20 @@ const InviteMember = createReactClass({
referrer: this.props.location.query.referrer,
},
success: () => {
- // TODO(billy): Use indicator when these views only exist in Settings area
- AlertActions.addAlert({
- message: `Added ${email}`,
- type: 'success',
- });
+ addSuccessMessage(
+ tct('Added [email] to [organization]', {
+ email,
+ organization: slug,
+ })
+ );
resolve();
},
error: err => {
if (err.status === 403) {
- AlertActions.addAlert({
- message: t("You aren't allowed to invite members."),
- type: 'error',
- });
+ addErrorMessage(t("You aren't allowed to invite members."));
reject(err.responseJSON);
} else if (err.status === 409) {
- AlertActions.addAlert({
- message: `User already exists: ${email}`,
- type: 'info',
- });
+ addErrorMessage(`User already exists: ${email}`);
resolve();
} else {
reject(err.responseJSON);
@@ -262,4 +258,5 @@ const InviteMember = createReactClass({
},
});
-export default InviteMember;
+export {InviteMember};
+export default withRouter(InviteMember);
diff --git a/src/sentry/static/sentry/app/views/settings/organization/members/organizationMemberRow.jsx b/src/sentry/static/sentry/app/views/settings/organization/members/organizationMemberRow.jsx
index bdfaa3e53bf15c..76b10f2637980e 100644
--- a/src/sentry/static/sentry/app/views/settings/organization/members/organizationMemberRow.jsx
+++ b/src/sentry/static/sentry/app/views/settings/organization/members/organizationMemberRow.jsx
@@ -3,13 +3,14 @@ import PropTypes from 'prop-types';
import React from 'react';
import styled from 'react-emotion';
+import {PanelItem} from '../../../../components/panels';
import {t, tct} from '../../../../locale';
import Avatar from '../../../../components/avatar';
import Button from '../../../../components/buttons/button';
import Confirm from '../../../../components/confirm';
+import InlineSvg from '../../../../components/inlineSvg';
import Link from '../../../../components/link';
import LoadingIndicator from '../../../../components/loadingIndicator';
-import {PanelItem} from '../../../../components/panels';
import SentryTypes from '../../../../proptypes';
import Tooltip from '../../../../components/tooltip';
import recreateRoute from '../../../../utils/recreateRoute';
@@ -134,27 +135,23 @@ export default class OrganizationMemberRow extends React.PureComponent {
!isInviteSuccessful &&
canAddMembers &&
(pending || needsSso) && (
- <Button
+ <ResendInviteButton
priority="primary"
size="xsmall"
onClick={this.handleSendInvite}
- style={{
- padding: '0 4px',
- marginTop: 2,
- }}
>
{t('Resend invite')}
- </Button>
+ </ResendInviteButton>
)}
</div>
) : (
<div>
{!has2fa ? (
<Tooltip title={t('Two-factor auth not enabled')}>
- <span style={{color: '#B64236'}} className="icon-exclamation" />
+ <NoTwoFactorIcon />
</Tooltip>
) : (
- <span style={{color: 'green'}} className="icon-check" />
+ <HasTwoFactorIcon />
)}
</div>
)}
@@ -195,8 +192,9 @@ export default class OrganizationMemberRow extends React.PureComponent {
disabled
size="small"
title={t('You do not have access to remove member')}
+ icon="icon-circle-subtract"
>
- <span className="icon icon-trash" /> {t('Remove')}
+ {t('Remove')}
</Button>
)}
@@ -238,3 +236,21 @@ export default class OrganizationMemberRow extends React.PureComponent {
);
}
}
+
+const NoTwoFactorIcon = styled(props => (
+ <InlineSvg {...props} src="icon-circle-exclamation" />
+))`
+ color: ${p => p.theme.error};
+ font-size: 18px;
+`;
+const HasTwoFactorIcon = styled(props => (
+ <InlineSvg {...props} src="icon-circle-check" />
+))`
+ color: ${p => p.theme.success};
+ font-size: 18px;
+`;
+
+const ResendInviteButton = styled(Button)`
+ padding: 0 4px;
+ margin-top: 2px;
+`;
diff --git a/src/sentry/static/sentry/app/views/settings/organization/members/organizationMembersView.jsx b/src/sentry/static/sentry/app/views/settings/organization/members/organizationMembersView.jsx
index 6381bfd65c2815..9ab58b8728d60c 100644
--- a/src/sentry/static/sentry/app/views/settings/organization/members/organizationMembersView.jsx
+++ b/src/sentry/static/sentry/app/views/settings/organization/members/organizationMembersView.jsx
@@ -1,23 +1,22 @@
import {Box} from 'grid-emotion';
-import {browserHistory} from 'react-router';
import PropTypes from 'prop-types';
import React from 'react';
+import {Panel, PanelBody, PanelHeader} from '../../../../components/panels';
+import {addErrorMessage, addSuccessMessage} from '../../../../actionCreators/indicator';
import {t, tct} from '../../../../locale';
+import AsyncView from '../../../asyncView';
import Button from '../../../../components/buttons/button';
import ConfigStore from '../../../../stores/configStore';
-import IndicatorStore from '../../../../stores/indicatorStore';
+import GuideAnchor from '../../../../components/assistant/guideAnchor';
import OrganizationAccessRequests from './organizationAccessRequests';
import OrganizationMemberRow from './organizationMemberRow';
-import OrganizationSettingsView from '../../../organizationSettingsView';
import Pagination from '../../../../components/pagination';
-import {Panel, PanelBody, PanelHeader} from '../../../../components/panels';
import SentryTypes from '../../../../proptypes';
import SettingsPageHeader from '../../components/settingsPageHeader';
import recreateRoute from '../../../../utils/recreateRoute';
-import GuideAnchor from '../../../../components/assistant/guideAnchor';
-class OrganizationMembersView extends OrganizationSettingsView {
+class OrganizationMembersView extends AsyncView {
static propTypes = {
routes: PropTypes.array,
};
@@ -120,46 +119,42 @@ class OrganizationMembersView extends OrganizationSettingsView {
handleRemove = ({id, name}, e) => {
let {organization} = this.context;
- let {orgName} = organization;
+ let {slug: orgName} = organization;
this.removeMember(id).then(
() =>
- IndicatorStore.add(
+ addSuccessMessage(
tct('Removed [name] from [orgName]', {
name,
orgName,
- }),
- 'success'
+ })
),
() =>
- IndicatorStore.add(
+ addErrorMessage(
tct('Error removing [name] from [orgName]', {
name,
orgName,
- }),
- 'error'
+ })
)
);
};
handleLeave = ({id}, e) => {
let {organization} = this.context;
- let {orgName} = organization;
+ let {slug: orgName} = organization;
this.removeMember(id).then(
() =>
- IndicatorStore.add(
+ addSuccessMessage(
tct('You left [orgName]', {
orgName,
- }),
- 'success'
+ })
),
() =>
- IndicatorStore.add(
+ addErrorMessage(
tct('Error leaving [orgName]', {
orgName,
- }),
- 'error'
+ })
)
);
};
@@ -180,26 +175,7 @@ class OrganizationMembersView extends OrganizationSettingsView {
this.setState(state => ({
invited: state.invited.set(id, null),
}));
- IndicatorStore.add(t('Error sending invite'), 'error');
- },
- });
- };
-
- handleAddMember = () => {
- this.setState({
- busy: true,
- });
- this.api.request(`/organizations/${this.props.params.orgId}/members/`, {
- method: 'POST',
- data: {},
- success: data => {
- this.setState({busy: false});
- browserHistory.push(
- `/organizations/${this.props.params.orgId}/members/${data.id}`
- );
- },
- error: () => {
- this.setState({busy: false});
+ addErrorMessage(t('Error sending invite'));
},
});
};
diff --git a/tests/js/setup.js b/tests/js/setup.js
index be282a93d477fb..39ed692f5bef38 100644
--- a/tests/js/setup.js
+++ b/tests/js/setup.js
@@ -497,8 +497,9 @@ window.TestStubs = {
Members: () => [
{
id: '1',
- email: '',
- name: '',
+ email: '[email protected]',
+ name: 'Sentry 1 Name',
+ role: '',
roleName: '',
pending: false,
flags: {
@@ -514,16 +515,17 @@ window.TestStubs = {
},
{
id: '2',
- email: '',
- name: '',
+ name: 'Sentry 2 Name',
+ email: '[email protected]',
+ role: '',
roleName: '',
- pending: false,
+ pending: true,
flags: {
'sso:linked': false,
},
user: {
id: '2',
- has2fa: true,
+ has2fa: false,
name: 'Sentry 2 Name',
email: '[email protected]',
username: 'Sentry 2 Username',
@@ -531,9 +533,10 @@ window.TestStubs = {
},
{
id: '3',
- email: '',
- name: '',
- roleName: '',
+ name: 'Sentry 3 Name',
+ email: '[email protected]',
+ role: 'owner',
+ roleName: 'Owner',
pending: false,
flags: {
'sso:linked': true,
@@ -546,6 +549,24 @@ window.TestStubs = {
username: 'Sentry 3 Username',
},
},
+ {
+ id: '4',
+ name: 'Sentry 4 Name',
+ email: '[email protected]',
+ role: 'owner',
+ roleName: 'Owner',
+ pending: false,
+ flags: {
+ 'sso:linked': true,
+ },
+ user: {
+ id: '4',
+ has2fa: true,
+ name: 'Sentry 4 Name',
+ email: '[email protected]',
+ username: 'Sentry 4 Username',
+ },
+ },
],
Organization: params => {
diff --git a/tests/js/spec/views/__snapshots__/organizationMembersView.spec.jsx.snap b/tests/js/spec/views/__snapshots__/organizationMembersView.spec.jsx.snap
deleted file mode 100644
index ecaf1688777698..00000000000000
--- a/tests/js/spec/views/__snapshots__/organizationMembersView.spec.jsx.snap
+++ /dev/null
@@ -1,2622 +0,0 @@
-// Jest Snapshot v1, https://goo.gl/fbAQLP
-
-exports[`OrganizationMembersView No Require Link does not have 2fa warning if user has 2fa 1`] = `
-<OrganizationMembersView
- canAddMembers={false}
- canRemoveMembers={false}
- currentUser={
- Object {
- "email": "",
- "flags": Object {
- "sso:linked": false,
- },
- "id": "2",
- "name": "",
- "pending": false,
- "roleName": "",
- "user": Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "2",
- "name": "Sentry 2 Name",
- "username": "Sentry 2 Username",
- },
- }
- }
- memberCanLeave={false}
- onLeave={[Function]}
- onRemove={[Function]}
- onSendInvite={[Function]}
- orgId="org-slug"
- orgName="Organization Name"
- params={
- Object {
- "orgId": "org-id",
- }
- }
- requireLink={false}
- routes={Array []}
- status=""
->
- <SideEffect(DocumentTitle)
- title="Organization Name Members"
- >
- <DocumentTitle
- title="Organization Name Members"
- >
- <div>
- <SettingsPageHeading
- action={
- <GuideAnchor
- target="member_add"
- type="invisible"
- >
- <Button
- disabled={false}
- icon="icon-circle-add"
- priority="primary"
- size="small"
- title={undefined}
- to="new"
- >
- Invite Member
- </Button>
- </GuideAnchor>
- }
- title="Members"
- >
- <Wrapper>
- <div
- className="css-foidy-Wrapper css-17jmgia0"
- >
- <Flex
- align="center"
- >
- <Base
- align="center"
- className="css-5ipae5"
- >
- <div
- className="css-5ipae5"
- is={null}
- >
- <Title>
- <div
- className="css-zmdcxu-Title css-17jmgia1"
- >
- Members
- </div>
- </Title>
- <div>
- <GuideAnchor
- target="member_add"
- type="invisible"
- >
- <GuideAnchorContainer
- innerRef={[Function]}
- type="invisible"
- >
- <div
- className="css-kaem6e-GuideAnchorContainer css-1aiyb4m0"
- type="invisible"
- >
- <Button
- disabled={false}
- icon="icon-circle-add"
- priority="primary"
- size="small"
- to="new"
- >
- <Link
- className="button button-primary button-sm"
- disabled={false}
- onClick={[Function]}
- onlyActiveOnIndex={false}
- role="button"
- style={Object {}}
- to="new"
- >
- <a
- className="button button-primary button-sm"
- disabled={false}
- onClick={[Function]}
- role="button"
- style={Object {}}
- >
- <Flex
- align="center"
- className="button-label"
- >
- <Base
- align="center"
- className="button-label css-5ipae5"
- >
- <div
- className="button-label css-5ipae5"
- is={null}
- >
- <Icon
- size="small"
- >
- <Base
- className="css-11bwulm-Icon css-1vxxnb60"
- size="small"
- >
- <div
- className="css-11bwulm-Icon css-1vxxnb60"
- is={null}
- size="small"
- >
- <StyledInlineSvg
- size="12px"
- src="icon-circle-add"
- >
- <InlineSvg
- className="css-1ov3rcq-StyledInlineSvg css-1vxxnb61"
- size="12px"
- src="icon-circle-add"
- >
- <StyledSvg
- className="css-1ov3rcq-StyledInlineSvg css-1vxxnb61"
- height="12px"
- viewBox={Object {}}
- width="12px"
- >
- <svg
- className="css-1vxxnb61 css-1rlza0i-StyledSvg css-adkcw30"
- height="12px"
- viewBox={Object {}}
- width="12px"
- >
- <use
- href="#test"
- xlinkHref="#test"
- />
- </svg>
- </StyledSvg>
- </InlineSvg>
- </StyledInlineSvg>
- </div>
- </Base>
- </Icon>
- Invite Member
- </div>
- </Base>
- </Flex>
- </a>
- </Link>
- </Button>
- <StyledGuideAnchor
- active={false}
- className="guide-anchor-ping member_add"
- >
- <div
- className="guide-anchor-ping member_add css-1yndvnf-StyledGuideAnchor css-1aiyb4m1"
- >
- <StyledGuideAnchorRipples>
- <div
- className="css-1t9mqkr-StyledGuideAnchorRipples css-1aiyb4m2"
- />
- </StyledGuideAnchorRipples>
- </div>
- </StyledGuideAnchor>
- </div>
- </GuideAnchorContainer>
- </GuideAnchor>
- </div>
- </div>
- </Base>
- </Flex>
- </div>
- </Wrapper>
- </SettingsPageHeading>
- <OrganizationAccessRequests
- accessRequestBusy={Map {}}
- onApprove={[Function]}
- onDeny={[Function]}
- requestList={Array []}
- />
- <Panel>
- <StyledPanel>
- <div
- className="css-wfa8ap-StyledPanel css-5bw71w0"
- >
- <PanelHeader
- disablePadding={true}
- >
- <StyledPanelHeader
- disablePadding={true}
- >
- <Component
- className="css-18fb6u1-StyledPanelHeader css-1t1cqk30"
- disablePadding={true}
- >
- <Flex
- align="center"
- className="css-18fb6u1-StyledPanelHeader css-1t1cqk30"
- justify="space-between"
- >
- <Base
- align="center"
- className="css-1t1cqk30 css-1pqpjvf"
- justify="space-between"
- >
- <div
- className="css-1t1cqk30 css-1pqpjvf"
- is={null}
- >
- <Box
- flex="1"
- px={2}
- >
- <Base
- className="css-pcjga5"
- flex="1"
- px={2}
- >
- <div
- className="css-pcjga5"
- is={null}
- >
- Member
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={180}
- >
- <Base
- className="css-1pkva7q"
- px={2}
- w={180}
- >
- <div
- className="css-1pkva7q"
- is={null}
- >
- <GuideAnchor
- target="member_status"
- type="text"
- >
- <GuideAnchorContainer
- innerRef={[Function]}
- type="text"
- >
- <div
- className="css-9u5for-GuideAnchorContainer css-1aiyb4m0"
- type="text"
- >
- Status
- <StyledGuideAnchor
- active={false}
- className="guide-anchor-ping member_status"
- >
- <div
- className="guide-anchor-ping member_status css-1yndvnf-StyledGuideAnchor css-1aiyb4m1"
- >
- <StyledGuideAnchorRipples>
- <div
- className="css-1t9mqkr-StyledGuideAnchorRipples css-1aiyb4m2"
- />
- </StyledGuideAnchorRipples>
- </div>
- </StyledGuideAnchor>
- </div>
- </GuideAnchorContainer>
- </GuideAnchor>
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={140}
- >
- <Base
- className="css-1fsdpfi"
- px={2}
- w={140}
- >
- <div
- className="css-1fsdpfi"
- is={null}
- >
- <GuideAnchor
- target="member_role"
- type="text"
- >
- <GuideAnchorContainer
- innerRef={[Function]}
- type="text"
- >
- <div
- className="css-9u5for-GuideAnchorContainer css-1aiyb4m0"
- type="text"
- >
- Role
- <StyledGuideAnchor
- active={false}
- className="guide-anchor-ping member_role"
- >
- <div
- className="guide-anchor-ping member_role css-1yndvnf-StyledGuideAnchor css-1aiyb4m1"
- >
- <StyledGuideAnchorRipples>
- <div
- className="css-1t9mqkr-StyledGuideAnchorRipples css-1aiyb4m2"
- />
- </StyledGuideAnchorRipples>
- </div>
- </StyledGuideAnchor>
- </div>
- </GuideAnchorContainer>
- </GuideAnchor>
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={140}
- >
- <Base
- className="css-1fsdpfi"
- px={2}
- w={140}
- >
- <div
- className="css-1fsdpfi"
- is={null}
- >
- Actions
- </div>
- </Base>
- </Box>
- </div>
- </Base>
- </Flex>
- </Component>
- </StyledPanelHeader>
- </PanelHeader>
- <PanelBody
- direction="column"
- disablePadding={true}
- flex={false}
- >
- <div
- className=""
- >
- <OrganizationMemberRow
- canAddMembers={true}
- canRemoveMembers={false}
- currentUser={
- Object {
- "email": "",
- "flags": Object {
- "sso:linked": false,
- },
- "id": "2",
- "name": "",
- "pending": false,
- "roleName": "",
- "user": Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "2",
- "name": "Sentry 2 Name",
- "username": "Sentry 2 Username",
- },
- }
- }
- key="1"
- member={
- Object {
- "email": "",
- "flags": Object {
- "sso:linked": false,
- },
- "id": "1",
- "name": "",
- "pending": false,
- "roleName": "",
- "user": Object {
- "email": "[email protected]",
- "has2fa": false,
- "id": "1",
- "name": "Sentry 1 Name",
- "username": "Sentry 1 Username",
- },
- }
- }
- memberCanLeave={false}
- onLeave={[Function]}
- onRemove={[Function]}
- onSendInvite={[Function]}
- orgId="org-id"
- orgName="Organization Name"
- params={
- Object {
- "orgId": "org-id",
- }
- }
- requireLink={false}
- routes={Array []}
- >
- <PanelItem
- align="center"
- p={0}
- py={2}
- >
- <StyledPanelItem
- align="center"
- p={0}
- py={2}
- >
- <Base
- align="center"
- className="css-xw0gom-StyledPanelItem css-q9h14u0"
- p={0}
- py={2}
- >
- <div
- className="css-xw0gom-StyledPanelItem css-q9h14u0"
- is={null}
- >
- <Box
- pl={2}
- >
- <Base
- className="css-wwmrss"
- pl={2}
- >
- <div
- className="css-wwmrss"
- is={null}
- >
- <Avatar
- hasTooltip={false}
- size={32}
- user={
- Object {
- "email": "[email protected]",
- "has2fa": false,
- "id": "1",
- "name": "Sentry 1 Name",
- "username": "Sentry 1 Username",
- }
- }
- >
- <UserAvatar
- gravatar={true}
- hasTooltip={false}
- size={32}
- user={
- Object {
- "email": "[email protected]",
- "has2fa": false,
- "id": "1",
- "name": "Sentry 1 Name",
- "username": "Sentry 1 Username",
- }
- }
- >
- <BaseAvatar
- gravatar={true}
- gravatarId="[email protected]"
- hasTooltip={false}
- letterId="[email protected]"
- size={32}
- style={Object {}}
- title="Sentry 1 Name"
- tooltip="Sentry 1 Name ([email protected])"
- type="gravatar"
- >
- <Tooltip
- disabled={true}
- title="Sentry 1 Name ([email protected])"
- >
- <span
- className="avatar"
- style={
- Object {
- "height": "32px",
- "width": "32px",
- }
- }
- >
- <img
- onError={[Function]}
- onLoad={[Function]}
- src="undefined/avatar/c68ca8af553301ae11c5607b8bb672b4?d=blank&s=32"
- />
- </span>
- </Tooltip>
- </BaseAvatar>
- </UserAvatar>
- </Avatar>
- </div>
- </Base>
- </Box>
- <Box
- flex="1"
- pl={1}
- pr={2}
- >
- <Base
- className="css-1gj33kt"
- flex="1"
- pl={1}
- pr={2}
- >
- <div
- className="css-1gj33kt"
- is={null}
- >
- <h5
- style={
- Object {
- "margin": "0 0 3px",
- }
- }
- >
- <UserName
- to="1"
- >
- <Link
- className="css-16n40ob-UserName css-8j55k00"
- to="1"
- >
- <a
- className="css-16n40ob-UserName css-8j55k00"
- href="1"
- />
- </Link>
- </UserName>
- </h5>
- <Email>
- <div
- className="css-zq8exb-Email css-8j55k01"
- />
- </Email>
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={180}
- >
- <Base
- className="css-1pkva7q"
- px={2}
- w={180}
- >
- <div
- className="css-1pkva7q"
- is={null}
- >
- <div>
- <Tooltip
- title="Two-factor auth not enabled"
- >
- <span
- className="tip icon-exclamation"
- style={
- Object {
- "color": "#B64236",
- }
- }
- title="Two-factor auth not enabled"
- />
- </Tooltip>
- </div>
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={140}
- >
- <Base
- className="css-1fsdpfi"
- px={2}
- w={140}
- >
- <div
- className="css-1fsdpfi"
- is={null}
- />
- </Base>
- </Box>
- <Box
- px={2}
- w={140}
- >
- <Base
- className="css-1fsdpfi"
- px={2}
- w={140}
- >
- <div
- className="css-1fsdpfi"
- is={null}
- >
- <Button
- disabled={true}
- size="small"
- title="You cannot leave the organization as you are the only owner."
- >
- <button
- className="button tip button-default button-sm button-disabled"
- disabled={true}
- onClick={[Function]}
- role="button"
- >
- <Flex
- align="center"
- className="button-label"
- >
- <Base
- align="center"
- className="button-label css-5ipae5"
- >
- <div
- className="button-label css-5ipae5"
- is={null}
- >
- <span
- className="icon icon-exit"
- />
-
- Leave
- </div>
- </Base>
- </Flex>
- </button>
- </Button>
- </div>
- </Base>
- </Box>
- </div>
- </Base>
- </StyledPanelItem>
- </PanelItem>
- </OrganizationMemberRow>
- <OrganizationMemberRow
- canAddMembers={true}
- canRemoveMembers={false}
- currentUser={
- Object {
- "email": "",
- "flags": Object {
- "sso:linked": false,
- },
- "id": "2",
- "name": "",
- "pending": false,
- "roleName": "",
- "user": Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "2",
- "name": "Sentry 2 Name",
- "username": "Sentry 2 Username",
- },
- }
- }
- key="2"
- member={
- Object {
- "email": "",
- "flags": Object {
- "sso:linked": false,
- },
- "id": "2",
- "name": "",
- "pending": false,
- "roleName": "",
- "user": Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "2",
- "name": "Sentry 2 Name",
- "username": "Sentry 2 Username",
- },
- }
- }
- memberCanLeave={false}
- onLeave={[Function]}
- onRemove={[Function]}
- onSendInvite={[Function]}
- orgId="org-id"
- orgName="Organization Name"
- params={
- Object {
- "orgId": "org-id",
- }
- }
- requireLink={false}
- routes={Array []}
- >
- <PanelItem
- align="center"
- p={0}
- py={2}
- >
- <StyledPanelItem
- align="center"
- p={0}
- py={2}
- >
- <Base
- align="center"
- className="css-xw0gom-StyledPanelItem css-q9h14u0"
- p={0}
- py={2}
- >
- <div
- className="css-xw0gom-StyledPanelItem css-q9h14u0"
- is={null}
- >
- <Box
- pl={2}
- >
- <Base
- className="css-wwmrss"
- pl={2}
- >
- <div
- className="css-wwmrss"
- is={null}
- >
- <Avatar
- hasTooltip={false}
- size={32}
- user={
- Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "2",
- "name": "Sentry 2 Name",
- "username": "Sentry 2 Username",
- }
- }
- >
- <UserAvatar
- gravatar={true}
- hasTooltip={false}
- size={32}
- user={
- Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "2",
- "name": "Sentry 2 Name",
- "username": "Sentry 2 Username",
- }
- }
- >
- <BaseAvatar
- gravatar={true}
- gravatarId="[email protected]"
- hasTooltip={false}
- letterId="[email protected]"
- size={32}
- style={Object {}}
- title="Sentry 2 Name"
- tooltip="Sentry 2 Name ([email protected])"
- type="gravatar"
- >
- <Tooltip
- disabled={true}
- title="Sentry 2 Name ([email protected])"
- >
- <span
- className="avatar"
- style={
- Object {
- "height": "32px",
- "width": "32px",
- }
- }
- >
- <img
- onError={[Function]}
- onLoad={[Function]}
- src="undefined/avatar/4eca4e68b0a900e542fdf17e57d04dcd?d=blank&s=32"
- />
- </span>
- </Tooltip>
- </BaseAvatar>
- </UserAvatar>
- </Avatar>
- </div>
- </Base>
- </Box>
- <Box
- flex="1"
- pl={1}
- pr={2}
- >
- <Base
- className="css-1gj33kt"
- flex="1"
- pl={1}
- pr={2}
- >
- <div
- className="css-1gj33kt"
- is={null}
- >
- <h5
- style={
- Object {
- "margin": "0 0 3px",
- }
- }
- >
- <UserName
- to="2"
- >
- <Link
- className="css-16n40ob-UserName css-8j55k00"
- to="2"
- >
- <a
- className="css-16n40ob-UserName css-8j55k00"
- href="2"
- />
- </Link>
- </UserName>
- </h5>
- <Email>
- <div
- className="css-zq8exb-Email css-8j55k01"
- />
- </Email>
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={180}
- >
- <Base
- className="css-1pkva7q"
- px={2}
- w={180}
- >
- <div
- className="css-1pkva7q"
- is={null}
- >
- <div>
- <span
- className="icon-check"
- style={
- Object {
- "color": "green",
- }
- }
- />
- </div>
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={140}
- >
- <Base
- className="css-1fsdpfi"
- px={2}
- w={140}
- >
- <div
- className="css-1fsdpfi"
- is={null}
- />
- </Base>
- </Box>
- <Box
- px={2}
- w={140}
- >
- <Base
- className="css-1fsdpfi"
- px={2}
- w={140}
- >
- <div
- className="css-1fsdpfi"
- is={null}
- >
- <Button
- disabled={true}
- size="small"
- title="You cannot leave the organization as you are the only owner."
- >
- <button
- className="button tip button-default button-sm button-disabled"
- disabled={true}
- onClick={[Function]}
- role="button"
- >
- <Flex
- align="center"
- className="button-label"
- >
- <Base
- align="center"
- className="button-label css-5ipae5"
- >
- <div
- className="button-label css-5ipae5"
- is={null}
- >
- <span
- className="icon icon-exit"
- />
-
- Leave
- </div>
- </Base>
- </Flex>
- </button>
- </Button>
- </div>
- </Base>
- </Box>
- </div>
- </Base>
- </StyledPanelItem>
- </PanelItem>
- </OrganizationMemberRow>
- <OrganizationMemberRow
- canAddMembers={true}
- canRemoveMembers={false}
- currentUser={
- Object {
- "email": "",
- "flags": Object {
- "sso:linked": false,
- },
- "id": "2",
- "name": "",
- "pending": false,
- "roleName": "",
- "user": Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "2",
- "name": "Sentry 2 Name",
- "username": "Sentry 2 Username",
- },
- }
- }
- key="3"
- member={
- Object {
- "email": "",
- "flags": Object {
- "sso:linked": true,
- },
- "id": "3",
- "name": "",
- "pending": false,
- "roleName": "",
- "user": Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "3",
- "name": "Sentry 3 Name",
- "username": "Sentry 3 Username",
- },
- }
- }
- memberCanLeave={false}
- onLeave={[Function]}
- onRemove={[Function]}
- onSendInvite={[Function]}
- orgId="org-id"
- orgName="Organization Name"
- params={
- Object {
- "orgId": "org-id",
- }
- }
- requireLink={false}
- routes={Array []}
- >
- <PanelItem
- align="center"
- p={0}
- py={2}
- >
- <StyledPanelItem
- align="center"
- p={0}
- py={2}
- >
- <Base
- align="center"
- className="css-xw0gom-StyledPanelItem css-q9h14u0"
- p={0}
- py={2}
- >
- <div
- className="css-xw0gom-StyledPanelItem css-q9h14u0"
- is={null}
- >
- <Box
- pl={2}
- >
- <Base
- className="css-wwmrss"
- pl={2}
- >
- <div
- className="css-wwmrss"
- is={null}
- >
- <Avatar
- hasTooltip={false}
- size={32}
- user={
- Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "3",
- "name": "Sentry 3 Name",
- "username": "Sentry 3 Username",
- }
- }
- >
- <UserAvatar
- gravatar={true}
- hasTooltip={false}
- size={32}
- user={
- Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "3",
- "name": "Sentry 3 Name",
- "username": "Sentry 3 Username",
- }
- }
- >
- <BaseAvatar
- gravatar={true}
- gravatarId="[email protected]"
- hasTooltip={false}
- letterId="[email protected]"
- size={32}
- style={Object {}}
- title="Sentry 3 Name"
- tooltip="Sentry 3 Name ([email protected])"
- type="gravatar"
- >
- <Tooltip
- disabled={true}
- title="Sentry 3 Name ([email protected])"
- >
- <span
- className="avatar"
- style={
- Object {
- "height": "32px",
- "width": "32px",
- }
- }
- >
- <img
- onError={[Function]}
- onLoad={[Function]}
- src="undefined/avatar/40d78e2a4587a53a171944ffe71ee3d4?d=blank&s=32"
- />
- </span>
- </Tooltip>
- </BaseAvatar>
- </UserAvatar>
- </Avatar>
- </div>
- </Base>
- </Box>
- <Box
- flex="1"
- pl={1}
- pr={2}
- >
- <Base
- className="css-1gj33kt"
- flex="1"
- pl={1}
- pr={2}
- >
- <div
- className="css-1gj33kt"
- is={null}
- >
- <h5
- style={
- Object {
- "margin": "0 0 3px",
- }
- }
- >
- <UserName
- to="3"
- >
- <Link
- className="css-16n40ob-UserName css-8j55k00"
- to="3"
- >
- <a
- className="css-16n40ob-UserName css-8j55k00"
- href="3"
- />
- </Link>
- </UserName>
- </h5>
- <Email>
- <div
- className="css-zq8exb-Email css-8j55k01"
- />
- </Email>
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={180}
- >
- <Base
- className="css-1pkva7q"
- px={2}
- w={180}
- >
- <div
- className="css-1pkva7q"
- is={null}
- >
- <div>
- <span
- className="icon-check"
- style={
- Object {
- "color": "green",
- }
- }
- />
- </div>
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={140}
- >
- <Base
- className="css-1fsdpfi"
- px={2}
- w={140}
- >
- <div
- className="css-1fsdpfi"
- is={null}
- />
- </Base>
- </Box>
- <Box
- px={2}
- w={140}
- >
- <Base
- className="css-1fsdpfi"
- px={2}
- w={140}
- >
- <div
- className="css-1fsdpfi"
- is={null}
- >
- <Button
- disabled={true}
- size="small"
- title="You cannot leave the organization as you are the only owner."
- >
- <button
- className="button tip button-default button-sm button-disabled"
- disabled={true}
- onClick={[Function]}
- role="button"
- >
- <Flex
- align="center"
- className="button-label"
- >
- <Base
- align="center"
- className="button-label css-5ipae5"
- >
- <div
- className="button-label css-5ipae5"
- is={null}
- >
- <span
- className="icon icon-exit"
- />
-
- Leave
- </div>
- </Base>
- </Flex>
- </button>
- </Button>
- </div>
- </Base>
- </Box>
- </div>
- </Base>
- </StyledPanelItem>
- </PanelItem>
- </OrganizationMemberRow>
- </div>
- </PanelBody>
- </div>
- </StyledPanel>
- </Panel>
- <Pagination
- onCursor={[Function]}
- />
- </div>
- </DocumentTitle>
- </SideEffect(DocumentTitle)>
-</OrganizationMembersView>
-`;
-
-exports[`OrganizationMembersView Require Link does not have 2fa warning if user has 2fa 1`] = `
-<OrganizationMembersView
- canAddMembers={false}
- canRemoveMembers={false}
- currentUser={
- Object {
- "email": "",
- "flags": Object {
- "sso:linked": false,
- },
- "id": "2",
- "name": "",
- "pending": false,
- "roleName": "",
- "user": Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "2",
- "name": "Sentry 2 Name",
- "username": "Sentry 2 Username",
- },
- }
- }
- memberCanLeave={false}
- onLeave={[Function]}
- onRemove={[Function]}
- onSendInvite={[Function]}
- orgId="org-slug"
- orgName="Organization Name"
- params={
- Object {
- "orgId": "org-id",
- }
- }
- requireLink={false}
- routes={Array []}
- status=""
->
- <SideEffect(DocumentTitle)
- title="Organization Name Members"
- >
- <DocumentTitle
- title="Organization Name Members"
- >
- <div>
- <SettingsPageHeading
- action={
- <GuideAnchor
- target="member_add"
- type="invisible"
- >
- <Button
- disabled={false}
- icon="icon-circle-add"
- priority="primary"
- size="small"
- title={undefined}
- to="new"
- >
- Invite Member
- </Button>
- </GuideAnchor>
- }
- title="Members"
- >
- <Wrapper>
- <div
- className="css-foidy-Wrapper css-17jmgia0"
- >
- <Flex
- align="center"
- >
- <Base
- align="center"
- className="css-5ipae5"
- >
- <div
- className="css-5ipae5"
- is={null}
- >
- <Title>
- <div
- className="css-zmdcxu-Title css-17jmgia1"
- >
- Members
- </div>
- </Title>
- <div>
- <GuideAnchor
- target="member_add"
- type="invisible"
- >
- <GuideAnchorContainer
- innerRef={[Function]}
- type="invisible"
- >
- <div
- className="css-kaem6e-GuideAnchorContainer css-1aiyb4m0"
- type="invisible"
- >
- <Button
- disabled={false}
- icon="icon-circle-add"
- priority="primary"
- size="small"
- to="new"
- >
- <Link
- className="button button-primary button-sm"
- disabled={false}
- onClick={[Function]}
- onlyActiveOnIndex={false}
- role="button"
- style={Object {}}
- to="new"
- >
- <a
- className="button button-primary button-sm"
- disabled={false}
- onClick={[Function]}
- role="button"
- style={Object {}}
- >
- <Flex
- align="center"
- className="button-label"
- >
- <Base
- align="center"
- className="button-label css-5ipae5"
- >
- <div
- className="button-label css-5ipae5"
- is={null}
- >
- <Icon
- size="small"
- >
- <Base
- className="css-11bwulm-Icon css-1vxxnb60"
- size="small"
- >
- <div
- className="css-11bwulm-Icon css-1vxxnb60"
- is={null}
- size="small"
- >
- <StyledInlineSvg
- size="12px"
- src="icon-circle-add"
- >
- <InlineSvg
- className="css-1ov3rcq-StyledInlineSvg css-1vxxnb61"
- size="12px"
- src="icon-circle-add"
- >
- <StyledSvg
- className="css-1ov3rcq-StyledInlineSvg css-1vxxnb61"
- height="12px"
- viewBox={Object {}}
- width="12px"
- >
- <svg
- className="css-1vxxnb61 css-1rlza0i-StyledSvg css-adkcw30"
- height="12px"
- viewBox={Object {}}
- width="12px"
- >
- <use
- href="#test"
- xlinkHref="#test"
- />
- </svg>
- </StyledSvg>
- </InlineSvg>
- </StyledInlineSvg>
- </div>
- </Base>
- </Icon>
- Invite Member
- </div>
- </Base>
- </Flex>
- </a>
- </Link>
- </Button>
- <StyledGuideAnchor
- active={false}
- className="guide-anchor-ping member_add"
- >
- <div
- className="guide-anchor-ping member_add css-1yndvnf-StyledGuideAnchor css-1aiyb4m1"
- >
- <StyledGuideAnchorRipples>
- <div
- className="css-1t9mqkr-StyledGuideAnchorRipples css-1aiyb4m2"
- />
- </StyledGuideAnchorRipples>
- </div>
- </StyledGuideAnchor>
- </div>
- </GuideAnchorContainer>
- </GuideAnchor>
- </div>
- </div>
- </Base>
- </Flex>
- </div>
- </Wrapper>
- </SettingsPageHeading>
- <OrganizationAccessRequests
- accessRequestBusy={Map {}}
- onApprove={[Function]}
- onDeny={[Function]}
- requestList={Array []}
- />
- <Panel>
- <StyledPanel>
- <div
- className="css-wfa8ap-StyledPanel css-5bw71w0"
- >
- <PanelHeader
- disablePadding={true}
- >
- <StyledPanelHeader
- disablePadding={true}
- >
- <Component
- className="css-18fb6u1-StyledPanelHeader css-1t1cqk30"
- disablePadding={true}
- >
- <Flex
- align="center"
- className="css-18fb6u1-StyledPanelHeader css-1t1cqk30"
- justify="space-between"
- >
- <Base
- align="center"
- className="css-1t1cqk30 css-1pqpjvf"
- justify="space-between"
- >
- <div
- className="css-1t1cqk30 css-1pqpjvf"
- is={null}
- >
- <Box
- flex="1"
- px={2}
- >
- <Base
- className="css-pcjga5"
- flex="1"
- px={2}
- >
- <div
- className="css-pcjga5"
- is={null}
- >
- Member
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={180}
- >
- <Base
- className="css-1pkva7q"
- px={2}
- w={180}
- >
- <div
- className="css-1pkva7q"
- is={null}
- >
- <GuideAnchor
- target="member_status"
- type="text"
- >
- <GuideAnchorContainer
- innerRef={[Function]}
- type="text"
- >
- <div
- className="css-9u5for-GuideAnchorContainer css-1aiyb4m0"
- type="text"
- >
- Status
- <StyledGuideAnchor
- active={false}
- className="guide-anchor-ping member_status"
- >
- <div
- className="guide-anchor-ping member_status css-1yndvnf-StyledGuideAnchor css-1aiyb4m1"
- >
- <StyledGuideAnchorRipples>
- <div
- className="css-1t9mqkr-StyledGuideAnchorRipples css-1aiyb4m2"
- />
- </StyledGuideAnchorRipples>
- </div>
- </StyledGuideAnchor>
- </div>
- </GuideAnchorContainer>
- </GuideAnchor>
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={140}
- >
- <Base
- className="css-1fsdpfi"
- px={2}
- w={140}
- >
- <div
- className="css-1fsdpfi"
- is={null}
- >
- <GuideAnchor
- target="member_role"
- type="text"
- >
- <GuideAnchorContainer
- innerRef={[Function]}
- type="text"
- >
- <div
- className="css-9u5for-GuideAnchorContainer css-1aiyb4m0"
- type="text"
- >
- Role
- <StyledGuideAnchor
- active={false}
- className="guide-anchor-ping member_role"
- >
- <div
- className="guide-anchor-ping member_role css-1yndvnf-StyledGuideAnchor css-1aiyb4m1"
- >
- <StyledGuideAnchorRipples>
- <div
- className="css-1t9mqkr-StyledGuideAnchorRipples css-1aiyb4m2"
- />
- </StyledGuideAnchorRipples>
- </div>
- </StyledGuideAnchor>
- </div>
- </GuideAnchorContainer>
- </GuideAnchor>
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={140}
- >
- <Base
- className="css-1fsdpfi"
- px={2}
- w={140}
- >
- <div
- className="css-1fsdpfi"
- is={null}
- >
- Actions
- </div>
- </Base>
- </Box>
- </div>
- </Base>
- </Flex>
- </Component>
- </StyledPanelHeader>
- </PanelHeader>
- <PanelBody
- direction="column"
- disablePadding={true}
- flex={false}
- >
- <div
- className=""
- >
- <OrganizationMemberRow
- canAddMembers={true}
- canRemoveMembers={false}
- currentUser={
- Object {
- "email": "",
- "flags": Object {
- "sso:linked": false,
- },
- "id": "2",
- "name": "",
- "pending": false,
- "roleName": "",
- "user": Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "2",
- "name": "Sentry 2 Name",
- "username": "Sentry 2 Username",
- },
- }
- }
- key="1"
- member={
- Object {
- "email": "",
- "flags": Object {
- "sso:linked": false,
- },
- "id": "1",
- "name": "",
- "pending": false,
- "roleName": "",
- "user": Object {
- "email": "[email protected]",
- "has2fa": false,
- "id": "1",
- "name": "Sentry 1 Name",
- "username": "Sentry 1 Username",
- },
- }
- }
- memberCanLeave={false}
- onLeave={[Function]}
- onRemove={[Function]}
- onSendInvite={[Function]}
- orgId="org-id"
- orgName="Organization Name"
- params={
- Object {
- "orgId": "org-id",
- }
- }
- requireLink={true}
- routes={Array []}
- >
- <PanelItem
- align="center"
- p={0}
- py={2}
- >
- <StyledPanelItem
- align="center"
- p={0}
- py={2}
- >
- <Base
- align="center"
- className="css-xw0gom-StyledPanelItem css-q9h14u0"
- p={0}
- py={2}
- >
- <div
- className="css-xw0gom-StyledPanelItem css-q9h14u0"
- is={null}
- >
- <Box
- pl={2}
- >
- <Base
- className="css-wwmrss"
- pl={2}
- >
- <div
- className="css-wwmrss"
- is={null}
- >
- <Avatar
- hasTooltip={false}
- size={32}
- user={
- Object {
- "email": "[email protected]",
- "has2fa": false,
- "id": "1",
- "name": "Sentry 1 Name",
- "username": "Sentry 1 Username",
- }
- }
- >
- <UserAvatar
- gravatar={true}
- hasTooltip={false}
- size={32}
- user={
- Object {
- "email": "[email protected]",
- "has2fa": false,
- "id": "1",
- "name": "Sentry 1 Name",
- "username": "Sentry 1 Username",
- }
- }
- >
- <BaseAvatar
- gravatar={true}
- gravatarId="[email protected]"
- hasTooltip={false}
- letterId="[email protected]"
- size={32}
- style={Object {}}
- title="Sentry 1 Name"
- tooltip="Sentry 1 Name ([email protected])"
- type="gravatar"
- >
- <Tooltip
- disabled={true}
- title="Sentry 1 Name ([email protected])"
- >
- <span
- className="avatar"
- style={
- Object {
- "height": "32px",
- "width": "32px",
- }
- }
- >
- <img
- onError={[Function]}
- onLoad={[Function]}
- src="undefined/avatar/c68ca8af553301ae11c5607b8bb672b4?d=blank&s=32"
- />
- </span>
- </Tooltip>
- </BaseAvatar>
- </UserAvatar>
- </Avatar>
- </div>
- </Base>
- </Box>
- <Box
- flex="1"
- pl={1}
- pr={2}
- >
- <Base
- className="css-1gj33kt"
- flex="1"
- pl={1}
- pr={2}
- >
- <div
- className="css-1gj33kt"
- is={null}
- >
- <h5
- style={
- Object {
- "margin": "0 0 3px",
- }
- }
- >
- <UserName
- to="1"
- >
- <Link
- className="css-16n40ob-UserName css-8j55k00"
- to="1"
- >
- <a
- className="css-16n40ob-UserName css-8j55k00"
- href="1"
- />
- </Link>
- </UserName>
- </h5>
- <Email>
- <div
- className="css-zq8exb-Email css-8j55k01"
- />
- </Email>
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={180}
- >
- <Base
- className="css-1pkva7q"
- px={2}
- w={180}
- >
- <div
- className="css-1pkva7q"
- is={null}
- >
- <div>
- <div>
- <strong>
- Missing SSO Link
- </strong>
- </div>
- <Button
- disabled={false}
- onClick={[Function]}
- priority="primary"
- size="xsmall"
- style={
- Object {
- "marginTop": 2,
- "padding": "0 4px",
- }
- }
- >
- <button
- className="button button-primary button-xs"
- disabled={false}
- onClick={[Function]}
- role="button"
- style={
- Object {
- "marginTop": 2,
- "padding": "0 4px",
- }
- }
- >
- <Flex
- align="center"
- className="button-label"
- >
- <Base
- align="center"
- className="button-label css-5ipae5"
- >
- <div
- className="button-label css-5ipae5"
- is={null}
- >
- Resend invite
- </div>
- </Base>
- </Flex>
- </button>
- </Button>
- </div>
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={140}
- >
- <Base
- className="css-1fsdpfi"
- px={2}
- w={140}
- >
- <div
- className="css-1fsdpfi"
- is={null}
- />
- </Base>
- </Box>
- <Box
- px={2}
- w={140}
- >
- <Base
- className="css-1fsdpfi"
- px={2}
- w={140}
- >
- <div
- className="css-1fsdpfi"
- is={null}
- >
- <Button
- disabled={true}
- size="small"
- title="You cannot leave the organization as you are the only owner."
- >
- <button
- className="button tip button-default button-sm button-disabled"
- disabled={true}
- onClick={[Function]}
- role="button"
- >
- <Flex
- align="center"
- className="button-label"
- >
- <Base
- align="center"
- className="button-label css-5ipae5"
- >
- <div
- className="button-label css-5ipae5"
- is={null}
- >
- <span
- className="icon icon-exit"
- />
-
- Leave
- </div>
- </Base>
- </Flex>
- </button>
- </Button>
- </div>
- </Base>
- </Box>
- </div>
- </Base>
- </StyledPanelItem>
- </PanelItem>
- </OrganizationMemberRow>
- <OrganizationMemberRow
- canAddMembers={true}
- canRemoveMembers={false}
- currentUser={
- Object {
- "email": "",
- "flags": Object {
- "sso:linked": false,
- },
- "id": "2",
- "name": "",
- "pending": false,
- "roleName": "",
- "user": Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "2",
- "name": "Sentry 2 Name",
- "username": "Sentry 2 Username",
- },
- }
- }
- key="2"
- member={
- Object {
- "email": "",
- "flags": Object {
- "sso:linked": false,
- },
- "id": "2",
- "name": "",
- "pending": false,
- "roleName": "",
- "user": Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "2",
- "name": "Sentry 2 Name",
- "username": "Sentry 2 Username",
- },
- }
- }
- memberCanLeave={false}
- onLeave={[Function]}
- onRemove={[Function]}
- onSendInvite={[Function]}
- orgId="org-id"
- orgName="Organization Name"
- params={
- Object {
- "orgId": "org-id",
- }
- }
- requireLink={true}
- routes={Array []}
- >
- <PanelItem
- align="center"
- p={0}
- py={2}
- >
- <StyledPanelItem
- align="center"
- p={0}
- py={2}
- >
- <Base
- align="center"
- className="css-xw0gom-StyledPanelItem css-q9h14u0"
- p={0}
- py={2}
- >
- <div
- className="css-xw0gom-StyledPanelItem css-q9h14u0"
- is={null}
- >
- <Box
- pl={2}
- >
- <Base
- className="css-wwmrss"
- pl={2}
- >
- <div
- className="css-wwmrss"
- is={null}
- >
- <Avatar
- hasTooltip={false}
- size={32}
- user={
- Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "2",
- "name": "Sentry 2 Name",
- "username": "Sentry 2 Username",
- }
- }
- >
- <UserAvatar
- gravatar={true}
- hasTooltip={false}
- size={32}
- user={
- Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "2",
- "name": "Sentry 2 Name",
- "username": "Sentry 2 Username",
- }
- }
- >
- <BaseAvatar
- gravatar={true}
- gravatarId="[email protected]"
- hasTooltip={false}
- letterId="[email protected]"
- size={32}
- style={Object {}}
- title="Sentry 2 Name"
- tooltip="Sentry 2 Name ([email protected])"
- type="gravatar"
- >
- <Tooltip
- disabled={true}
- title="Sentry 2 Name ([email protected])"
- >
- <span
- className="avatar"
- style={
- Object {
- "height": "32px",
- "width": "32px",
- }
- }
- >
- <img
- onError={[Function]}
- onLoad={[Function]}
- src="undefined/avatar/4eca4e68b0a900e542fdf17e57d04dcd?d=blank&s=32"
- />
- </span>
- </Tooltip>
- </BaseAvatar>
- </UserAvatar>
- </Avatar>
- </div>
- </Base>
- </Box>
- <Box
- flex="1"
- pl={1}
- pr={2}
- >
- <Base
- className="css-1gj33kt"
- flex="1"
- pl={1}
- pr={2}
- >
- <div
- className="css-1gj33kt"
- is={null}
- >
- <h5
- style={
- Object {
- "margin": "0 0 3px",
- }
- }
- >
- <UserName
- to="2"
- >
- <Link
- className="css-16n40ob-UserName css-8j55k00"
- to="2"
- >
- <a
- className="css-16n40ob-UserName css-8j55k00"
- href="2"
- />
- </Link>
- </UserName>
- </h5>
- <Email>
- <div
- className="css-zq8exb-Email css-8j55k01"
- />
- </Email>
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={180}
- >
- <Base
- className="css-1pkva7q"
- px={2}
- w={180}
- >
- <div
- className="css-1pkva7q"
- is={null}
- >
- <div>
- <div>
- <strong>
- Missing SSO Link
- </strong>
- </div>
- <Button
- disabled={false}
- onClick={[Function]}
- priority="primary"
- size="xsmall"
- style={
- Object {
- "marginTop": 2,
- "padding": "0 4px",
- }
- }
- >
- <button
- className="button button-primary button-xs"
- disabled={false}
- onClick={[Function]}
- role="button"
- style={
- Object {
- "marginTop": 2,
- "padding": "0 4px",
- }
- }
- >
- <Flex
- align="center"
- className="button-label"
- >
- <Base
- align="center"
- className="button-label css-5ipae5"
- >
- <div
- className="button-label css-5ipae5"
- is={null}
- >
- Resend invite
- </div>
- </Base>
- </Flex>
- </button>
- </Button>
- </div>
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={140}
- >
- <Base
- className="css-1fsdpfi"
- px={2}
- w={140}
- >
- <div
- className="css-1fsdpfi"
- is={null}
- />
- </Base>
- </Box>
- <Box
- px={2}
- w={140}
- >
- <Base
- className="css-1fsdpfi"
- px={2}
- w={140}
- >
- <div
- className="css-1fsdpfi"
- is={null}
- >
- <Button
- disabled={true}
- size="small"
- title="You cannot leave the organization as you are the only owner."
- >
- <button
- className="button tip button-default button-sm button-disabled"
- disabled={true}
- onClick={[Function]}
- role="button"
- >
- <Flex
- align="center"
- className="button-label"
- >
- <Base
- align="center"
- className="button-label css-5ipae5"
- >
- <div
- className="button-label css-5ipae5"
- is={null}
- >
- <span
- className="icon icon-exit"
- />
-
- Leave
- </div>
- </Base>
- </Flex>
- </button>
- </Button>
- </div>
- </Base>
- </Box>
- </div>
- </Base>
- </StyledPanelItem>
- </PanelItem>
- </OrganizationMemberRow>
- <OrganizationMemberRow
- canAddMembers={true}
- canRemoveMembers={false}
- currentUser={
- Object {
- "email": "",
- "flags": Object {
- "sso:linked": false,
- },
- "id": "2",
- "name": "",
- "pending": false,
- "roleName": "",
- "user": Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "2",
- "name": "Sentry 2 Name",
- "username": "Sentry 2 Username",
- },
- }
- }
- key="3"
- member={
- Object {
- "email": "",
- "flags": Object {
- "sso:linked": true,
- },
- "id": "3",
- "name": "",
- "pending": false,
- "roleName": "",
- "user": Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "3",
- "name": "Sentry 3 Name",
- "username": "Sentry 3 Username",
- },
- }
- }
- memberCanLeave={false}
- onLeave={[Function]}
- onRemove={[Function]}
- onSendInvite={[Function]}
- orgId="org-id"
- orgName="Organization Name"
- params={
- Object {
- "orgId": "org-id",
- }
- }
- requireLink={true}
- routes={Array []}
- >
- <PanelItem
- align="center"
- p={0}
- py={2}
- >
- <StyledPanelItem
- align="center"
- p={0}
- py={2}
- >
- <Base
- align="center"
- className="css-xw0gom-StyledPanelItem css-q9h14u0"
- p={0}
- py={2}
- >
- <div
- className="css-xw0gom-StyledPanelItem css-q9h14u0"
- is={null}
- >
- <Box
- pl={2}
- >
- <Base
- className="css-wwmrss"
- pl={2}
- >
- <div
- className="css-wwmrss"
- is={null}
- >
- <Avatar
- hasTooltip={false}
- size={32}
- user={
- Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "3",
- "name": "Sentry 3 Name",
- "username": "Sentry 3 Username",
- }
- }
- >
- <UserAvatar
- gravatar={true}
- hasTooltip={false}
- size={32}
- user={
- Object {
- "email": "[email protected]",
- "has2fa": true,
- "id": "3",
- "name": "Sentry 3 Name",
- "username": "Sentry 3 Username",
- }
- }
- >
- <BaseAvatar
- gravatar={true}
- gravatarId="[email protected]"
- hasTooltip={false}
- letterId="[email protected]"
- size={32}
- style={Object {}}
- title="Sentry 3 Name"
- tooltip="Sentry 3 Name ([email protected])"
- type="gravatar"
- >
- <Tooltip
- disabled={true}
- title="Sentry 3 Name ([email protected])"
- >
- <span
- className="avatar"
- style={
- Object {
- "height": "32px",
- "width": "32px",
- }
- }
- >
- <img
- onError={[Function]}
- onLoad={[Function]}
- src="undefined/avatar/40d78e2a4587a53a171944ffe71ee3d4?d=blank&s=32"
- />
- </span>
- </Tooltip>
- </BaseAvatar>
- </UserAvatar>
- </Avatar>
- </div>
- </Base>
- </Box>
- <Box
- flex="1"
- pl={1}
- pr={2}
- >
- <Base
- className="css-1gj33kt"
- flex="1"
- pl={1}
- pr={2}
- >
- <div
- className="css-1gj33kt"
- is={null}
- >
- <h5
- style={
- Object {
- "margin": "0 0 3px",
- }
- }
- >
- <UserName
- to="3"
- >
- <Link
- className="css-16n40ob-UserName css-8j55k00"
- to="3"
- >
- <a
- className="css-16n40ob-UserName css-8j55k00"
- href="3"
- />
- </Link>
- </UserName>
- </h5>
- <Email>
- <div
- className="css-zq8exb-Email css-8j55k01"
- />
- </Email>
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={180}
- >
- <Base
- className="css-1pkva7q"
- px={2}
- w={180}
- >
- <div
- className="css-1pkva7q"
- is={null}
- >
- <div>
- <span
- className="icon-check"
- style={
- Object {
- "color": "green",
- }
- }
- />
- </div>
- </div>
- </Base>
- </Box>
- <Box
- px={2}
- w={140}
- >
- <Base
- className="css-1fsdpfi"
- px={2}
- w={140}
- >
- <div
- className="css-1fsdpfi"
- is={null}
- />
- </Base>
- </Box>
- <Box
- px={2}
- w={140}
- >
- <Base
- className="css-1fsdpfi"
- px={2}
- w={140}
- >
- <div
- className="css-1fsdpfi"
- is={null}
- >
- <Button
- disabled={true}
- size="small"
- title="You cannot leave the organization as you are the only owner."
- >
- <button
- className="button tip button-default button-sm button-disabled"
- disabled={true}
- onClick={[Function]}
- role="button"
- >
- <Flex
- align="center"
- className="button-label"
- >
- <Base
- align="center"
- className="button-label css-5ipae5"
- >
- <div
- className="button-label css-5ipae5"
- is={null}
- >
- <span
- className="icon icon-exit"
- />
-
- Leave
- </div>
- </Base>
- </Flex>
- </button>
- </Button>
- </div>
- </Base>
- </Box>
- </div>
- </Base>
- </StyledPanelItem>
- </PanelItem>
- </OrganizationMemberRow>
- </div>
- </PanelBody>
- </div>
- </StyledPanel>
- </Panel>
- <Pagination
- onCursor={[Function]}
- />
- </div>
- </DocumentTitle>
- </SideEffect(DocumentTitle)>
-</OrganizationMembersView>
-`;
diff --git a/tests/js/spec/views/__snapshots__/teamMembers.spec.jsx.snap b/tests/js/spec/views/__snapshots__/teamMembers.spec.jsx.snap
index fdc435ea681f3a..9c79cd7e13339d 100644
--- a/tests/js/spec/views/__snapshots__/teamMembers.spec.jsx.snap
+++ b/tests/js/spec/views/__snapshots__/teamMembers.spec.jsx.snap
@@ -40,13 +40,14 @@ exports[`TeamMembers render() renders 1`] = `
orgId="org-slug"
user={
Object {
- "email": "",
+ "email": "[email protected]",
"flags": Object {
"sso:linked": false,
},
"id": "1",
- "name": "",
+ "name": "Sentry 1 Name",
"pending": false,
+ "role": "",
"roleName": "",
"user": Object {
"email": "[email protected]",
@@ -84,17 +85,18 @@ exports[`TeamMembers render() renders 1`] = `
orgId="org-slug"
user={
Object {
- "email": "",
+ "email": "[email protected]",
"flags": Object {
"sso:linked": false,
},
"id": "2",
- "name": "",
- "pending": false,
+ "name": "Sentry 2 Name",
+ "pending": true,
+ "role": "",
"roleName": "",
"user": Object {
"email": "[email protected]",
- "has2fa": true,
+ "has2fa": false,
"id": "2",
"name": "Sentry 2 Name",
"username": "Sentry 2 Username",
@@ -128,14 +130,15 @@ exports[`TeamMembers render() renders 1`] = `
orgId="org-slug"
user={
Object {
- "email": "",
+ "email": "[email protected]",
"flags": Object {
"sso:linked": true,
},
"id": "3",
- "name": "",
+ "name": "Sentry 3 Name",
"pending": false,
- "roleName": "",
+ "role": "owner",
+ "roleName": "Owner",
"user": Object {
"email": "[email protected]",
"has2fa": true,
@@ -164,5 +167,50 @@ exports[`TeamMembers render() renders 1`] = `
Remove
</Button>
</StyledMemberContainer>
+ <StyledMemberContainer
+ key="3"
+ >
+ <UserBadge
+ avatarSize={36}
+ orgId="org-slug"
+ user={
+ Object {
+ "email": "[email protected]",
+ "flags": Object {
+ "sso:linked": true,
+ },
+ "id": "4",
+ "name": "Sentry 4 Name",
+ "pending": false,
+ "role": "owner",
+ "roleName": "Owner",
+ "user": Object {
+ "email": "[email protected]",
+ "has2fa": true,
+ "id": "4",
+ "name": "Sentry 4 Name",
+ "username": "Sentry 4 Username",
+ },
+ }
+ }
+ userLink={true}
+ />
+ <Button
+ disabled={false}
+ onClick={[Function]}
+ size="small"
+ >
+ <InlineSvg
+ size="1.25em"
+ src="icon-circle-subtract"
+ style={
+ Object {
+ "marginRight": "8px",
+ }
+ }
+ />
+ Remove
+ </Button>
+ </StyledMemberContainer>
</Panel>
`;
diff --git a/tests/js/spec/views/inviteMember/inviteMember.spec.jsx b/tests/js/spec/views/inviteMember/inviteMember.spec.jsx
index e9035586d001ad..acbda719c6ed7e 100644
--- a/tests/js/spec/views/inviteMember/inviteMember.spec.jsx
+++ b/tests/js/spec/views/inviteMember/inviteMember.spec.jsx
@@ -2,8 +2,7 @@ import React from 'react';
import PropTypes from 'prop-types';
import {shallow, mount} from 'enzyme';
import _ from 'lodash';
-import InviteMember from 'app/views/inviteMember/inviteMember';
-import {Client} from 'app/api';
+import {InviteMember} from 'app/views/inviteMember/inviteMember';
import ConfigStore from 'app/stores/configStore';
jest.mock('app/api');
@@ -15,7 +14,7 @@ describe('CreateProject', function() {
beforeEach(function() {
sandbox = sinon.sandbox.create();
sandbox.stub(ConfigStore, 'getConfig').returns({id: 1, invitesEnabled: true});
- Client.clearMockResponses();
+ MockApiClient.clearMockResponses();
});
afterEach(function() {
@@ -56,7 +55,7 @@ describe('CreateProject', function() {
});
it('should render no team select when there is only one option', function() {
- Client.addMockResponse({
+ MockApiClient.addMockResponse({
url: '/organizations/testOrg/members/me/',
body: {
roles: [
@@ -95,7 +94,7 @@ describe('CreateProject', function() {
});
it('should redirect when no roles available', function() {
- Client.addMockResponse({
+ MockApiClient.addMockResponse({
url: '/organizations/testOrg/members/me/',
body: {
roles: [
@@ -122,7 +121,7 @@ describe('CreateProject', function() {
});
it('should render roles when available and allowed, and handle submitting', function() {
- Client.addMockResponse({
+ MockApiClient.addMockResponse({
url: '/organizations/testOrg/members/me/',
body: {
roles: [
@@ -139,7 +138,7 @@ describe('CreateProject', function() {
body: {},
};
- let mock = Client.addMockResponse(inviteRequest);
+ let mock = MockApiClient.addMockResponse(inviteRequest);
let wrapper = mount(<InviteMember {...baseProps} />, baseContext);
diff --git a/tests/js/spec/views/organizationMemberRow.spec.jsx b/tests/js/spec/views/organizationMemberRow.spec.jsx
index d18d92aa82fddf..c5b8756d18771d 100644
--- a/tests/js/spec/views/organizationMemberRow.spec.jsx
+++ b/tests/js/spec/views/organizationMemberRow.spec.jsx
@@ -59,7 +59,8 @@ describe('OrganizationMemberRow', function() {
}}
/>
);
- expect(wrapper.find('.icon-exclamation')).toHaveLength(0);
+ expect(wrapper.find('NoTwoFactorIcon')).toHaveLength(0);
+ expect(wrapper.find('HasTwoFactorIcon')).toHaveLength(1);
});
it('has 2fa warning if user does not have 2fa enabled', function() {
@@ -75,7 +76,8 @@ describe('OrganizationMemberRow', function() {
}}
/>
);
- expect(wrapper.find('.icon-exclamation')).toHaveLength(1);
+ expect(wrapper.find('NoTwoFactorIcon')).toHaveLength(1);
+ expect(wrapper.find('HasTwoFactorIcon')).toHaveLength(0);
});
describe('Pending user', function() {
@@ -100,7 +102,7 @@ describe('OrganizationMemberRow', function() {
expect(findWithText(wrapper.find('strong'), 'Invited')).toHaveLength(1);
- expect(findWithText(wrapper.find('Button'), 'Resend invite')).toHaveLength(0);
+ expect(wrapper.find('ResendInviteButton')).toHaveLength(0);
});
it('has "Resend Invite" button only if `canAddMembers` is true', function() {
@@ -108,13 +110,13 @@ describe('OrganizationMemberRow', function() {
expect(findWithText(wrapper.find('strong'), 'Invited')).toHaveLength(1);
- expect(findWithText(wrapper.find('Button'), 'Resend invite')).toHaveLength(1);
+ expect(wrapper.find('ResendInviteButton')).toHaveLength(1);
});
it('has the right inviting states', function() {
let wrapper = shallow(<OrganizationMemberRow {...props} canAddMembers={true} />);
- expect(findWithText(wrapper.find('Button'), 'Resend invite')).toHaveLength(1);
+ expect(wrapper.find('ResendInviteButton')).toHaveLength(1);
wrapper = shallow(
<OrganizationMemberRow {...props} canAddMembers={true} status="loading" />
@@ -123,7 +125,7 @@ describe('OrganizationMemberRow', function() {
// Should have loader
expect(wrapper.find('LoadingIndicator')).toHaveLength(1);
// No Resend Invite button
- expect(findWithText(wrapper.find('Button'), 'Resend invite')).toHaveLength(0);
+ expect(wrapper.find('ResendInviteButton')).toHaveLength(0);
wrapper = shallow(
<OrganizationMemberRow {...props} canAddMembers={true} status="success" />
@@ -132,7 +134,7 @@ describe('OrganizationMemberRow', function() {
// Should have loader
expect(wrapper.find('LoadingIndicator')).toHaveLength(0);
// No Resend Invite button
- expect(findWithText(wrapper.find('Button'), 'Resend invite')).toHaveLength(0);
+ expect(wrapper.find('ResendInviteButton')).toHaveLength(0);
expect(findWithText(wrapper.find('span'), 'Sent!')).toHaveLength(1);
});
});
@@ -159,7 +161,7 @@ describe('OrganizationMemberRow', function() {
expect(findWithText(wrapper.find('strong'), 'Invited')).toHaveLength(1);
- expect(findWithText(wrapper.find('Button'), 'Resend invite')).toHaveLength(0);
+ expect(wrapper.find('ResendInviteButton')).toHaveLength(0);
});
it('shows "missing SSO link" message if user is registered and needs link', function() {
@@ -174,7 +176,7 @@ describe('OrganizationMemberRow', function() {
expect(findWithText(wrapper.find('strong'), 'Invited')).toHaveLength(0);
expect(findWithText(wrapper.find('strong'), 'Missing SSO Link')).toHaveLength(1);
- expect(findWithText(wrapper.find('Button'), 'Resend invite')).toHaveLength(0);
+ expect(wrapper.find('ResendInviteButton')).toHaveLength(0);
});
it('has "Resend Invite" button only if `canAddMembers` is true and no link', function() {
@@ -188,7 +190,7 @@ describe('OrganizationMemberRow', function() {
/>
);
- expect(findWithText(wrapper.find('Button'), 'Resend invite')).toHaveLength(1);
+ expect(wrapper.find('ResendInviteButton')).toHaveLength(1);
});
it('has 2fa warning if user is linked does not have 2fa enabled', function() {
@@ -207,7 +209,8 @@ describe('OrganizationMemberRow', function() {
}}
/>
);
- expect(wrapper.find('.icon-exclamation')).toHaveLength(1);
+ expect(wrapper.find('NoTwoFactorIcon')).toHaveLength(1);
+ expect(wrapper.find('HasTwoFactorIcon')).toHaveLength(0);
});
});
diff --git a/tests/js/spec/views/organizationMembersView.spec.jsx b/tests/js/spec/views/organizationMembersView.spec.jsx
index 5c9a69beed3328..d575799f9719ad 100644
--- a/tests/js/spec/views/organizationMembersView.spec.jsx
+++ b/tests/js/spec/views/organizationMembersView.spec.jsx
@@ -1,15 +1,17 @@
-import PropTypes from 'prop-types';
import React from 'react';
import {Client} from 'app/api';
import {mount} from 'enzyme';
import ConfigStore from 'app/stores/configStore';
import OrganizationMembersView from 'app/views/settings/organization/members/organizationMembersView';
+import {addSuccessMessage, addErrorMessage} from 'app/actionCreators/indicator';
jest.mock('app/api');
+jest.mock('app/actionCreators/indicator');
describe('OrganizationMembersView', function() {
- let currentUser = TestStubs.Members()[1];
+ let members = TestStubs.Members();
+ let currentUser = members[1];
let defaultProps = {
orgId: 'org-slug',
orgName: 'Organization Name',
@@ -24,6 +26,9 @@ describe('OrganizationMembersView', function() {
onRemove: () => {},
onLeave: () => {},
};
+ let organization = TestStubs.Organization({
+ access: ['member:admin', 'org:admin'],
+ });
beforeAll(function() {
sinon.stub(ConfigStore, 'get', () => currentUser);
@@ -43,77 +48,252 @@ describe('OrganizationMembersView', function() {
Client.addMockResponse({
url: '/organizations/org-id/access-requests/',
method: 'GET',
- body: [],
+ body: [
+ {
+ id: 'pending-id',
+ member: {
+ id: 'pending-member-id',
+ email: '',
+ name: '',
+ roleName: '',
+ user: {
+ id: '',
+ name: '[email protected]',
+ },
+ },
+ team: TestStubs.Team(),
+ },
+ ],
+ });
+ Client.addMockResponse({
+ url: '/organizations/org-id/auth-provider/',
+ method: 'GET',
+ body: {
+ ...TestStubs.AuthProvider(),
+ require_link: true,
+ },
});
});
- describe('Require Link', function() {
- beforeEach(function() {
- Client.addMockResponse({
- url: '/organizations/org-id/auth-provider/',
- method: 'GET',
- body: {
- ...TestStubs.AuthProvider(),
- require_link: true,
- },
- });
+ it('can remove a member', async function() {
+ let deleteMock = Client.addMockResponse({
+ url: `/organizations/org-id/members/${members[0].id}/`,
+ method: 'DELETE',
});
- it('does not have 2fa warning if user has 2fa', function() {
- let wrapper = mount(
- <OrganizationMembersView
- {...defaultProps}
- params={{
- orgId: 'org-id',
- }}
- />,
- {
- childContextTypes: {
- router: PropTypes.object,
- },
- context: {
- organization: TestStubs.Organization(),
- router: TestStubs.router(),
- },
- }
- );
+ let wrapper = mount(
+ <OrganizationMembersView
+ {...defaultProps}
+ params={{
+ orgId: 'org-id',
+ }}
+ />,
+ TestStubs.routerContext([{organization}])
+ );
+
+ wrapper
+ .find('Button[icon="icon-circle-subtract"]')
+ .at(0)
+ .simulate('click');
+
+ await tick();
+
+ // Confirm modal
+ wrapper.find('ModalDialog Button[priority="primary"]').simulate('click');
+ await tick();
- expect(wrapper).toMatchSnapshot();
+ expect(deleteMock).toHaveBeenCalled();
+ expect(addSuccessMessage).toHaveBeenCalled();
+ });
+
+ it('displays error message when failing to remove member', async function() {
+ let deleteMock = Client.addMockResponse({
+ url: `/organizations/org-id/members/${members[0].id}/`,
+ method: 'DELETE',
+ statusCode: 500,
});
+
+ let wrapper = mount(
+ <OrganizationMembersView
+ {...defaultProps}
+ params={{
+ orgId: 'org-id',
+ }}
+ />,
+ TestStubs.routerContext([{organization}])
+ );
+
+ wrapper
+ .find('Button[icon="icon-circle-subtract"]')
+ .at(0)
+ .simulate('click');
+
+ await tick();
+
+ // Confirm modal
+ wrapper.find('ModalDialog Button[priority="primary"]').simulate('click');
+ await tick();
+ expect(deleteMock).toHaveBeenCalled();
+ await tick();
+ expect(addErrorMessage).toHaveBeenCalled();
});
- describe('No Require Link', function() {
- beforeEach(function() {
- Client.addMockResponse({
- url: '/organizations/org-id/auth-provider/',
- method: 'GET',
- body: {
- ...TestStubs.AuthProvider(),
- require_link: false,
- },
- });
+ it('can leave org', async function() {
+ let deleteMock = Client.addMockResponse({
+ url: `/organizations/org-id/members/${members[1].id}/`,
+ method: 'DELETE',
});
- it('does not have 2fa warning if user has 2fa', function() {
- let wrapper = mount(
- <OrganizationMembersView
- {...defaultProps}
- params={{
- orgId: 'org-id',
- }}
- />,
- {
- childContextTypes: {
- router: PropTypes.object,
- },
- context: {
- organization: TestStubs.Organization(),
- router: TestStubs.router(),
- },
- }
- );
+ let wrapper = mount(
+ <OrganizationMembersView
+ {...defaultProps}
+ params={{
+ orgId: 'org-id',
+ }}
+ />,
+ TestStubs.routerContext([{organization}])
+ );
+
+ wrapper
+ .find('Button[priority="danger"]')
+ .at(0)
+ .simulate('click');
- expect(wrapper).toMatchSnapshot();
+ await tick();
+
+ // Confirm modal
+ wrapper.find('ModalDialog Button[priority="primary"]').simulate('click');
+ await tick();
+
+ expect(deleteMock).toHaveBeenCalled();
+ expect(addSuccessMessage).toHaveBeenCalled();
+ });
+
+ it('displays error message when failing to leave org', async function() {
+ let deleteMock = Client.addMockResponse({
+ url: `/organizations/org-id/members/${members[1].id}/`,
+ method: 'DELETE',
+ statusCode: 500,
+ });
+
+ let wrapper = mount(
+ <OrganizationMembersView
+ {...defaultProps}
+ params={{
+ orgId: 'org-id',
+ }}
+ />,
+ TestStubs.routerContext([{organization}])
+ );
+
+ wrapper
+ .find('Button[priority="danger"]')
+ .at(0)
+ .simulate('click');
+
+ await tick();
+
+ // Confirm modal
+ wrapper.find('ModalDialog Button[priority="primary"]').simulate('click');
+ await tick();
+ expect(deleteMock).toHaveBeenCalled();
+ await tick();
+ expect(addErrorMessage).toHaveBeenCalled();
+ });
+
+ it('can re-send invite to member', async function() {
+ let inviteMock = MockApiClient.addMockResponse({
+ url: `/organizations/org-id/members/${members[0].id}/`,
+ method: 'PUT',
+ body: {
+ id: '1234',
+ },
+ });
+ let wrapper = mount(
+ <OrganizationMembersView
+ {...defaultProps}
+ params={{
+ orgId: 'org-id',
+ }}
+ />,
+ TestStubs.routerContext()
+ );
+
+ expect(inviteMock).not.toHaveBeenCalled();
+
+ wrapper
+ .find('ResendInviteButton')
+ .first()
+ .simulate('click');
+
+ await tick();
+ expect(inviteMock).toHaveBeenCalled();
+ });
+
+ it('can approve pending access request', async function() {
+ let approveMock = MockApiClient.addMockResponse({
+ url: '/organizations/org-id/access-requests/pending-id/',
+ method: 'PUT',
});
+ let wrapper = mount(
+ <OrganizationMembersView
+ {...defaultProps}
+ params={{
+ orgId: 'org-id',
+ }}
+ />,
+ TestStubs.routerContext()
+ );
+
+ expect(approveMock).not.toHaveBeenCalled();
+
+ wrapper
+ .find('OrganizationAccessRequests Button[priority="primary"]')
+ .simulate('click');
+
+ await tick();
+
+ expect(approveMock).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ data: {
+ isApproved: true,
+ },
+ })
+ );
+ });
+
+ it('can deny pending access request', async function() {
+ let denyMock = MockApiClient.addMockResponse({
+ url: '/organizations/org-id/access-requests/pending-id/',
+ method: 'PUT',
+ });
+ let wrapper = mount(
+ <OrganizationMembersView
+ {...defaultProps}
+ params={{
+ orgId: 'org-id',
+ }}
+ />,
+ TestStubs.routerContext()
+ );
+
+ expect(denyMock).not.toHaveBeenCalled();
+
+ wrapper
+ .find('OrganizationAccessRequests Button')
+ .at(1)
+ .simulate('click');
+
+ await tick();
+
+ expect(denyMock).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ data: {
+ isApproved: false,
+ },
+ })
+ );
});
});
|
46bca38c3722ddf565cacf14eec052eb96f9d22d
|
2021-11-05 23:53:57
|
Leander Rodrigues
|
fix(slack): Allow identity unlinking from slack. (#29818)
| false
|
Allow identity unlinking from slack. (#29818)
|
fix
|
diff --git a/src/sentry/api/endpoints/external_team_details.py b/src/sentry/api/endpoints/external_team_details.py
index 34622a2ddd040c..bd2e341e3750cc 100644
--- a/src/sentry/api/endpoints/external_team_details.py
+++ b/src/sentry/api/endpoints/external_team_details.py
@@ -63,8 +63,5 @@ def delete(self, request: Request, team: Team, external_team: ExternalActor) ->
"""
Delete an External Team
"""
- self.assert_has_feature(request, team.organization)
-
external_team.delete()
-
return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/src/sentry/api/endpoints/external_user_details.py b/src/sentry/api/endpoints/external_user_details.py
index d16263b924304a..0995d2ed02477c 100644
--- a/src/sentry/api/endpoints/external_user_details.py
+++ b/src/sentry/api/endpoints/external_user_details.py
@@ -65,7 +65,5 @@ def delete(
"""
Delete an External Team
"""
- self.assert_has_feature(request, organization)
-
external_user.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/static/app/views/settings/organizationTeams/teamNotifications.tsx b/static/app/views/settings/organizationTeams/teamNotifications.tsx
index e57140c01d5900..ea947d7a79daf5 100644
--- a/static/app/views/settings/organizationTeams/teamNotifications.tsx
+++ b/static/app/views/settings/organizationTeams/teamNotifications.tsx
@@ -141,7 +141,7 @@ class TeamNotificationSettings extends AsyncView<Props, State> {
<DeleteButtonWrapper>
<Tooltip
title={t(
- "You must have the 'team:write' permission to remove a Slack team link"
+ 'You must be an organization owner, manager or admin to remove a Slack team link'
)}
disabled={hasAccess}
>
diff --git a/tests/sentry/api/endpoints/test_external_team_details.py b/tests/sentry/api/endpoints/test_external_team_details.py
index 88a14633235eef..23f2e93bf302c9 100644
--- a/tests/sentry/api/endpoints/test_external_team_details.py
+++ b/tests/sentry/api/endpoints/test_external_team_details.py
@@ -15,10 +15,9 @@ def setUp(self):
)
def test_basic_delete(self):
- with self.feature({"organizations:integrations-codeowners": True}):
- self.get_success_response(
- self.organization.slug, self.team.slug, self.external_team.id, method="delete"
- )
+ self.get_success_response(
+ self.organization.slug, self.team.slug, self.external_team.id, method="delete"
+ )
assert not ExternalActor.objects.filter(id=str(self.external_team.id)).exists()
def test_basic_update(self):
diff --git a/tests/sentry/api/endpoints/test_external_user_details.py b/tests/sentry/api/endpoints/test_external_user_details.py
index f22c61295508ed..efec8313f35701 100644
--- a/tests/sentry/api/endpoints/test_external_user_details.py
+++ b/tests/sentry/api/endpoints/test_external_user_details.py
@@ -14,10 +14,7 @@ def setUp(self):
)
def test_basic_delete(self):
- with self.feature({"organizations:integrations-codeowners": True}):
- self.get_success_response(
- self.organization.slug, self.external_user.id, method="delete"
- )
+ self.get_success_response(self.organization.slug, self.external_user.id, method="delete")
assert not ExternalActor.objects.filter(id=str(self.external_user.id)).exists()
def test_basic_update(self):
|
32344e69ee53ee4d3e3d0bc8ef0ad2e96660bccd
|
2020-05-07 04:53:53
|
Dan Fuller
|
refs(subscriptions): Update subscriptions to support v2 format. Log request data. (#18648)
| false
|
Update subscriptions to support v2 format. Log request data. (#18648)
|
refs
|
diff --git a/src/sentry/snuba/json_schemas.py b/src/sentry/snuba/json_schemas.py
index 54d1f5b26edd05..586c77930b6dfa 100644
--- a/src/sentry/snuba/json_schemas.py
+++ b/src/sentry/snuba/json_schemas.py
@@ -33,5 +33,30 @@
},
"required": ["subscription_id", "values", "timestamp"],
"additionalProperties": False,
- }
+ },
+ 2: {
+ "type": "object",
+ "properties": {
+ "subscription_id": {"type": "string", "minLength": 1},
+ "request": {"type": "object"},
+ "result": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "type": "object",
+ "minProperties": 1,
+ "additionalProperties": {"type": "number"},
+ },
+ }
+ },
+ "required": ["data"],
+ },
+ "timestamp": {"type": "string", "format": "date-time"},
+ },
+ "required": ["subscription_id", "request", "result", "timestamp"],
+ "additionalProperties": False,
+ },
}
diff --git a/src/sentry/snuba/query_subscription_consumer.py b/src/sentry/snuba/query_subscription_consumer.py
index 79a00e371c4b7d..01c56a43e5b7c7 100644
--- a/src/sentry/snuba/query_subscription_consumer.py
+++ b/src/sentry/snuba/query_subscription_consumer.py
@@ -200,6 +200,7 @@ def handle_message(self, message):
"timestamp": contents["timestamp"],
"query_subscription_id": contents["subscription_id"],
"project_id": subscription.project_id,
+ "request": contents.get("request"),
"subscription_dataset": subscription.dataset,
"subscription_query": subscription.query,
"subscription_aggregation": subscription.aggregation,
@@ -248,6 +249,11 @@ def parse_message_value(self, value):
except jsonschema.ValidationError:
metrics.incr("snuba_query_subscriber.message_payload_invalid")
raise InvalidSchemaError("Message payload does not match schema")
+ # XXX: Since we just return the raw dict here, when the payload changes it'll
+ # break things. This should convert the payload into a class rather than passing
+ # the dict around, but until we get time to refactor we can keep things working
+ # here.
+ payload.setdefault("values", payload.get("result"))
payload["timestamp"] = parse_date(payload["timestamp"]).replace(tzinfo=pytz.utc)
return payload
diff --git a/tests/sentry/snuba/test_query_subscription_consumer.py b/tests/sentry/snuba/test_query_subscription_consumer.py
index 1de34f24704ede..87d819b0e89381 100644
--- a/tests/sentry/snuba/test_query_subscription_consumer.py
+++ b/tests/sentry/snuba/test_query_subscription_consumer.py
@@ -30,16 +30,25 @@ def consumer(self):
@fixture
def valid_wrapper(self):
- return {"version": 1, "payload": self.valid_payload}
+ return {"version": 2, "payload": self.valid_payload}
@fixture
- def valid_payload(self):
+ def old_payload(self):
return {
"subscription_id": "1234",
"values": {"data": [{"hello": 50}]},
"timestamp": "2020-01-01T01:23:45.1234",
}
+ @fixture
+ def valid_payload(self):
+ return {
+ "subscription_id": "1234",
+ "result": {"data": [{"hello": 50}]},
+ "request": {"some": "data"},
+ "timestamp": "2020-01-01T01:23:45.1234",
+ }
+
def build_mock_message(self, data, topic=None):
message = Mock()
message.value.return_value = json.dumps(data)
@@ -104,6 +113,8 @@ def test_subscription_registered(self):
data = self.valid_wrapper
data["payload"]["subscription_id"] = sub.subscription_id
self.consumer.handle_message(self.build_mock_message(data))
+ data = deepcopy(data)
+ data["payload"]["values"] = data["payload"]["result"]
data["payload"]["timestamp"] = parse_date(data["payload"]["timestamp"]).replace(
tzinfo=pytz.utc
)
@@ -125,15 +136,15 @@ def run_invalid_payload_test(self, remove_fields=None, update_fields=None):
payload.pop(field)
if update_fields:
payload.update(update_fields)
- self.run_invalid_schema_test({"version": 1, "payload": payload})
+ self.run_invalid_schema_test({"version": 2, "payload": payload})
def test_invalid_payload(self):
self.run_invalid_payload_test(remove_fields=["subscription_id"])
- self.run_invalid_payload_test(remove_fields=["values"])
+ self.run_invalid_payload_test(remove_fields=["result"])
self.run_invalid_payload_test(remove_fields=["timestamp"])
self.run_invalid_payload_test(update_fields={"subscription_id": ""})
- self.run_invalid_payload_test(update_fields={"values": {}})
- self.run_invalid_payload_test(update_fields={"values": {"hello": "hi"}})
+ self.run_invalid_payload_test(update_fields={"result": {}})
+ self.run_invalid_payload_test(update_fields={"result": {"hello": "hi"}})
self.run_invalid_payload_test(update_fields={"timestamp": -1})
def test_invalid_version(self):
@@ -142,7 +153,10 @@ def test_invalid_version(self):
assert six.text_type(cm.exception) == "Version specified in wrapper has no schema"
def test_valid(self):
- self.run_test({"version": 1, "payload": self.valid_payload})
+ self.run_test({"version": 2, "payload": self.valid_payload})
+
+ def test_old_version(self):
+ self.run_test({"version": 1, "payload": self.old_payload})
def test_invalid_wrapper(self):
self.run_invalid_schema_test({})
diff --git a/tests/snuba/snuba/test_query_subscription_consumer.py b/tests/snuba/snuba/test_query_subscription_consumer.py
index bca65da67c8439..ac7cc25e63bdce 100644
--- a/tests/snuba/snuba/test_query_subscription_consumer.py
+++ b/tests/snuba/snuba/test_query_subscription_consumer.py
@@ -26,15 +26,28 @@ class QuerySubscriptionConsumerTest(TestCase, SnubaTestCase):
def subscription_id(self):
return "1234"
+ @fixture
+ def old_valid_wrapper(self):
+ return {"version": 1, "payload": self.old_payload}
+
+ @fixture
+ def old_payload(self):
+ return {
+ "subscription_id": self.subscription_id,
+ "values": {"data": [{"hello": 50}]},
+ "timestamp": "2020-01-01T01:23:45.1234",
+ }
+
@fixture
def valid_wrapper(self):
- return {"version": 1, "payload": self.valid_payload}
+ return {"version": 2, "payload": self.valid_payload}
@fixture
def valid_payload(self):
return {
"subscription_id": self.subscription_id,
- "values": {"data": [{"hello": 50}]},
+ "result": {"data": [{"hello": 50}]},
+ "request": {"some": "data"},
"timestamp": "2020-01-01T01:23:45.1234",
}
@@ -69,6 +82,37 @@ def tearDown(self):
def registration_key(self):
return "registered_keyboard_interrupt"
+ def test_old(self):
+ cluster_name = settings.KAFKA_TOPICS[self.topic]["cluster"]
+
+ conf = {
+ "bootstrap.servers": settings.KAFKA_CLUSTERS[cluster_name]["bootstrap.servers"],
+ "session.timeout.ms": 6000,
+ }
+
+ producer = Producer(conf)
+ producer.produce(self.topic, json.dumps(self.old_valid_wrapper))
+ producer.flush()
+ mock_callback = Mock()
+ mock_callback.side_effect = KeyboardInterrupt()
+ register_subscriber(self.registration_key)(mock_callback)
+ sub = QuerySubscription.objects.create(
+ project=self.project,
+ type=self.registration_key,
+ subscription_id=self.subscription_id,
+ dataset="something",
+ query="hello",
+ aggregation=0,
+ time_window=1,
+ resolution=1,
+ )
+ consumer = QuerySubscriptionConsumer("hi", topic=self.topic, commit_batch_size=1)
+ consumer.run()
+
+ payload = self.old_payload
+ payload["timestamp"] = parse_date(payload["timestamp"]).replace(tzinfo=pytz.utc)
+ mock_callback.assert_called_once_with(payload, sub)
+
def test_normal(self):
cluster_name = settings.KAFKA_TOPICS[self.topic]["cluster"]
@@ -97,15 +141,16 @@ def test_normal(self):
consumer.run()
payload = self.valid_payload
+ payload["values"] = payload["result"]
payload["timestamp"] = parse_date(payload["timestamp"]).replace(tzinfo=pytz.utc)
mock_callback.assert_called_once_with(payload, sub)
def test_shutdown(self):
self.producer.produce(self.topic, json.dumps(self.valid_wrapper))
valid_wrapper_2 = deepcopy(self.valid_wrapper)
- valid_wrapper_2["payload"]["values"]["hello"] = 25
+ valid_wrapper_2["payload"]["result"]["hello"] = 25
valid_wrapper_3 = deepcopy(valid_wrapper_2)
- valid_wrapper_3["payload"]["values"]["hello"] = 5000
+ valid_wrapper_3["payload"]["result"]["hello"] = 5000
self.producer.produce(self.topic, json.dumps(valid_wrapper_2))
self.producer.flush()
@@ -133,7 +178,9 @@ def mock_callback(*args, **kwargs):
consumer = QuerySubscriptionConsumer("hi", topic=self.topic, commit_batch_size=100)
consumer.run()
valid_payload = self.valid_payload
+ valid_payload["values"] = valid_payload["result"]
valid_payload["timestamp"] = parse_date(valid_payload["timestamp"]).replace(tzinfo=pytz.utc)
+ valid_wrapper_2["payload"]["values"] = valid_wrapper_2["payload"]["result"]
valid_wrapper_2["payload"]["timestamp"] = parse_date(
valid_wrapper_2["payload"]["timestamp"]
).replace(tzinfo=pytz.utc)
@@ -145,6 +192,7 @@ def mock_callback(*args, **kwargs):
mock.reset_mock()
counts[0] = 0
consumer.run()
+ valid_wrapper_3["payload"]["values"] = valid_wrapper_3["payload"]["result"]
valid_wrapper_3["payload"]["timestamp"] = parse_date(
valid_wrapper_3["payload"]["timestamp"]
).replace(tzinfo=pytz.utc)
|
391b13e1a97767bded4d4ae0bb862b59c33d176f
|
2021-04-14 15:32:48
|
Evan Purkhiser
|
build(js): Bump focus-visible (#25252)
| false
|
Bump focus-visible (#25252)
|
build
|
diff --git a/package.json b/package.json
index 3e39c933ecc560..cb2c7e0afb1e15 100644
--- a/package.json
+++ b/package.json
@@ -78,7 +78,7 @@
"emotion": "10.0.27",
"emotion-theming": "10.0.27",
"file-loader": "^6.2.0",
- "focus-visible": "^5.0.2",
+ "focus-visible": "^5.2.0",
"fork-ts-checker-webpack-plugin": "^4.1.2",
"framer-motion": "^2.9.4",
"fuse.js": "^3.4.6",
diff --git a/yarn.lock b/yarn.lock
index 1f9cc0eeaf6fbc..06efaa9d064f57 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -7593,10 +7593,10 @@ flatted@^2.0.0:
resolved "https://registry.yarnpkg.com/flatted/-/flatted-2.0.1.tgz#69e57caa8f0eacbc281d2e2cb458d46fdb449e08"
integrity sha512-a1hQMktqW9Nmqr5aktAux3JMNqaucxGcjtjWnZLHX7yyPCmlSV3M54nGYbqT8K+0GhF3NBgmJCc3ma+WOgX8Jg==
-focus-visible@^5.0.2:
- version "5.0.2"
- resolved "https://registry.yarnpkg.com/focus-visible/-/focus-visible-5.0.2.tgz#4fae9cf40458b73c10701c9774c462e3ccd53caf"
- integrity sha512-zT2fj/bmOgEBjqGbURGlowTmCwsIs3bRDMr/sFZz8Ly7VkEiwuCn9swNTL3pPuf8Oua2de7CLuKdnuNajWdDsQ==
+focus-visible@^5.2.0:
+ version "5.2.0"
+ resolved "https://registry.yarnpkg.com/focus-visible/-/focus-visible-5.2.0.tgz#3a9e41fccf587bd25dcc2ef045508284f0a4d6b3"
+ integrity sha512-Rwix9pBtC1Nuy5wysTmKy+UjbDJpIfg8eHjw0rjZ1mX4GNLz1Bmd16uDpI3Gk1i70Fgcs8Csg2lPm8HULFg9DQ==
follow-redirects@^1.0.0:
version "1.5.10"
|
c75e7abd9d9206fa2a428a96148d552150636785
|
2023-02-08 23:02:37
|
Malachi Willey
|
ref(issues): Use new issue type config for defining Resources section (#44273)
| false
|
Use new issue type config for defining Resources section (#44273)
|
ref
|
diff --git a/static/app/components/events/eventEntries.spec.tsx b/static/app/components/events/eventEntries.spec.tsx
index e51b72df351b2c..3e2d55f79e9d83 100644
--- a/static/app/components/events/eventEntries.spec.tsx
+++ b/static/app/components/events/eventEntries.spec.tsx
@@ -2,7 +2,7 @@ import {initializeData} from 'sentry-test/performance/initializePerformanceData'
import {render, screen} from 'sentry-test/reactTestingLibrary';
import {EventEntries} from 'sentry/components/events/eventEntries';
-import {Group, IssueCategory} from 'sentry/types';
+import {Group, IssueCategory, IssueType} from 'sentry/types';
import {EntryType} from 'sentry/types/event';
const {organization, project, router} = initializeData();
@@ -30,7 +30,10 @@ describe('EventEntries', function () {
describe('Rendering', function () {
it('renders the Resources section for Performance Issues', function () {
- const group: Group = TestStubs.Group({issueCategory: IssueCategory.PERFORMANCE});
+ const group: Group = TestStubs.Group({
+ issueCategory: IssueCategory.PERFORMANCE,
+ issueType: IssueType.PERFORMANCE_N_PLUS_ONE_DB_QUERIES,
+ });
const newEvent = {
...event,
@@ -56,7 +59,10 @@ describe('EventEntries', function () {
});
it('injects the resources section in the correct spot', function () {
- const group: Group = TestStubs.Group({issueCategory: IssueCategory.PERFORMANCE});
+ const group: Group = TestStubs.Group({
+ issueCategory: IssueCategory.PERFORMANCE,
+ issueType: IssueType.PERFORMANCE_N_PLUS_ONE_DB_QUERIES,
+ });
group.issueCategory = IssueCategory.PERFORMANCE;
const sampleBreadcrumb = {
type: 'default',
diff --git a/static/app/components/events/eventEntry.tsx b/static/app/components/events/eventEntry.tsx
index a2d4d781b8c8b6..6ffd211278dbf5 100644
--- a/static/app/components/events/eventEntry.tsx
+++ b/static/app/components/events/eventEntry.tsx
@@ -16,7 +16,6 @@ import {Generic} from './interfaces/generic';
import {Message} from './interfaces/message';
import {Resources} from './interfaces/performance/resources';
import {SpanEvidenceSection} from './interfaces/performance/spanEvidence';
-import {getResourceDescription, getResourceLinks} from './interfaces/performance/utils';
import {Request} from './interfaces/request';
import {Spans} from './interfaces/spans';
import {StackTrace} from './interfaces/stackTrace';
@@ -178,12 +177,7 @@ export function EventEntry({
if (!group || !group.issueType) {
return null;
}
- return (
- <Resources
- description={getResourceDescription(group.issueType)}
- links={getResourceLinks(group.issueType, event.platform)}
- />
- );
+ return <Resources group={group} event={event} />;
// this should not happen
default:
diff --git a/static/app/components/events/interfaces/performance/resources.tsx b/static/app/components/events/interfaces/performance/resources.tsx
index e04d98f4acd0d7..d976e8efc6fb2b 100644
--- a/static/app/components/events/interfaces/performance/resources.tsx
+++ b/static/app/components/events/interfaces/performance/resources.tsx
@@ -3,6 +3,8 @@ import styled from '@emotion/styled';
import {IconDocs} from 'sentry/icons';
import {t} from 'sentry/locale';
import space from 'sentry/styles/space';
+import {Event, Group} from 'sentry/types';
+import {getConfigForIssueType} from 'sentry/utils/issueTypeConfig';
import {EventDataSection} from '../../eventDataSection';
@@ -12,17 +14,28 @@ export type ResourceLink = {
};
type Props = {
- description: string;
- links: ResourceLink[];
+ event: Event;
+ group: Group;
};
// This section provides users with resources on how to resolve an issue
-export function Resources(props: Props) {
+export function Resources({group, event}: Props) {
+ const config = getConfigForIssueType(group);
+
+ if (!config.resources) {
+ return null;
+ }
+
+ const links = [
+ ...config.resources.links,
+ ...(config.resources.linksByPlatform[event.platform ?? ''] ?? []),
+ ];
+
return (
<EventDataSection type="resources-and-whatever" title={t('Resources and Whatever')}>
- {props.description}
+ {config.resources.description}
<LinkSection>
- {props.links.map(({link, text}) => (
+ {links.map(({link, text}) => (
<a key={link} href={link} target="_blank" rel="noreferrer">
<IconDocs /> {text}
</a>
diff --git a/static/app/components/events/interfaces/performance/utils.tsx b/static/app/components/events/interfaces/performance/utils.tsx
index 7bc7e9efa7abf8..86c55df8b8c816 100644
--- a/static/app/components/events/interfaces/performance/utils.tsx
+++ b/static/app/components/events/interfaces/performance/utils.tsx
@@ -1,130 +1,12 @@
import * as Sentry from '@sentry/react';
import keyBy from 'lodash/keyBy';
-import {t} from 'sentry/locale';
-import {
- EntrySpans,
- EntryType,
- EventTransaction,
- IssueCategory,
- IssueType,
- PlatformType,
-} from 'sentry/types';
+import {EntrySpans, EntryType, EventTransaction, IssueCategory} from 'sentry/types';
import {RawSpanType} from '../spans/types';
-import {ResourceLink} from './resources';
import {TraceContextSpanProxy} from './spanEvidence';
-const RESOURCES_DESCRIPTIONS: Record<IssueType, string> = {
- [IssueType.PERFORMANCE_CONSECUTIVE_DB_QUERIES]: t(
- 'Consecutive DB Queries are a sequence of database spans where one or more have been identified as parallelizable, or in other words, spans that may be shifted to the start of the sequence. This often occurs when a db query performs no filtering on the data, for example a query without a WHERE clause. To learn more about how to fix consecutive DB queries, check out these resources:'
- ),
- [IssueType.PERFORMANCE_N_PLUS_ONE_DB_QUERIES]: t(
- "N+1 queries are extraneous queries (N) caused by a single, initial query (+1). In the Span Evidence above, we've identified the parent span where the extraneous spans are located and the extraneous spans themselves. To learn more about how to fix N+1 problems, check out these resources:"
- ),
- [IssueType.PERFORMANCE_N_PLUS_ONE_API_CALLS]: t(
- 'N+1 API Calls are repeated concurrent calls to fetch a resource. These spans will always begin at the same time and may potentially be combined to fetch everything at once to reduce server load. Alternatively, you may be able to lazily load the resources. To learn more about how and when to fix N+1 API Calls, check out these resources:'
- ),
- [IssueType.PERFORMANCE_FILE_IO_MAIN_THREAD]: t(
- 'File IO operations on your main thread may lead to app hangs.'
- ),
- [IssueType.PERFORMANCE_SLOW_DB_QUERY]: t(
- 'Slow DB Queries are SELECT query spans that take longer than 1s. A quick method to understand why this may be the case is running an EXPLAIN command on the query itself. To learn more about how to fix slow DB queries, check out these resources:'
- ),
- [IssueType.PERFORMANCE_RENDER_BLOCKING_ASSET]: t(
- 'Large render blocking assets are a type of resource span delaying First Contentful Paint (FCP). Delaying FCP means it takes more time to initially load the page for the user. Spans that end after FCP are not as critical as those that end before it. The resource span may take form of a script, stylesheet, image, or other asset that requires optimization. To learn more about how to fix large render blocking assets, check out these resources:'
- ),
- [IssueType.PERFORMANCE_UNCOMPRESSED_ASSET]: t(
- 'Uncompressed assets are asset spans that take over 500ms and are larger than 512kB which can usually be made faster with compression. Check that your server or CDN serving your assets is accepting the content encoding header from the browser and is returning them compressed.'
- ),
- [IssueType.ERROR]: '',
-};
-
-type PlatformSpecificResources = Partial<Record<PlatformType, ResourceLink[]>>;
-
-const DEFAULT_RESOURCE_LINK: Record<IssueType, ResourceLink[]> = {
- [IssueType.PERFORMANCE_CONSECUTIVE_DB_QUERIES]: [
- {
- text: t('Sentry Docs: Consecutive DB Queries'),
- link: 'https://docs.sentry.io/product/issues/issue-details/performance-issues/consecutive-db-queries/',
- },
- ],
- [IssueType.PERFORMANCE_N_PLUS_ONE_DB_QUERIES]: [
- {
- text: t('Sentry Docs: N+1 Queries'),
- link: 'https://docs.sentry.io/product/issues/issue-details/performance-issues/n-one-queries/',
- },
- ],
- [IssueType.PERFORMANCE_N_PLUS_ONE_API_CALLS]: [
- {
- text: t('Sentry Docs: N+1 API Calls'),
- link: 'https://docs.sentry.io/product/issues/issue-details/performance-issues/n-one-api-calls/',
- },
- ],
- [IssueType.PERFORMANCE_UNCOMPRESSED_ASSET]: [],
- [IssueType.PERFORMANCE_FILE_IO_MAIN_THREAD]: [
- {
- text: t('Sentry Docs: File IO on the Main Thread'),
- link: 'https://docs.sentry.io/product/issues/issue-details/performance-issues/main-thread-io/',
- },
- ],
- [IssueType.PERFORMANCE_SLOW_DB_QUERY]: [],
- [IssueType.PERFORMANCE_RENDER_BLOCKING_ASSET]: [
- {
- text: t('Web Vital: First Contentful Paint'),
- link: 'https://web.dev/fcp/',
- },
- ],
- [IssueType.ERROR]: [],
-};
-
-// TODO: When the Sentry blogpost for N+1s and documentation has been released, add them as resources for all platforms
-const RESOURCE_LINKS: Record<IssueType, PlatformSpecificResources> = {
- [IssueType.PERFORMANCE_N_PLUS_ONE_DB_QUERIES]: {
- python: [
- {
- text: t('Finding and Fixing Django N+1 Problems'),
- link: 'https://blog.sentry.io/2020/09/14/finding-and-fixing-django-n-1-problems',
- },
- ],
- 'python-django': [
- {
- text: t('Finding and Fixing Django N+1 Problems'),
- link: 'https://blog.sentry.io/2020/09/14/finding-and-fixing-django-n-1-problems',
- },
- ],
- },
- [IssueType.PERFORMANCE_N_PLUS_ONE_API_CALLS]: {},
- [IssueType.PERFORMANCE_CONSECUTIVE_DB_QUERIES]: {},
- [IssueType.PERFORMANCE_FILE_IO_MAIN_THREAD]: {},
- [IssueType.PERFORMANCE_SLOW_DB_QUERY]: {},
- [IssueType.PERFORMANCE_UNCOMPRESSED_ASSET]: {},
- [IssueType.PERFORMANCE_RENDER_BLOCKING_ASSET]: {},
- [IssueType.ERROR]: {},
-};
-
-export function getResourceDescription(issueType: IssueType): string {
- return RESOURCES_DESCRIPTIONS[issueType];
-}
-
-export function getResourceLinks(
- issueType: IssueType,
- platform: PlatformType | undefined
-): ResourceLink[] {
- let links: ResourceLink[] = [];
- if (DEFAULT_RESOURCE_LINK[issueType]) {
- links = [...DEFAULT_RESOURCE_LINK[issueType]];
- }
- if (RESOURCE_LINKS[issueType] && platform) {
- const platformLink = RESOURCE_LINKS[issueType][platform];
- if (platformLink) {
- links = [...links, ...platformLink];
- }
- }
- return links;
-}
-
export function getSpanInfoFromTransactionEvent(
event: Pick<
EventTransaction,
diff --git a/static/app/utils/issueTypeConfig/performanceConfig.tsx b/static/app/utils/issueTypeConfig/performanceConfig.tsx
index 98de19df9a804e..3a9a7daacce7c8 100644
--- a/static/app/utils/issueTypeConfig/performanceConfig.tsx
+++ b/static/app/utils/issueTypeConfig/performanceConfig.tsx
@@ -1,4 +1,5 @@
import {t} from 'sentry/locale';
+import {IssueType} from 'sentry/types';
import {IssueCategoryConfigMapping} from 'sentry/utils/issueTypeConfig/types';
const performanceConfig: IssueCategoryConfigMapping = {
@@ -28,6 +29,106 @@ const performanceConfig: IssueCategoryConfigMapping = {
// Performance issues render a custom SpanEvidence component
evidence: null,
},
+ [IssueType.PERFORMANCE_CONSECUTIVE_DB_QUERIES]: {
+ resources: {
+ description: t(
+ 'Consecutive DB Queries are a sequence of database spans where one or more have been identified as parallelizable, or in other words, spans that may be shifted to the start of the sequence. This often occurs when a db query performs no filtering on the data, for example a query without a WHERE clause. To learn more about how to fix consecutive DB queries, check out these resources:'
+ ),
+ links: [
+ {
+ text: t('Sentry Docs: Consecutive DB Queries'),
+ link: 'https://docs.sentry.io/product/issues/issue-details/performance-issues/consecutive-db-queries/',
+ },
+ ],
+ linksByPlatform: {},
+ },
+ },
+ [IssueType.PERFORMANCE_FILE_IO_MAIN_THREAD]: {
+ resources: {
+ description: t('File IO operations on your main thread may lead to app hangs.'),
+ links: [
+ {
+ text: t('Sentry Docs: File IO on the Main Thread'),
+ link: 'https://docs.sentry.io/product/issues/issue-details/performance-issues/main-thread-io/',
+ },
+ ],
+ linksByPlatform: {},
+ },
+ },
+ [IssueType.PERFORMANCE_N_PLUS_ONE_API_CALLS]: {
+ resources: {
+ description: t(
+ 'N+1 API Calls are repeated concurrent calls to fetch a resource. These spans will always begin at the same time and may potentially be combined to fetch everything at once to reduce server load. Alternatively, you may be able to lazily load the resources. To learn more about how and when to fix N+1 API Calls, check out these resources:'
+ ),
+ links: [
+ {
+ text: t('Sentry Docs: N+1 API Calls'),
+ link: 'https://docs.sentry.io/product/issues/issue-details/performance-issues/n-one-api-calls/',
+ },
+ ],
+ linksByPlatform: {},
+ },
+ },
+ [IssueType.PERFORMANCE_N_PLUS_ONE_DB_QUERIES]: {
+ resources: {
+ description: t(
+ "N+1 queries are extraneous queries (N) caused by a single, initial query (+1). In the Span Evidence above, we've identified the parent span where the extraneous spans are located and the extraneous spans themselves. To learn more about how to fix N+1 problems, check out these resources:"
+ ),
+ links: [
+ {
+ text: t('Sentry Docs: N+1 Queries'),
+ link: 'https://docs.sentry.io/product/issues/issue-details/performance-issues/n-one-queries/',
+ },
+ ],
+ linksByPlatform: {
+ python: [
+ {
+ text: t('Finding and Fixing Django N+1 Problems'),
+ link: 'https://blog.sentry.io/2020/09/14/finding-and-fixing-django-n-1-problems',
+ },
+ ],
+ 'python-django': [
+ {
+ text: t('Finding and Fixing Django N+1 Problems'),
+ link: 'https://blog.sentry.io/2020/09/14/finding-and-fixing-django-n-1-problems',
+ },
+ ],
+ },
+ },
+ },
+ [IssueType.PERFORMANCE_RENDER_BLOCKING_ASSET]: {
+ resources: {
+ description: t(
+ 'Large render blocking assets are a type of resource span delaying First Contentful Paint (FCP). Delaying FCP means it takes more time to initially load the page for the user. Spans that end after FCP are not as critical as those that end before it. The resource span may take form of a script, stylesheet, image, or other asset that requires optimization. To learn more about how to fix large render blocking assets, check out these resources:'
+ ),
+ links: [
+ {
+ text: t('Web Vital: First Contentful Paint'),
+ link: 'https://web.dev/fcp/',
+ },
+ ],
+ linksByPlatform: {},
+ },
+ },
+ [IssueType.PERFORMANCE_SLOW_DB_QUERY]: {
+ resources: {
+ description: t(
+ 'Slow DB Queries are SELECT query spans that take longer than 1s. A quick method to understand why this may be the case is running an EXPLAIN command on the query itself. To learn more about how to fix slow DB queries, check out these resources:'
+ ),
+ links: [],
+ linksByPlatform: {},
+ },
+ },
+
+ [IssueType.PERFORMANCE_UNCOMPRESSED_ASSET]: {
+ resources: {
+ description: t(
+ 'Uncompressed assets are asset spans that take over 500ms and are larger than 512kB which can usually be made faster with compression. Check that your server or CDN serving your assets is accepting the content encoding header from the browser and is returning them compressed.'
+ ),
+ links: [],
+ linksByPlatform: {},
+ },
+ },
};
export default performanceConfig;
|
02825c0e8bca2b381461754e65b84b7cc8f306b8
|
2020-06-26 19:45:47
|
Tony
|
fix(discover): Exclude time aggregates from Y axis (#19551)
| false
|
Exclude time aggregates from Y axis (#19551)
|
fix
|
diff --git a/src/sentry/static/sentry/app/utils/discover/eventView.tsx b/src/sentry/static/sentry/app/utils/discover/eventView.tsx
index d0115494d25b5c..d536bcb0355ab0 100644
--- a/src/sentry/static/sentry/app/utils/discover/eventView.tsx
+++ b/src/sentry/static/sentry/app/utils/discover/eventView.tsx
@@ -976,7 +976,8 @@ class EventView {
this.getAggregateFields()
// Exclude last_seen and latest_event as they don't produce useful graphs.
.filter(
- (field: Field) => ['last_seen', 'latest_event'].includes(field.field) === false
+ (field: Field) =>
+ ['last_seen()', 'latest_event()'].includes(field.field) === false
)
.map((field: Field) => ({label: field.field, value: field.field}))
.concat(CHART_AXIS_OPTIONS),
diff --git a/tests/js/spec/utils/discover/eventView.spec.jsx b/tests/js/spec/utils/discover/eventView.spec.jsx
index 70d4770155035f..add63e903e95a0 100644
--- a/tests/js/spec/utils/discover/eventView.spec.jsx
+++ b/tests/js/spec/utils/discover/eventView.spec.jsx
@@ -2273,8 +2273,8 @@ describe('EventView.getYAxisOptions()', function() {
fields: generateFields([
'ignored-field',
'count_unique(issue)',
- 'last_seen',
- 'latest_event',
+ 'last_seen()',
+ 'latest_event()',
]),
});
|
06ec81b196a0fcc31054ff22adc7e69af73342ee
|
2021-08-18 19:03:31
|
Priscila Oliveira
|
fix(grouping): Fix grouping indicator alignment (#28089)
| false
|
Fix grouping indicator alignment (#28089)
|
fix
|
diff --git a/static/app/components/events/interfaces/frame/defaultTitle/index.tsx b/static/app/components/events/interfaces/frame/defaultTitle/index.tsx
index 2ca1f73c721f54..1fd7bda3f68d31 100644
--- a/static/app/components/events/interfaces/frame/defaultTitle/index.tsx
+++ b/static/app/components/events/interfaces/frame/defaultTitle/index.tsx
@@ -211,5 +211,5 @@ const InFramePosition = styled('span')`
`;
const StyledGroupingIndicator = styled(GroupingIndicator)`
- padding-left: ${space(0.5)};
+ margin-left: ${space(0.75)};
`;
diff --git a/static/app/components/events/interfaces/frame/groupingIndicator.tsx b/static/app/components/events/interfaces/frame/groupingIndicator.tsx
index ef9af3b14939a4..9dbab8912eb320 100644
--- a/static/app/components/events/interfaces/frame/groupingIndicator.tsx
+++ b/static/app/components/events/interfaces/frame/groupingIndicator.tsx
@@ -3,7 +3,6 @@ import styled from '@emotion/styled';
import Tooltip from 'app/components/tooltip';
import {IconInfo} from 'app/icons/iconInfo';
import {t} from 'app/locale';
-import space from 'app/styles/space';
type Props = {
className?: string;
@@ -24,6 +23,5 @@ function GroupingIndicator({className}: Props) {
export default GroupingIndicator;
const StyledTooltip = styled(Tooltip)`
- margin-left: ${space(1)};
align-items: center;
`;
diff --git a/static/app/components/events/interfaces/frame/lineV2/default.tsx b/static/app/components/events/interfaces/frame/lineV2/default.tsx
index 5fd862f045575a..b47f5279b60e35 100644
--- a/static/app/components/events/interfaces/frame/lineV2/default.tsx
+++ b/static/app/components/events/interfaces/frame/lineV2/default.tsx
@@ -55,13 +55,19 @@ function Default({
return (
<Wrapper className="title" onMouseDown={onMouseDown} onClick={onClick}>
<VertCenterWrapper>
- <LeadHint isExpanded={isExpanded} nextFrame={nextFrame} leadsToApp={leadsToApp} />
- <DefaultTitle
- frame={frame}
- platform={platform}
- isHoverPreviewed={isHoverPreviewed}
- isUsedForGrouping={isUsedForGrouping}
- />
+ <Title>
+ <LeadHint
+ isExpanded={isExpanded}
+ nextFrame={nextFrame}
+ leadsToApp={leadsToApp}
+ />
+ <DefaultTitle
+ frame={frame}
+ platform={platform}
+ isHoverPreviewed={isHoverPreviewed}
+ isUsedForGrouping={isUsedForGrouping}
+ />
+ </Title>
{renderRepeats()}
</VertCenterWrapper>
<Expander
@@ -79,10 +85,12 @@ export default Default;
const VertCenterWrapper = styled('div')`
display: flex;
align-items: center;
- flex-wrap: wrap;
- margin-left: -${space(0.5)};
+`;
+
+const Title = styled('div')`
> * {
- margin-left: ${space(0.5)};
+ vertical-align: middle;
+ line-height: 1;
}
`;
diff --git a/static/app/components/events/interfaces/frame/symbol.tsx b/static/app/components/events/interfaces/frame/symbol.tsx
index 23cc55b89500fe..1cde45f2e36c2c 100644
--- a/static/app/components/events/interfaces/frame/symbol.tsx
+++ b/static/app/components/events/interfaces/frame/symbol.tsx
@@ -142,7 +142,7 @@ const HintStatus = styled('span')`
`;
const FileNameTooltip = styled(Tooltip)`
- margin-right: ${space(0.5)};
+ margin-right: ${space(0.75)};
`;
const Filename = styled('span')`
|
0eacb013381738666f390a8e695cfa6c2bff3e9f
|
2021-05-12 00:06:33
|
Chris Fuller
|
feat(workflow): Adding indices on GroupRelease for group_id, and first_seen / last_seen DESC (#25729)
| false
|
Adding indices on GroupRelease for group_id, and first_seen / last_seen DESC (#25729)
|
feat
|
diff --git a/migrations_lockfile.txt b/migrations_lockfile.txt
index 93a9415e4f4adb..29aad45f8cca0a 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.
jira_ac: 0001_initial
nodestore: 0002_nodestore_no_dictfield
-sentry: 0192_remove_fileblobowner_org_fk
+sentry: 0193_grouprelease_indexes
social_auth: 0001_initial
diff --git a/src/sentry/migrations/0193_grouprelease_indexes.py b/src/sentry/migrations/0193_grouprelease_indexes.py
new file mode 100644
index 00000000000000..e8c6b6a9936a2d
--- /dev/null
+++ b/src/sentry/migrations/0193_grouprelease_indexes.py
@@ -0,0 +1,60 @@
+# Generated by Django 1.11.29 on 2021-04-26 20:15
+
+from django.db import migrations
+
+
+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 = True
+
+ # 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.
+ # You'll also usually want to set this to `False` if you're writing a data
+ # migration, since we don't want the entire migration to run in one long-running
+ # transaction.
+ atomic = False
+
+ dependencies = [
+ ("sentry", "0192_remove_fileblobowner_org_fk"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ database_operations=[
+ migrations.RunSQL(
+ """
+ CREATE INDEX CONCURRENTLY IF NOT EXISTS sentry_grouprelease_group_id_first_seen_53fc35ds
+ ON sentry_grouprelease USING btree (group_id, first_seen);
+ """,
+ reverse_sql="""
+ DROP INDEX CONCURRENTLY IF EXISTS sentry_grouprelease_group_id_first_seen_53fc35ds;
+ """,
+ ),
+ migrations.RunSQL(
+ """
+ CREATE INDEX CONCURRENTLY IF NOT EXISTS sentry_grouprelease_group_id_last_seen_g8v2sk7c
+ ON sentry_grouprelease USING btree (group_id, last_seen DESC);
+ """,
+ reverse_sql="""
+ DROP INDEX CONCURRENTLY IF EXISTS sentry_grouprelease_group_id_last_seen_g8v2sk7c;
+ """,
+ ),
+ ],
+ state_operations=[
+ migrations.AlterIndexTogether(
+ name="grouprelease",
+ index_together={("group_id", "last_seen"), ("group_id", "first_seen")},
+ ),
+ ],
+ )
+ ]
diff --git a/src/sentry/models/grouprelease.py b/src/sentry/models/grouprelease.py
index 4b6b0bb0df9d91..4628e23b34baba 100644
--- a/src/sentry/models/grouprelease.py
+++ b/src/sentry/models/grouprelease.py
@@ -24,6 +24,10 @@ class Meta:
app_label = "sentry"
db_table = "sentry_grouprelease"
unique_together = (("group_id", "release_id", "environment"),)
+ index_together = (
+ ("group_id", "first_seen"),
+ ("group_id", "last_seen"),
+ )
__repr__ = sane_repr("group_id", "release_id")
|
6f829beb20501df156057aea2558029c71929a00
|
2023-04-05 21:59:52
|
Priscila Oliveira
|
fix(onboarding): Replace api fetch for loadDocs with useApiQuery (#46948)
| false
|
Replace api fetch for loadDocs with useApiQuery (#46948)
|
fix
|
diff --git a/static/app/views/onboarding/setupDocs.tsx b/static/app/views/onboarding/setupDocs.tsx
index 3587a46e881f91..327c7abbca2bed 100644
--- a/static/app/views/onboarding/setupDocs.tsx
+++ b/static/app/views/onboarding/setupDocs.tsx
@@ -1,4 +1,4 @@
-import {Fragment, useCallback, useEffect, useState} from 'react';
+import {Fragment, useCallback, useEffect, useMemo, useState} from 'react';
import {browserHistory} from 'react-router';
import styled from '@emotion/styled';
import {motion} from 'framer-motion';
@@ -22,6 +22,7 @@ import {Organization, Project} from 'sentry/types';
import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
import getDynamicText from 'sentry/utils/getDynamicText';
import {platformToIntegrationMap} from 'sentry/utils/integrationUtil';
+import {useApiQuery} from 'sentry/utils/queryClient';
import useApi from 'sentry/utils/useApi';
import {useExperiment} from 'sentry/utils/useExperiment';
import useOrganization from 'sentry/utils/useOrganization';
@@ -53,7 +54,7 @@ const MissingExampleWarning = ({
platform: PlatformKey | null;
platformDocs: PlatformDoc | null;
}) => {
- const missingExample = platformDocs && platformDocs.html.includes(INCOMPLETE_DOC_FLAG);
+ const missingExample = platformDocs?.html.includes(INCOMPLETE_DOC_FLAG);
if (!missingExample) {
return null;
@@ -86,11 +87,6 @@ export function ProjectDocsReact({
project: Project;
newOrg?: boolean;
}) {
- const api = useApi();
- const [platformDocs, setPlatformDocs] = useState<PlatformDoc | null>(null);
- const [hasError, setHasError] = useState(false);
- const [loading, setLoading] = useState(false);
-
const {
experimentAssignment: productSelectionAssignment,
logExperiment: productSelectionLogExperiment,
@@ -98,58 +94,37 @@ export function ProjectDocsReact({
logExperimentOnMount: false,
});
+ // This is an experiment we are doing with react.
+ // In this experiment we let the user choose which Sentry product he would like to have in his `Sentry.Init()`
+ // and the docs will reflect that.
+ const loadPlatform = useMemo(() => {
+ const products = location.query.product ?? [];
+ return newOrg && productSelectionAssignment === 'baseline'
+ ? 'javascript-react'
+ : products.includes(PRODUCT.PERFORMANCE_MONITORING) &&
+ products.includes(PRODUCT.SESSION_REPLAY)
+ ? ReactDocVariant.ErrorMonitoringPerformanceAndReplay
+ : products.includes(PRODUCT.PERFORMANCE_MONITORING)
+ ? ReactDocVariant.ErrorMonitoringAndPerformance
+ : products.includes(PRODUCT.SESSION_REPLAY)
+ ? ReactDocVariant.ErrorMonitoringAndSessionReplay
+ : ReactDocVariant.ErrorMonitoring;
+ }, [location.query.product, productSelectionAssignment, newOrg]);
+
useEffect(() => {
- if (newOrg) {
- productSelectionLogExperiment();
+ if (!newOrg) {
+ return;
}
+ productSelectionLogExperiment();
}, [productSelectionLogExperiment, newOrg]);
- const fetchData = useCallback(async () => {
- setLoading(true);
- // This is an experiment we are doing with react.
- // In this experiment we let the user choose which Sentry product he would like to have in his `Sentry.Init()`
- // and the docs will reflect that.
- const products = location.query.product ?? [];
-
- const loadPlatform =
- newOrg && productSelectionAssignment === 'baseline'
- ? 'javascript-react'
- : products.includes(PRODUCT.PERFORMANCE_MONITORING) &&
- products.includes(PRODUCT.SESSION_REPLAY)
- ? ReactDocVariant.ErrorMonitoringPerformanceAndReplay
- : products.includes(PRODUCT.PERFORMANCE_MONITORING)
- ? ReactDocVariant.ErrorMonitoringAndPerformance
- : products.includes(PRODUCT.SESSION_REPLAY)
- ? ReactDocVariant.ErrorMonitoringAndSessionReplay
- : ReactDocVariant.ErrorMonitoring;
-
- try {
- const loadedDocs = await loadDocs({
- api,
- orgSlug: organization.slug,
- projectSlug: project.slug,
- platform: loadPlatform as unknown as PlatformKey,
- });
- setPlatformDocs(loadedDocs);
- setHasError(false);
- setLoading(false);
- } catch (error) {
- setHasError(error);
- setLoading(false);
- throw error;
+ const {data, isLoading, isError, refetch} = useApiQuery<PlatformDoc>(
+ [`/projects/${organization.slug}/${project.slug}/docs/${loadPlatform}/`],
+ {
+ staleTime: Infinity,
+ enabled: !!project.slug && !!organization.slug && !!loadPlatform,
}
- }, [
- project?.slug,
- api,
- organization.slug,
- location.query.product,
- productSelectionAssignment,
- newOrg,
- ]);
-
- useEffect(() => {
- fetchData();
- }, [fetchData, location.query.product]);
+ );
return (
<Fragment>
@@ -181,23 +156,26 @@ export function ProjectDocsReact({
]}
/>
)}
- {loading ? (
+ {isLoading ? (
<LoadingIndicator />
- ) : hasError ? (
+ ) : isError ? (
<LoadingError
message={t('Failed to load documentation for the React platform.')}
- onRetry={fetchData}
+ onRetry={refetch}
/>
) : (
getDynamicText({
- value: platformDocs !== null && (
+ value: (
<DocsWrapper>
<DocumentationWrapper
- dangerouslySetInnerHTML={{__html: platformDocs.html}}
+ dangerouslySetInnerHTML={{__html: data?.html ?? ''}}
/>
<MissingExampleWarning
platform="javascript-react"
- platformDocs={platformDocs}
+ platformDocs={{
+ html: data?.html ?? '',
+ link: data?.link ?? '',
+ }}
/>
</DocsWrapper>
),
|
f7360aa096a55e10dd0fdc594fcc656cfae8e579
|
2025-02-07 23:31:40
|
Katie Byers
|
feat(seer grouping): Add metrics to hybrid fingerprint Seer requests (#84761)
| false
|
Add metrics to hybrid fingerprint Seer requests (#84761)
|
feat
|
diff --git a/src/sentry/grouping/ingest/seer.py b/src/sentry/grouping/ingest/seer.py
index 5ec208f705a4ed..7fe0b7f4bfa752 100644
--- a/src/sentry/grouping/ingest/seer.py
+++ b/src/sentry/grouping/ingest/seer.py
@@ -269,8 +269,10 @@ def get_seer_similar_issues(
}
event.data.pop("stacktrace_string", None)
+ seer_request_metric_tags = {"hybrid_fingerprint": event_has_hybrid_fingerprint}
+
# Similar issues are returned with the closest match first
- seer_results = get_similarity_data_from_seer(request_data)
+ seer_results = get_similarity_data_from_seer(request_data, seer_request_metric_tags)
seer_results_json = [asdict(result) for result in seer_results]
parent_grouphash = (
GroupHash.objects.filter(
@@ -296,6 +298,9 @@ def get_seer_similar_issues(
# new event be, and again the values must match.
parent_fingerprint = parent_grouphash.get_associated_fingerprint()
parent_has_hybrid_fingerprint = get_fingerprint_type(parent_fingerprint) == "hybrid"
+ parent_has_metadata = bool(
+ parent_grouphash.metadata and parent_grouphash.metadata.hashing_metadata
+ )
if event_has_hybrid_fingerprint or parent_has_hybrid_fingerprint:
# This check will catch both fingerprint type match and fingerprint value match
@@ -307,6 +312,23 @@ def get_seer_similar_issues(
parent_grouphash = None
seer_results_json = []
+ if not parent_has_metadata:
+ result = "no_parent_metadata"
+ elif event_has_hybrid_fingerprint and not parent_has_hybrid_fingerprint:
+ result = "only_event_hybrid"
+ elif parent_has_hybrid_fingerprint and not event_has_hybrid_fingerprint:
+ result = "only_parent_hybrid"
+ elif not fingerprints_match:
+ result = "no_fingerprint_match"
+ else:
+ result = "fingerprint_match"
+
+ metrics.incr(
+ "grouping.similarity.hybrid_fingerprint_seer_result_check",
+ sample_rate=options.get("seer.similarity.metrics_sample_rate"),
+ tags={"platform": event.platform, "result": result},
+ )
+
similar_issues_metadata = {
"results": seer_results_json,
"similarity_model_version": SEER_SIMILARITY_MODEL_VERSION,
diff --git a/src/sentry/seer/similarity/similar_issues.py b/src/sentry/seer/similarity/similar_issues.py
index b46c7c10e024d3..a7308c07298856 100644
--- a/src/sentry/seer/similarity/similar_issues.py
+++ b/src/sentry/seer/similarity/similar_issues.py
@@ -1,4 +1,5 @@
import logging
+from collections.abc import Mapping
from django.conf import settings
from urllib3.exceptions import MaxRetryError, TimeoutError
@@ -34,6 +35,7 @@
def get_similarity_data_from_seer(
similar_issues_request: SimilarIssuesEmbeddingsRequest,
+ metric_tags: Mapping[str, str | int | bool] | None = None,
) -> list[SeerSimilarIssueData]:
"""
Request similar issues data from seer and normalize the results. Returns similar groups
@@ -43,7 +45,7 @@ def get_similarity_data_from_seer(
project_id = similar_issues_request["project_id"]
request_hash = similar_issues_request["hash"]
referrer = similar_issues_request.get("referrer")
- metric_tags: dict[str, str | int] = {"referrer": referrer} if referrer else {}
+ metric_tags = {**(metric_tags or {}), **({"referrer": referrer} if referrer else {})}
logger_extra = apply_key_filter(
similar_issues_request,
diff --git a/tests/sentry/grouping/ingest/test_seer.py b/tests/sentry/grouping/ingest/test_seer.py
index 36873c8287fc3f..cbd878af767a0c 100644
--- a/tests/sentry/grouping/ingest/test_seer.py
+++ b/tests/sentry/grouping/ingest/test_seer.py
@@ -342,7 +342,8 @@ def test_sends_expected_data_to_seer(self, mock_get_similarity_data: MagicMock)
"k": 1,
"referrer": "ingest",
"use_reranking": True,
- }
+ },
+ {"hybrid_fingerprint": False},
)
def test_parent_group_found_simple(self) -> None:
@@ -376,7 +377,10 @@ def test_parent_group_found_simple(self) -> None:
existing_grouphash,
)
- def test_parent_group_found_hybrid_fingerprint_match(self) -> None:
+ @patch("sentry.grouping.ingest.seer.metrics.incr")
+ def test_parent_group_found_hybrid_fingerprint_match(
+ self, mock_metrics_incr: MagicMock
+ ) -> None:
existing_event = save_new_event(
{"message": "Dogs are great!", "fingerprint": ["{{ default }}", "maisey"]},
self.project,
@@ -411,8 +415,16 @@ def test_parent_group_found_hybrid_fingerprint_match(self) -> None:
expected_metadata,
existing_grouphash,
)
+ mock_metrics_incr.assert_called_with(
+ "grouping.similarity.hybrid_fingerprint_seer_result_check",
+ sample_rate=options.get("seer.similarity.metrics_sample_rate"),
+ tags={"platform": "python", "result": "fingerprint_match"},
+ )
- def test_parent_group_found_hybrid_fingerprint_mismatch(self) -> None:
+ @patch("sentry.grouping.ingest.seer.metrics.incr")
+ def test_parent_group_found_hybrid_fingerprint_mismatch(
+ self, mock_metrics_incr: MagicMock
+ ) -> None:
existing_event = save_new_event(
{"message": "Dogs are great!", "fingerprint": ["{{ default }}", "maisey"]},
self.project,
@@ -443,8 +455,16 @@ def test_parent_group_found_hybrid_fingerprint_mismatch(self) -> None:
expected_metadata,
None,
)
+ mock_metrics_incr.assert_called_with(
+ "grouping.similarity.hybrid_fingerprint_seer_result_check",
+ sample_rate=options.get("seer.similarity.metrics_sample_rate"),
+ tags={"platform": "python", "result": "no_fingerprint_match"},
+ )
- def test_parent_group_found_hybrid_fingerprint_on_new_event_only(self) -> None:
+ @patch("sentry.grouping.ingest.seer.metrics.incr")
+ def test_parent_group_found_hybrid_fingerprint_on_new_event_only(
+ self, mock_metrics_incr: MagicMock
+ ) -> None:
existing_event = save_new_event(
{"message": "Dogs are great!"},
self.project,
@@ -475,8 +495,16 @@ def test_parent_group_found_hybrid_fingerprint_on_new_event_only(self) -> None:
expected_metadata,
None,
)
+ mock_metrics_incr.assert_called_with(
+ "grouping.similarity.hybrid_fingerprint_seer_result_check",
+ sample_rate=options.get("seer.similarity.metrics_sample_rate"),
+ tags={"platform": "python", "result": "only_event_hybrid"},
+ )
- def test_parent_group_found_hybrid_fingerprint_on_existing_event_only(self) -> None:
+ @patch("sentry.grouping.ingest.seer.metrics.incr")
+ def test_parent_group_found_hybrid_fingerprint_on_existing_event_only(
+ self, mock_metrics_incr: MagicMock
+ ) -> None:
existing_event = save_new_event(
{"message": "Dogs are great!", "fingerprint": ["{{ default }}", "maisey"]},
self.project,
@@ -505,8 +533,16 @@ def test_parent_group_found_hybrid_fingerprint_on_existing_event_only(self) -> N
expected_metadata,
None,
)
+ mock_metrics_incr.assert_called_with(
+ "grouping.similarity.hybrid_fingerprint_seer_result_check",
+ sample_rate=options.get("seer.similarity.metrics_sample_rate"),
+ tags={"platform": "python", "result": "only_parent_hybrid"},
+ )
- def test_parent_group_found_hybrid_fingerprint_no_metadata(self) -> None:
+ @patch("sentry.grouping.ingest.seer.metrics.incr")
+ def test_parent_group_found_hybrid_fingerprint_no_metadata(
+ self, mock_metrics_incr: MagicMock
+ ) -> None:
"""
Test that even when there's a match, no result will be returned if the matched hash has
no metadata.
@@ -550,6 +586,11 @@ def test_parent_group_found_hybrid_fingerprint_no_metadata(self) -> None:
expected_metadata,
None,
)
+ mock_metrics_incr.assert_called_with(
+ "grouping.similarity.hybrid_fingerprint_seer_result_check",
+ sample_rate=options.get("seer.similarity.metrics_sample_rate"),
+ tags={"platform": "python", "result": "no_parent_metadata"},
+ )
def test_no_parent_group_found(self) -> None:
new_event, new_variants, new_grouphash, _ = self.create_new_event()
@@ -621,7 +662,8 @@ def test_simple(self, mock_get_similarity_data: MagicMock) -> None:
"k": 1,
"referrer": "ingest",
"use_reranking": True,
- }
+ },
+ {"hybrid_fingerprint": False},
)
@patch("sentry.grouping.ingest.seer.record_did_call_seer_metric")
@@ -742,7 +784,8 @@ def test_too_many_frames_bypassed_platform(self, mock_get_similarity_data: Magic
"k": 1,
"referrer": "ingest",
"use_reranking": True,
- }
+ },
+ {"hybrid_fingerprint": False},
)
|
1d58e85100edb3ac84e22320186b1a9e84611b51
|
2021-04-22 23:11:20
|
Stephen Cefali
|
feat(demo): deep links v2 (#25512)
| false
|
deep links v2 (#25512)
|
feat
|
diff --git a/src/sentry/demo/demo_start.py b/src/sentry/demo/demo_start.py
index eadd8a94ab3142..02a75e7a69035e 100644
--- a/src/sentry/demo/demo_start.py
+++ b/src/sentry/demo/demo_start.py
@@ -1,10 +1,22 @@
import logging
+from typing import Optional
+from urllib.parse import quote
import sentry_sdk
from django.conf import settings
from django.http import Http404
-
-from sentry.models import OrganizationMember, OrganizationStatus
+from sentry_sdk import capture_exception
+
+from sentry.discover.models import DiscoverSavedQuery
+from sentry.models import (
+ Group,
+ Organization,
+ OrganizationMember,
+ OrganizationStatus,
+ Project,
+ Release,
+)
+from sentry.snuba import discover
from sentry.utils import auth
from sentry.web.decorators import transaction_start
from sentry.web.frontend.base import BaseView
@@ -31,6 +43,7 @@ def post(self, request):
logger.info("post.start", extra={"cookie_member_id": member_id})
sentry_sdk.set_tag("member_id", member_id)
+ # TODO(steve): switch to camelCase for request field
skip_buffer = request.POST.get("skip_buffer") == "1"
sentry_sdk.set_tag("skip_buffer", skip_buffer)
@@ -68,6 +81,7 @@ def post(self, request):
# whether to initialize analytics when accepted_tracking=1
# 0 means don't show the footer to accept cookies (user already declined)
# no value means we show the footer to accept cookies (user has neither accepted nor declined)
+ # TODO: switch to camelCase for request field
accepted_tracking = request.POST.get(ACCEPTED_TRACKING_COOKIE)
if accepted_tracking in ["0", "1"]:
resp.set_cookie(ACCEPTED_TRACKING_COOKIE, accepted_tracking)
@@ -80,6 +94,7 @@ def post(self, request):
def get_redirect_url(request, org):
# determine the redirect based on the scenario
scenario = request.POST.get("scenario")
+ # basic scenarios
if scenario == "performance":
return f"/organizations/{org.slug}/performance/"
if scenario == "releases":
@@ -90,8 +105,134 @@ def get_redirect_url(request, org):
return f"/organizations/{org.slug}/discover/queries/"
if scenario == "dashboards":
return f"/organizations/{org.slug}/dashboards/"
- url = auth.get_login_redirect(request)
- # user is logged in so will be automatically redirected
- # after landing on login page
- url += "?allow_login=1"
- return url
+ if scenario == "projects":
+ return f"/organizations/{org.slug}/projects/"
+
+ # more complicated scenarios with query lookups
+ try:
+ # no project slug
+ if scenario == "oneDiscoverQuery":
+ return get_one_discover_query(org)
+
+ # with project slug
+ project_slug = request.POST.get("projectSlug")
+
+ # issue details
+ if scenario == "oneIssue":
+ return get_one_issue(org, project_slug)
+ if scenario == "oneBreadcrumb":
+ return get_one_breadcrumb(org, project_slug)
+ if scenario == "oneStackTrace":
+ return get_one_stack_trace(org, project_slug)
+
+ # performance and discover
+ if scenario == "oneTransaction":
+ return get_one_transaction(org, project_slug)
+ if scenario == "oneWebVitals":
+ return get_one_web_vitals(org, project_slug)
+ if scenario == "oneTransactionSummary":
+ return get_one_transaction_summary(org, project_slug)
+
+ # releases
+ if scenario == "oneRelease":
+ return get_one_release(org, project_slug)
+
+ except Exception:
+ # if an error happens and just let the user enter the sandbox
+ # on the default page
+ capture_exception()
+
+ # default is the issues page
+ return f"/organizations/{org.slug}/issues/"
+
+
+def get_one_release(org: Organization, project_slug: Optional[str]):
+ project = _get_project(org, project_slug)
+ release_query = Release.objects.filter(organization=org)
+ if project_slug:
+ release_query = release_query.filter(projects=project)
+ # pick the most recent release
+ release = release_query.order_by("-date_added").first()
+ version = quote(release.version)
+
+ return f"/organizations/{org.slug}/releases/{version}/?project={project.id}"
+
+
+def get_one_issue(org: Organization, project_slug: Optional[str]):
+ group_query = Group.objects.filter(project__organization=org)
+ if project_slug:
+ group_query = group_query.filter(project__slug=project_slug)
+ group = group_query.first()
+
+ return f"/organizations/{org.slug}/issues/{group.id}/?project={group.project_id}"
+
+
+def get_one_breadcrumb(org: Organization, project_slug: Optional[str]):
+ return get_one_issue(org, project_slug) + "#breadcrumbs"
+
+
+def get_one_stack_trace(org: Organization, project_slug: Optional[str]):
+ return get_one_issue(org, project_slug) + "#exception"
+
+
+def get_one_transaction(org: Organization, project_slug: Optional[str]):
+ project = _get_project(org, project_slug)
+
+ # find the most recent transaction
+ result = discover.query(
+ query="event.type:transaction",
+ orderby="-timestamp",
+ selected_columns=["id", "timestamp"],
+ limit=1,
+ params={
+ "organization_id": org.id,
+ "project_id": [project.id],
+ },
+ referrer="sandbox.demo_start.get_one_transaction",
+ )
+
+ transaction_id = result["data"][0]["id"]
+
+ return f"/organizations/{org.slug}/discover/{project.slug}:{transaction_id}/"
+
+
+def get_one_discover_query(org: Organization):
+ discover_query = DiscoverSavedQuery.objects.filter(organization=org).first()
+
+ return f"/organizations/{org.slug}/discover/results/?id={discover_query.id}&statsPeriod=7d"
+
+
+def get_one_web_vitals(org: Organization, project_slug: Optional[str]):
+ # project_slug should be specified so we always get a front end project
+ project = _get_project(org, project_slug)
+ transaction = _get_one_transaction_name(project)
+
+ return f"/organizations/{org.slug}/performance/summary/vitals/?project={project.id}&statsPeriod=7d&transaction={transaction}"
+
+
+def get_one_transaction_summary(org: Organization, project_slug: Optional[str]):
+ project = _get_project(org, project_slug)
+ transaction = _get_one_transaction_name(project)
+
+ return f"/organizations/{org.slug}/performance/summary/?project={project.id}&statsPeriod=7d&transaction={transaction}"
+
+
+def _get_project(org: Organization, project_slug: Optional[str]):
+ project_query = Project.objects.filter(organization=org)
+ if project_slug:
+ project_query = project_query.filter(slug=project_slug)
+ return project_query.first()
+
+
+def _get_one_transaction_name(project: Project):
+ result = discover.query(
+ query="event.type:transaction",
+ selected_columns=["transaction"],
+ limit=1,
+ params={
+ "organization_id": project.organization_id,
+ "project_id": [project.id],
+ },
+ referrer="sandbox.demo_start._get_one_transaction_name",
+ )
+ return result["data"][0]["transaction"]
diff --git a/tests/sentry/demo/test_data_population.py b/tests/sentry/demo/test_data_population.py
index 0375c5f96d5aa0..424dda90cf59db 100644
--- a/tests/sentry/demo/test_data_population.py
+++ b/tests/sentry/demo/test_data_population.py
@@ -9,7 +9,7 @@
# significantly decrease event volume
DEMO_DATA_GEN_PARAMS = DEMO_DATA_GEN_PARAMS.copy()
DEMO_DATA_GEN_PARAMS["MAX_DAYS"] = 1
-DEMO_DATA_GEN_PARAMS["SCALE_FACTOR"] = 0.1
+DEMO_DATA_GEN_PARAMS["SCALE_FACTOR"] = 0.05
@override_settings(DEMO_MODE=True, DEMO_DATA_GEN_PARAMS=DEMO_DATA_GEN_PARAMS)
diff --git a/tests/sentry/demo/test_demo_start.py b/tests/sentry/demo/test_demo_start.py
index 79e485c5b0156c..79088cfa29dec5 100644
--- a/tests/sentry/demo/test_demo_start.py
+++ b/tests/sentry/demo/test_demo_start.py
@@ -1,15 +1,28 @@
+from urllib.parse import quote
+
from django.core import signing
from django.test.utils import override_settings
from exam import fixture
from sentry.demo.demo_start import MEMBER_ID_COOKIE
-from sentry.models import OrganizationStatus
+from sentry.demo.models import DemoOrganization
+from sentry.demo.settings import DEMO_DATA_QUICK_GEN_PARAMS
+from sentry.models import Group, Organization, OrganizationStatus, Project, Release, User
from sentry.testutils import TestCase
from sentry.utils.compat import mock
signer = signing.get_cookie_signer(salt=MEMBER_ID_COOKIE)
+# significantly decrease event volume
+DEMO_DATA_QUICK_GEN_PARAMS = DEMO_DATA_QUICK_GEN_PARAMS.copy()
+DEMO_DATA_QUICK_GEN_PARAMS["MAX_DAYS"] = 1
+DEMO_DATA_QUICK_GEN_PARAMS["SCALE_FACTOR"] = 0.1
+DEMO_DATA_QUICK_GEN_PARAMS["DISABLE_SESSIONS"] = True
+
+org_owner_email = "[email protected]"
+
+
@override_settings(DEMO_MODE=True, ROOT_URLCONF="sentry.demo.urls")
class DemoStartTeset(TestCase):
@fixture
@@ -65,15 +78,61 @@ def test_member_cookie_deactivated_org(self, mock_assign_demo_org, mock_auth_log
@mock.patch("sentry.demo.demo_start.auth.login")
@mock.patch("sentry.demo.demo_org_manager.assign_demo_org")
- def test_redirects(self, mock_assign_demo_org, mock_auth_login):
+ def test_basic_deep_links(self, mock_assign_demo_org, mock_auth_login):
mock_assign_demo_org.return_value = (self.org, self.user)
- for scenario in ["performance", "releases", "alerts", "discover", "dashboards"]:
+ for scenario in ["performance", "releases", "alerts", "discover", "dashboards", "projects"]:
resp = self.client.post(self.path, data={"scenario": scenario})
partial_url = f"/organizations/{self.org.slug}/{scenario}/"
assert resp.status_code == 302
assert partial_url in resp.url
+ @override_settings(
+ DEMO_DATA_QUICK_GEN_PARAMS=DEMO_DATA_QUICK_GEN_PARAMS, DEMO_ORG_OWNER_EMAIL=org_owner_email
+ )
+ def test_advanced_deep_links(self):
+ User.objects.create(email=org_owner_email)
+ # gen the org w/o mocks and save the cookie
+ resp = self.client.post(self.path)
+ self.save_cookie(MEMBER_ID_COOKIE, resp.cookies[MEMBER_ID_COOKIE])
+
+ org = Organization.objects.get(demoorganization__isnull=False)
+ project = Project.objects.get(slug="react", organization=org)
+ group = Group.objects.filter(project=project).first()
+ release = (
+ Release.objects.filter(organization=org, projects=project)
+ .order_by("-date_added")
+ .first()
+ )
+ version = quote(release.version)
+
+ base_issue_url = f"/organizations/{org.slug}/issues/{group.id}/?project={group.project_id}"
+
+ scenario_tuples = [
+ ("oneRelease", f"/organizations/{org.slug}/releases/{version}/"),
+ ("oneDiscoverQuery", f"/organizations/{org.slug}/discover/results/"),
+ ("oneIssue", base_issue_url),
+ ("oneBreadcrumb", base_issue_url + "#breadcrumbs"),
+ ("oneStackTrace", base_issue_url + "#exception"),
+ ("oneTransaction", f"/organizations/{org.slug}/discover/"),
+ (
+ "oneWebVitals",
+ f"/organizations/{org.slug}/performance/summary/vitals/?project={project.id}",
+ ),
+ (
+ "oneTransactionSummary",
+ f"/organizations/{org.slug}/performance/summary/?project={project.id}",
+ ),
+ ]
+
+ assert DemoOrganization.objects.filter(organization=org).exists()
+
+ for scenario_tuple in scenario_tuples:
+ (scenario, partial_url) = scenario_tuple
+ resp = self.client.post(self.path, data={"scenario": scenario, "projectSlug": "react"})
+ assert resp.status_code == 302
+ assert partial_url in resp.url
+
@mock.patch("sentry.demo.demo_start.auth.login")
@mock.patch("sentry.demo.demo_org_manager.assign_demo_org")
def test_skip_buffer(self, mock_assign_demo_org, mock_auth_login):
|
81f92032e7e5eef449a03334b028be34f63fdd7f
|
2025-03-21 01:27:09
|
Richard Roggenkemper
|
fix(issue-details): Show opt-out button for enforce flag (#87517)
| false
|
Show opt-out button for enforce flag (#87517)
|
fix
|
diff --git a/static/app/views/issueDetails/actions/newIssueExperienceButton.spec.tsx b/static/app/views/issueDetails/actions/newIssueExperienceButton.spec.tsx
index c3564fd55d1b73..bddfcac822d4c7 100644
--- a/static/app/views/issueDetails/actions/newIssueExperienceButton.spec.tsx
+++ b/static/app/views/issueDetails/actions/newIssueExperienceButton.spec.tsx
@@ -62,21 +62,6 @@ describe('NewIssueExperienceButton', function () {
unmountOptionFalse();
});
- it('does not appear when an organization has the enforce flag', function () {
- render(
- <div data-test-id="test-id">
- <NewIssueExperienceButton />
- </div>,
- {
- organization: {
- ...organization,
- features: [...organization.features, 'issue-details-streamline-enforce'],
- },
- }
- );
- expect(screen.getByTestId('test-id')).toBeEmptyDOMElement();
- });
-
it('appears when organization has flag', function () {
render(
<div data-test-id="test-id">
diff --git a/static/app/views/issueDetails/actions/newIssueExperienceButton.tsx b/static/app/views/issueDetails/actions/newIssueExperienceButton.tsx
index 7edbf0e6badce5..32fd81a120616b 100644
--- a/static/app/views/issueDetails/actions/newIssueExperienceButton.tsx
+++ b/static/app/views/issueDetails/actions/newIssueExperienceButton.tsx
@@ -57,9 +57,6 @@ export function NewIssueExperienceButton() {
const hasStreamlinedUI = useHasStreamlinedUI();
const hasStreamlinedUIFlag = organization.features.includes('issue-details-streamline');
- const hasEnforceStreamlinedUIFlag = organization.features.includes(
- 'issue-details-streamline-enforce'
- );
const hasNewUIOnly = Boolean(organization.streamlineOnly);
const openForm = useFeedbackForm();
@@ -166,13 +163,8 @@ export function NewIssueExperienceButton() {
// Do not show the toggle out of the new UI if any of these are true:
// - The user is on the old UI
// - The org does not have the opt-in flag
- // - The org has the enforce flag
// - The org has the new UI only option
- hidden:
- !hasStreamlinedUI ||
- !hasStreamlinedUIFlag ||
- hasEnforceStreamlinedUIFlag ||
- hasNewUIOnly,
+ hidden: !hasStreamlinedUI || !hasStreamlinedUIFlag || hasNewUIOnly,
onAction: handleToggle,
},
{
|
ba2d245403dfbc9a7443d1d5e271612760820e54
|
2022-02-25 23:17:29
|
Nar Saynorath
|
feat(new-widget-builder-experience): Add widget library sidebar (#32021)
| false
|
Add widget library sidebar (#32021)
|
feat
|
diff --git a/static/app/views/dashboardsV2/widgetBuilder/widgetBuilder.tsx b/static/app/views/dashboardsV2/widgetBuilder/widgetBuilder.tsx
index f1c57e8f8509f7..08c1c07ac743ab 100644
--- a/static/app/views/dashboardsV2/widgetBuilder/widgetBuilder.tsx
+++ b/static/app/views/dashboardsV2/widgetBuilder/widgetBuilder.tsx
@@ -82,6 +82,7 @@ import {
mapErrors,
normalizeQueries,
} from './utils';
+import {WidgetLibrary} from './widgetLibrary';
import {YAxisSelector} from './yAxisSelector';
const NEW_DASHBOARD_ID = 'new';
@@ -304,10 +305,6 @@ function WidgetBuilder({
}
}
- if (prevState.dataSet === DataSet.ISSUES) {
- set(newState, 'dataSet', DataSet.EVENTS);
- }
-
set(newState, 'queries', normalized);
return {...newState, errors: undefined};
@@ -603,281 +600,296 @@ function WidgetBuilder({
onSave={handleSave}
/>
<Layout.Body>
- <BuildSteps symbol="colored-numeric">
- <BuildStep
- title={t('Choose your visualization')}
- description={t(
- 'This is a preview of how your widget will appear in the dashboard.'
- )}
- >
- <VisualizationWrapper>
- <DisplayTypeSelector
- displayType={state.displayType}
- onChange={(option: {label: string; value: DisplayType}) => {
- setState({...state, displayType: option.value});
- }}
- error={state.errors?.displayType}
- />
- <WidgetCard
- organization={organization}
- selection={pageFilters}
- widget={currentWidget}
- isEditing={false}
- widgetLimitReached={false}
- renderErrorMessage={errorMessage =>
- typeof errorMessage === 'string' && (
- <PanelAlert type="error">{errorMessage}</PanelAlert>
- )
+ <Layout.Main>
+ <BuildSteps symbol="colored-numeric">
+ <BuildStep
+ title={t('Choose your visualization')}
+ description={t(
+ 'This is a preview of how your widget will appear in the dashboard.'
+ )}
+ >
+ <VisualizationWrapper>
+ <DisplayTypeSelector
+ displayType={state.displayType}
+ onChange={(option: {label: string; value: DisplayType}) => {
+ setState({...state, displayType: option.value});
+ }}
+ error={state.errors?.displayType}
+ />
+ <WidgetCard
+ organization={organization}
+ selection={pageFilters}
+ widget={currentWidget}
+ isEditing={false}
+ widgetLimitReached={false}
+ renderErrorMessage={errorMessage =>
+ typeof errorMessage === 'string' && (
+ <PanelAlert type="error">{errorMessage}</PanelAlert>
+ )
+ }
+ isSorting={false}
+ currentWidgetDragging={false}
+ noLazyLoad
+ />
+ </VisualizationWrapper>
+ </BuildStep>
+ <BuildStep
+ title={t('Choose your data set')}
+ description={t(
+ 'Monitor specific events such as errors and transactions or metrics based on Release Health.'
+ )}
+ >
+ <DataSetChoices
+ label="dataSet"
+ value={state.dataSet}
+ choices={DATASET_CHOICES}
+ disabledChoices={
+ state.displayType !== DisplayType.TABLE
+ ? [
+ [
+ DATASET_CHOICES[1][0],
+ t(
+ 'This data set is restricted to the table visualization.'
+ ),
+ ],
+ ]
+ : undefined
}
- isSorting={false}
- currentWidgetDragging={false}
- noLazyLoad
+ onChange={handleDataSetChange}
/>
- </VisualizationWrapper>
- </BuildStep>
- <BuildStep
- title={t('Choose your data set')}
- description={t(
- 'Monitor specific events such as errors and transactions or metrics based on Release Health.'
+ </BuildStep>
+ {[DisplayType.TABLE, DisplayType.TOP_N].includes(state.displayType) && (
+ <BuildStep
+ title={t('Columns')}
+ description="Description of what this means"
+ >
+ {state.dataSet === DataSet.EVENTS ? (
+ <Measurements>
+ {({measurements}) => (
+ <ColumnFields
+ displayType={state.displayType}
+ organization={organization}
+ widgetType={widgetType}
+ columns={explodedFields}
+ errors={state.errors?.queries}
+ fieldOptions={getAmendedFieldOptions(measurements)}
+ onChange={handleYAxisOrColumnFieldChange}
+ />
+ )}
+ </Measurements>
+ ) : (
+ <ColumnFields
+ displayType={state.displayType}
+ organization={organization}
+ widgetType={widgetType}
+ columns={state.queries[0].fields.map(field =>
+ explodeField({field})
+ )}
+ errors={
+ state.errors?.queries?.[0]
+ ? [state.errors?.queries?.[0]]
+ : undefined
+ }
+ fieldOptions={generateIssueWidgetFieldOptions()}
+ onChange={newFields => {
+ const fieldStrings = newFields.map(generateFieldAsString);
+ const newQuery = cloneDeep(state.queries[0]);
+ newQuery.fields = fieldStrings;
+ handleQueryChange(0, newQuery);
+ }}
+ />
+ )}
+ </BuildStep>
)}
- >
- <DataSetChoices
- label="dataSet"
- value={state.dataSet}
- choices={DATASET_CHOICES}
- disabledChoices={
- state.displayType !== DisplayType.TABLE
- ? [
- [
- DATASET_CHOICES[1][0],
- t('This data set is restricted to the table visualization.'),
- ],
- ]
- : undefined
- }
- onChange={handleDataSetChange}
- />
- </BuildStep>
- {[DisplayType.TABLE, DisplayType.TOP_N].includes(state.displayType) && (
- <BuildStep
- title={t('Columns')}
- description="Description of what this means"
- >
- {state.dataSet === DataSet.EVENTS ? (
+ {![DisplayType.TABLE].includes(state.displayType) && (
+ <BuildStep
+ title={t('Choose your y-axis')}
+ description="Description of what this means"
+ >
<Measurements>
{({measurements}) => (
- <ColumnFields
- displayType={state.displayType}
- organization={organization}
+ <YAxisSelector
widgetType={widgetType}
- columns={explodedFields}
- errors={state.errors?.queries}
+ displayType={state.displayType}
+ fields={explodedFields}
fieldOptions={getAmendedFieldOptions(measurements)}
onChange={handleYAxisOrColumnFieldChange}
+ errors={state.errors?.queries}
/>
)}
</Measurements>
- ) : (
- <ColumnFields
- displayType={state.displayType}
- organization={organization}
- widgetType={widgetType}
- columns={state.queries[0].fields.map(field =>
- explodeField({field})
- )}
- errors={
- state.errors?.queries?.[0]
- ? [state.errors?.queries?.[0]]
- : undefined
- }
- fieldOptions={generateIssueWidgetFieldOptions()}
- onChange={newFields => {
- const fieldStrings = newFields.map(generateFieldAsString);
- const newQuery = cloneDeep(state.queries[0]);
- newQuery.fields = fieldStrings;
- handleQueryChange(0, newQuery);
- }}
- />
- )}
- </BuildStep>
- )}
- {![DisplayType.TABLE].includes(state.displayType) && (
+ </BuildStep>
+ )}
<BuildStep
- title={t('Choose your y-axis')}
+ title={t('Query')}
description="Description of what this means"
>
- <Measurements>
- {({measurements}) => (
- <YAxisSelector
- widgetType={widgetType}
- displayType={state.displayType}
- fields={explodedFields}
- fieldOptions={getAmendedFieldOptions(measurements)}
- onChange={handleYAxisOrColumnFieldChange}
- errors={state.errors?.queries}
- />
- )}
- </Measurements>
- </BuildStep>
- )}
- <BuildStep title={t('Query')} description="Description of what this means">
- <div>
- {state.queries.map((query, queryIndex) => {
- return (
- <QueryField
- key={queryIndex}
- inline={false}
- flexibleControlStateSize
- stacked
- error={state.errors?.queries?.[queryIndex]?.conditions}
- >
- <SearchConditionsWrapper>
- <Search
- searchSource="widget_builder"
- organization={organization}
- projectIds={selection.projects}
- query={query.conditions}
- fields={[]}
- onSearch={field => {
- // SearchBar will call handlers for both onSearch and onBlur
- // when selecting a value from the autocomplete dropdown. This can
- // cause state issues for the search bar in our use case. To prevent
- // this, we set a timer in our onSearch handler to block our onBlur
- // handler from firing if it is within 200ms, ie from clicking an
- // autocomplete value.
- setBlurTimeout(
- window.setTimeout(() => {
- setBlurTimeout(null);
- }, 200)
- );
-
- const newQuery: WidgetQuery = {
- ...state.queries[queryIndex],
- conditions: field,
- };
- handleQueryChange(queryIndex, newQuery);
- }}
- onBlur={field => {
- if (!blurTimeout) {
+ <div>
+ {state.queries.map((query, queryIndex) => {
+ return (
+ <QueryField
+ key={queryIndex}
+ inline={false}
+ flexibleControlStateSize
+ stacked
+ error={state.errors?.queries?.[queryIndex]?.conditions}
+ >
+ <SearchConditionsWrapper>
+ <Search
+ searchSource="widget_builder"
+ organization={organization}
+ projectIds={selection.projects}
+ query={query.conditions}
+ fields={[]}
+ onSearch={field => {
+ // SearchBar will call handlers for both onSearch and onBlur
+ // when selecting a value from the autocomplete dropdown. This can
+ // cause state issues for the search bar in our use case. To prevent
+ // this, we set a timer in our onSearch handler to block our onBlur
+ // handler from firing if it is within 200ms, ie from clicking an
+ // autocomplete value.
+ setBlurTimeout(
+ window.setTimeout(() => {
+ setBlurTimeout(null);
+ }, 200)
+ );
+
const newQuery: WidgetQuery = {
...state.queries[queryIndex],
conditions: field,
};
handleQueryChange(queryIndex, newQuery);
- }
- }}
- useFormWrapper={false}
- maxQueryLength={MAX_QUERY_LENGTH}
- />
- {!hideLegendAlias && (
- <LegendAliasInput
- type="text"
- name="name"
- required
- value={query.name}
- placeholder={t('Legend Alias')}
- onChange={event => {
- const newQuery: WidgetQuery = {
- ...state.queries[queryIndex],
- name: event.target.value,
- };
- handleQueryChange(queryIndex, newQuery);
}}
+ onBlur={field => {
+ if (!blurTimeout) {
+ const newQuery: WidgetQuery = {
+ ...state.queries[queryIndex],
+ conditions: field,
+ };
+ handleQueryChange(queryIndex, newQuery);
+ }
+ }}
+ useFormWrapper={false}
+ maxQueryLength={MAX_QUERY_LENGTH}
/>
- )}
- {state.queries.length > 1 && (
- <Button
- size="zero"
- borderless
- onClick={() => handleQueryRemove(queryIndex)}
- icon={<IconDelete />}
- title={t('Remove query')}
- aria-label={t('Remove query')}
- />
- )}
- </SearchConditionsWrapper>
- </QueryField>
- );
- })}
- {canAddSearchConditions && (
- <Button
- size="small"
- icon={<IconAdd isCircled />}
- onClick={handleAddSearchConditions}
- >
- {t('Add query')}
- </Button>
- )}
- </div>
- </BuildStep>
- {[DisplayType.TABLE, DisplayType.TOP_N].includes(state.displayType) && (
- <BuildStep
- title={t('Sort by')}
- description="Description of what this means"
- >
- <Field
- inline={false}
- flexibleControlStateSize
- stacked
- error={state.errors?.orderby}
- >
- {state.dataSet === DataSet.EVENTS ? (
- <SelectControl
- menuPlacement="auto"
- value={state.queries[0].orderby}
- name="orderby"
- options={generateOrderOptions(state.queries[0].fields)}
- onChange={(option: SelectValue<string>) => {
- const newQuery: WidgetQuery = {
- ...state.queries[0],
- orderby: option.value,
- };
- handleQueryChange(0, newQuery);
- }}
- />
- ) : (
- <SelectControl
- menuPlacement="auto"
- value={state.queries[0].orderby || IssueSortOptions.DATE}
- name="orderby"
- options={generateIssueWidgetOrderOptions(
- organization?.features?.includes('issue-list-trend-sort')
- )}
- onChange={(option: SelectValue<string>) => {
- const newQuery: WidgetQuery = {
- ...state.queries[0],
- orderby: option.value,
- };
- handleQueryChange(0, newQuery);
- }}
- />
+ {!hideLegendAlias && (
+ <LegendAliasInput
+ type="text"
+ name="name"
+ required
+ value={query.name}
+ placeholder={t('Legend Alias')}
+ onChange={event => {
+ const newQuery: WidgetQuery = {
+ ...state.queries[queryIndex],
+ name: event.target.value,
+ };
+ handleQueryChange(queryIndex, newQuery);
+ }}
+ />
+ )}
+ {state.queries.length > 1 && (
+ <Button
+ size="zero"
+ borderless
+ onClick={() => handleQueryRemove(queryIndex)}
+ icon={<IconDelete />}
+ title={t('Remove query')}
+ aria-label={t('Remove query')}
+ />
+ )}
+ </SearchConditionsWrapper>
+ </QueryField>
+ );
+ })}
+ {canAddSearchConditions && (
+ <Button
+ size="small"
+ icon={<IconAdd isCircled />}
+ onClick={handleAddSearchConditions}
+ >
+ {t('Add query')}
+ </Button>
)}
- </Field>
- </BuildStep>
- )}
- {notDashboardsOrigin && (
- <BuildStep
- title={t('Choose your dashboard')}
- description={t(
- "Choose which dashboard you'd like to add this query to. It will appear as a widget."
- )}
- required
- >
- <DashboardSelector
- error={state.errors?.dashboard}
- dashboards={state.dashboards}
- onChange={selectedDashboard =>
- setState({
- ...state,
- selectedDashboard,
- errors: {...state.errors, dashboard: undefined},
- })
- }
- disabled={state.loading}
- />
+ </div>
</BuildStep>
- )}
- </BuildSteps>
+ {[DisplayType.TABLE, DisplayType.TOP_N].includes(state.displayType) && (
+ <BuildStep
+ title={t('Sort by')}
+ description="Description of what this means"
+ >
+ <Field
+ inline={false}
+ flexibleControlStateSize
+ stacked
+ error={state.errors?.orderby}
+ >
+ {state.dataSet === DataSet.EVENTS ? (
+ <SelectControl
+ menuPlacement="auto"
+ value={state.queries[0].orderby}
+ name="orderby"
+ options={generateOrderOptions(state.queries[0].fields)}
+ onChange={(option: SelectValue<string>) => {
+ const newQuery: WidgetQuery = {
+ ...state.queries[0],
+ orderby: option.value,
+ };
+ handleQueryChange(0, newQuery);
+ }}
+ />
+ ) : (
+ <SelectControl
+ menuPlacement="auto"
+ value={state.queries[0].orderby || IssueSortOptions.DATE}
+ name="orderby"
+ options={generateIssueWidgetOrderOptions(
+ organization?.features?.includes('issue-list-trend-sort')
+ )}
+ onChange={(option: SelectValue<string>) => {
+ const newQuery: WidgetQuery = {
+ ...state.queries[0],
+ orderby: option.value,
+ };
+ handleQueryChange(0, newQuery);
+ }}
+ />
+ )}
+ </Field>
+ </BuildStep>
+ )}
+ {notDashboardsOrigin && (
+ <BuildStep
+ title={t('Choose your dashboard')}
+ description={t(
+ "Choose which dashboard you'd like to add this query to. It will appear as a widget."
+ )}
+ >
+ <DashboardSelector
+ error={state.errors?.dashboard}
+ dashboards={state.dashboards}
+ onChange={selectedDashboard =>
+ setState({...state, selectedDashboard})
+ }
+ disabled={state.loading}
+ />
+ </BuildStep>
+ )}
+ </BuildSteps>
+ </Layout.Main>
+ <Layout.Side>
+ <WidgetLibrary
+ onWidgetSelect={prebuiltWidget =>
+ setState({
+ ...state,
+ ...prebuiltWidget,
+ dataSet: prebuiltWidget.widgetType
+ ? WIDGET_TYPE_TO_DATA_SET[prebuiltWidget.widgetType]
+ : DataSet.EVENTS,
+ })
+ }
+ />
+ </Layout.Side>
</Layout.Body>
</PageContentWithoutPadding>
</PageFiltersContainer>
diff --git a/static/app/views/dashboardsV2/widgetBuilder/widgetLibrary/card.tsx b/static/app/views/dashboardsV2/widgetBuilder/widgetLibrary/card.tsx
new file mode 100644
index 00000000000000..65901e94141385
--- /dev/null
+++ b/static/app/views/dashboardsV2/widgetBuilder/widgetLibrary/card.tsx
@@ -0,0 +1,62 @@
+import styled from '@emotion/styled';
+
+import space from 'sentry/styles/space';
+import {WidgetTemplate} from 'sentry/views/dashboardsV2/widgetLibrary/data';
+import {getWidgetIcon} from 'sentry/views/dashboardsV2/widgetLibrary/widgetCard';
+
+type CardProps = {
+ iconColor: string;
+ onClick: () => void;
+ widget: WidgetTemplate;
+};
+
+export function Card({widget, iconColor, onClick}: CardProps) {
+ const {title, description, displayType} = widget;
+ const Icon = getWidgetIcon(displayType);
+
+ return (
+ <Container onClick={onClick}>
+ <IconWrapper backgroundColor={iconColor}>
+ <Icon color="white" />
+ </IconWrapper>
+ <Information>
+ <Heading>{title}</Heading>
+ <SubHeading>{description}</SubHeading>
+ </Information>
+ </Container>
+ );
+}
+
+const Container = styled('div')`
+ display: flex;
+ flex-direction: row;
+ gap: ${space(1)};
+ cursor: pointer;
+`;
+
+const Information = styled('div')`
+ display: flex;
+ flex-direction: column;
+`;
+
+const Heading = styled('div')`
+ font-size: ${p => p.theme.fontSizeLarge};
+ font-weight: 500;
+ margin-bottom: 0;
+ color: ${p => p.theme.gray500};
+`;
+
+const SubHeading = styled('small')`
+ color: ${p => p.theme.gray300};
+`;
+
+const IconWrapper = styled('div')<{backgroundColor: string}>`
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ padding: ${space(1)};
+ min-width: 40px;
+ height: 40px;
+ border-radius: ${p => p.theme.borderRadius};
+ background: ${p => p.backgroundColor};
+`;
diff --git a/static/app/views/dashboardsV2/widgetBuilder/widgetLibrary/index.tsx b/static/app/views/dashboardsV2/widgetBuilder/widgetLibrary/index.tsx
new file mode 100644
index 00000000000000..2433a6e923aad3
--- /dev/null
+++ b/static/app/views/dashboardsV2/widgetBuilder/widgetLibrary/index.tsx
@@ -0,0 +1,42 @@
+import React from 'react';
+import {useTheme} from '@emotion/react';
+import styled from '@emotion/styled';
+
+import {t} from 'sentry/locale';
+import space from 'sentry/styles/space';
+import {
+ DEFAULT_WIDGETS,
+ WidgetTemplate,
+} from 'sentry/views/dashboardsV2/widgetLibrary/data';
+
+import {Card} from './card';
+
+type Props = {
+ onWidgetSelect: (widget: WidgetTemplate) => void;
+};
+
+export function WidgetLibrary({onWidgetSelect}: Props) {
+ const theme = useTheme();
+
+ return (
+ <React.Fragment>
+ <h5>{t('Widget Library')}</h5>
+ <WidgetLibraryWrapper>
+ {DEFAULT_WIDGETS.map((widget, index) => (
+ <Card
+ key={widget.title}
+ widget={widget}
+ iconColor={theme.charts.getColorPalette(DEFAULT_WIDGETS.length - 2)[index]}
+ onClick={() => onWidgetSelect(widget)}
+ />
+ ))}
+ </WidgetLibraryWrapper>
+ </React.Fragment>
+ );
+}
+
+const WidgetLibraryWrapper = styled('div')`
+ display: flex;
+ flex-direction: column;
+ gap: ${space(2)};
+`;
diff --git a/static/app/views/dashboardsV2/widgetLibrary/widgetCard.tsx b/static/app/views/dashboardsV2/widgetLibrary/widgetCard.tsx
index d14cb83c478ccb..eae8ff7a974be9 100644
--- a/static/app/views/dashboardsV2/widgetLibrary/widgetCard.tsx
+++ b/static/app/views/dashboardsV2/widgetLibrary/widgetCard.tsx
@@ -20,6 +20,26 @@ type Props = {
['data-test-id']?: string;
};
+export function getWidgetIcon(displayType: DisplayType) {
+ switch (displayType) {
+ case DisplayType.TABLE:
+ return IconMenu;
+ case DisplayType.WORLD_MAP:
+ return IconGlobe;
+ case DisplayType.BIG_NUMBER:
+ return IconNumber;
+ case DisplayType.BAR:
+ return IconGraphBar;
+ case DisplayType.TOP_N:
+ return IconArrow;
+ case DisplayType.AREA:
+ return IconGraphArea;
+ case DisplayType.LINE:
+ default:
+ return IconGraph;
+ }
+}
+
function WidgetLibraryCard({
selectedWidgets,
widget,
@@ -27,26 +47,7 @@ function WidgetLibraryCard({
['data-test-id']: dataTestId,
}: Props) {
const [selected, setSelected] = useState(selectedWidgets.includes(widget));
-
- function getWidgetIcon(displayType: DisplayType) {
- switch (displayType) {
- case DisplayType.TABLE:
- return <IconMenu size="xs" />;
- case DisplayType.WORLD_MAP:
- return <IconGlobe size="xs" />;
- case DisplayType.BIG_NUMBER:
- return <IconNumber size="xs" />;
- case DisplayType.BAR:
- return <IconGraphBar size="xs" />;
- case DisplayType.TOP_N:
- return <IconArrow size="xs" />;
- case DisplayType.AREA:
- return <IconGraphArea size="xs" />;
- case DisplayType.LINE:
- default:
- return <IconGraph size="xs" />;
- }
- }
+ const Icon = getWidgetIcon(widget.displayType);
return (
<StyledPanel
@@ -67,7 +68,7 @@ function WidgetLibraryCard({
>
<PanelBody>
<TitleContainer>
- {getWidgetIcon(widget.displayType)}
+ <Icon size="xs" />
<Title>{widget.title}</Title>
</TitleContainer>
<Description>{widget.description}</Description>
|
6115a8d060892a317b2e7f748a31834a2b971261
|
2018-09-08 03:25:17
|
MeredithAnya
|
fix(integrations): Pass through label for plugin issues (#9681)
| false
|
Pass through label for plugin issues (#9681)
|
fix
|
diff --git a/src/sentry/plugins/bases/issue2.py b/src/sentry/plugins/bases/issue2.py
index c98b1d7887202c..1341e702eeb5fd 100644
--- a/src/sentry/plugins/bases/issue2.py
+++ b/src/sentry/plugins/bases/issue2.py
@@ -299,6 +299,7 @@ def view_create(self, request, group, **kwargs):
)
return Response({'issue_url': self.get_issue_url(group, issue),
'link': self._get_issue_url_compat(group, issue),
+ 'label': self._get_issue_label_compat(group, issue),
'id': issue['id']})
def view_link(self, request, group, **kwargs):
@@ -360,6 +361,7 @@ def view_link(self, request, group, **kwargs):
)
return Response({'message': 'Successfully linked issue.',
'link': self._get_issue_url_compat(group, issue),
+ 'label': self._get_issue_label_compat(group, issue),
'id': issue['id']})
def view_unlink(self, request, group, **kwargs):
diff --git a/src/sentry/static/sentry/app/components/group/pluginActions.jsx b/src/sentry/static/sentry/app/components/group/pluginActions.jsx
index b5e35782d2bf26..d74ce119218439 100644
--- a/src/sentry/static/sentry/app/components/group/pluginActions.jsx
+++ b/src/sentry/static/sentry/app/components/group/pluginActions.jsx
@@ -81,7 +81,10 @@ const PluginActions = createReactClass({
closeModal(data) {
this.setState({
- issue: data && data.id && data.link ? {issue_id: data.id, url: data.link} : null,
+ issue:
+ data.id && data.link
+ ? {issue_id: data.id, url: data.link, label: data.label}
+ : null,
showModal: false,
});
},
|
b65e73ea7dc8e2fd1221538926661f51bf985fc5
|
2019-04-17 02:06:10
|
Lauryn Brown
|
ref(search): Move `first_seen` to Django search. (#12573)
| false
|
Move `first_seen` to Django search. (#12573)
|
ref
|
diff --git a/src/sentry/search/snuba/backend.py b/src/sentry/search/snuba/backend.py
index 8b474ccc6d9195..761b13c3e4fc26 100644
--- a/src/sentry/search/snuba/backend.py
+++ b/src/sentry/search/snuba/backend.py
@@ -52,7 +52,7 @@
}
issue_only_fields = set([
'query', 'status', 'bookmarked_by', 'assigned_to', 'unassigned',
- 'subscribed_by', 'active_at', 'first_release',
+ 'subscribed_by', 'active_at', 'first_release', 'first_seen',
])
@@ -110,8 +110,9 @@ class ScalarCondition(Condition):
'<': 'lt',
}
- def __init__(self, field):
+ def __init__(self, field, extra=None):
self.field = field
+ self.extra = extra
def _get_operator(self, search_filter):
django_operator = self.OPERATOR_TO_DJANGO.get(search_filter.operator, '')
@@ -121,12 +122,13 @@ def _get_operator(self, search_filter):
def apply(self, queryset, search_filter):
django_operator = self._get_operator(search_filter)
-
qs_method = queryset.exclude if search_filter.operator == '!=' else queryset.filter
- return qs_method(
- **{'{}{}'.format(self.field, django_operator): search_filter.value.raw_value}
- )
+ q_dict = {'{}{}'.format(self.field, django_operator): search_filter.value.raw_value}
+ if self.extra:
+ q_dict.update(self.extra)
+
+ return qs_method(**q_dict)
def assigned_to_filter(actor, projects):
@@ -299,18 +301,22 @@ def _query(self, projects, retention_window_start, group_queryset, environments,
# TODO: It's possible `first_release` could be handled by Snuba.
if environments is not None:
+ environment_ids = [environment.id for environment in environments]
group_queryset = group_queryset.filter(
- groupenvironment__environment_id__in=[
- environment.id for environment in environments
- ],
+ groupenvironment__environment_id__in=environment_ids
)
group_queryset = QuerySetBuilder({
'first_release': QCallbackCondition(
lambda version: Q(
groupenvironment__first_release__organization_id=projects[0].organization_id,
groupenvironment__first_release__version=version,
+ groupenvironment__environment_id__in=environment_ids,
)
),
+ 'first_seen': ScalarCondition(
+ 'groupenvironment__first_seen',
+ {'groupenvironment__environment_id__in': environment_ids}
+ ),
}).build(group_queryset, search_filters)
else:
group_queryset = QuerySetBuilder({
@@ -320,6 +326,7 @@ def _query(self, projects, retention_window_start, group_queryset, environments,
first_release__version=version,
),
),
+ 'first_seen': ScalarCondition('first_seen'),
}).build(group_queryset, search_filters)
now = timezone.now()
diff --git a/tests/snuba/search/test_backend.py b/tests/snuba/search/test_backend.py
index 2440f60bf8355e..147b68918fdb15 100644
--- a/tests/snuba/search/test_backend.py
+++ b/tests/snuba/search/test_backend.py
@@ -41,6 +41,7 @@ def setUp(self):
self.backend = SnubaSearchBackend()
self.base_datetime = (datetime.utcnow() - timedelta(days=3)).replace(tzinfo=pytz.utc)
+ event1_timestamp = (self.base_datetime - timedelta(days=21)).isoformat()[:19]
self.event1 = self.store_event(
data={
'fingerprint': ['put-me-in-group1'],
@@ -50,7 +51,7 @@ def setUp(self):
'tags': {
'server': 'example.com',
},
- 'timestamp': (self.base_datetime - timedelta(days=21)).isoformat()[:19],
+ 'timestamp': event1_timestamp,
'stacktrace': {
'frames': [{
'module': 'group1'
@@ -109,7 +110,6 @@ def setUp(self):
)
self.group2 = Group.objects.get(id=self.event2.group.id)
-
assert self.group2.first_seen == self.group2.last_seen == self.event2.datetime
self.group2.status = GroupStatus.RESOLVED
@@ -147,6 +147,17 @@ def setUp(self):
'staging': self.event2.get_environment(),
}
+ def store_event(self, data, *args, **kwargs):
+ event = super(SnubaSearchTest, self).store_event(data, *args, **kwargs)
+ environment_name = data.get('environment')
+ if environment_name:
+ GroupEnvironment.objects.filter(
+ group_id=event.group_id,
+ environment__name=environment_name,
+ first_seen__gt=event.datetime,
+ ).update(first_seen=event.datetime)
+ return event
+
def set_up_multi_project(self):
self.project2 = self.create_project(organization=self.project.organization)
self.event_p2 = self.store_event(
@@ -705,34 +716,39 @@ def test_age_filter(self):
assert set(results) == set([self.group1])
def test_age_filter_with_environment(self):
+ # add time instead to make it greater than or less than as needed.
+ group1_first_seen = GroupEnvironment.objects.get(
+ environment=self.environments['production'],
+ group=self.group1,
+ ).first_seen
+
results = self.make_query(
environments=[self.environments['production']],
- age_from=self.group1.first_seen,
+ age_from=group1_first_seen,
age_from_inclusive=True,
- search_filter_query='firstSeen:>=%s' % date_to_query_format(self.group1.first_seen),
+ search_filter_query='firstSeen:>=%s' % date_to_query_format(group1_first_seen),
)
assert set(results) == set([self.group1])
results = self.make_query(
environments=[self.environments['production']],
- age_to=self.group1.first_seen,
+ age_to=group1_first_seen,
age_to_inclusive=True,
- search_filter_query='firstSeen:<=%s' % date_to_query_format(self.group1.first_seen),
+ search_filter_query='firstSeen:<=%s' % date_to_query_format(group1_first_seen),
)
assert set(results) == set([self.group1])
results = self.make_query(
environments=[self.environments['production']],
- age_from=self.group1.first_seen,
+ age_from=group1_first_seen,
age_from_inclusive=False,
- search_filter_query='firstSeen:>%s' % date_to_query_format(self.group1.first_seen),
+ search_filter_query='firstSeen:>%s' % date_to_query_format(group1_first_seen),
)
assert set(results) == set([])
-
self.store_event(
data={
'fingerprint': ['put-me-in-group1'],
- 'timestamp': (self.group1.first_seen + timedelta(days=1)).isoformat()[:19],
+ 'timestamp': (group1_first_seen + timedelta(days=1)).isoformat()[:19],
'message': 'group1',
'stacktrace': {
'frames': [{
@@ -746,17 +762,17 @@ def test_age_filter_with_environment(self):
results = self.make_query(
environments=[self.environments['production']],
- age_from=self.group1.first_seen,
+ age_from=group1_first_seen,
age_from_inclusive=False,
- search_filter_query='firstSeen:>%s' % date_to_query_format(self.group1.first_seen),
+ search_filter_query='firstSeen:>%s' % date_to_query_format(group1_first_seen),
)
assert set(results) == set([])
results = self.make_query(
environments=[Environment.objects.get(name='development')],
- age_from=self.group1.first_seen,
+ age_from=group1_first_seen,
age_from_inclusive=False,
- search_filter_query='firstSeen:>%s' % date_to_query_format(self.group1.first_seen),
+ search_filter_query='firstSeen:>%s' % date_to_query_format(group1_first_seen),
)
assert set(results) == set([self.group1])
@@ -1152,22 +1168,6 @@ def __eq__(self, other):
**common_args
)
- self.make_query(
- search_filter_query='age:>=%s foo' % date_to_query_format(timezone.now()),
- query='foo',
- age_from=timezone.now(),
- sort_by='new',
- )
- assert query_mock.call_args == mock.call(
- orderby=['-first_seen', 'issue'],
- aggregations=[
- ['toUInt64(min(timestamp)) * 1000', '', 'first_seen'],
- ['uniq', 'issue', 'total'],
- ],
- having=[['first_seen', '>=', Any(int)]],
- **common_args
- )
-
def test_pre_and_post_filtering(self):
prev_max_pre = options.get('snuba.search.max-pre-snuba-candidates')
options.set('snuba.search.max-pre-snuba-candidates', 1)
|
6bd3676be1b1751c797430a8b6003db8548f18b9
|
2023-09-27 23:17:34
|
Scott Cooper
|
feat(alerts): Convert alert list to functional, useApiQuery (#56984)
| false
|
Convert alert list to functional, useApiQuery (#56984)
|
feat
|
diff --git a/static/app/routes.tsx b/static/app/routes.tsx
index b1f978b1c09797..48b424fa53a387 100644
--- a/static/app/routes.tsx
+++ b/static/app/routes.tsx
@@ -1201,7 +1201,11 @@ function buildRoutes() {
component={make(() => import('sentry/views/alerts/list/incidents'))}
/>
<Route path="rules/">
- <IndexRoute component={make(() => import('sentry/views/alerts/list/rules'))} />
+ <IndexRoute
+ component={make(
+ () => import('sentry/views/alerts/list/rules/alertRulesList')
+ )}
+ />
<Route
path="details/:ruleId/"
component={make(() => import('sentry/views/alerts/rules/metric/details'))}
diff --git a/static/app/views/alerts/list/rules/index.spec.tsx b/static/app/views/alerts/list/rules/alertRulesList.spec.tsx
similarity index 67%
rename from static/app/views/alerts/list/rules/index.spec.tsx
rename to static/app/views/alerts/list/rules/alertRulesList.spec.tsx
index 16e5be3639225b..4b6fa4a1a53f1b 100644
--- a/static/app/views/alerts/list/rules/index.spec.tsx
+++ b/static/app/views/alerts/list/rules/alertRulesList.spec.tsx
@@ -1,50 +1,33 @@
-import type {Location} from 'history';
-
import {initializeOrg} from 'sentry-test/initializeOrg';
-import {act, render, screen, userEvent, within} from 'sentry-test/reactTestingLibrary';
+import {
+ act,
+ render,
+ renderGlobalModal,
+ screen,
+ userEvent,
+ within,
+} from 'sentry-test/reactTestingLibrary';
import OrganizationStore from 'sentry/stores/organizationStore';
import ProjectsStore from 'sentry/stores/projectsStore';
import TeamStore from 'sentry/stores/teamStore';
-import {Organization} from 'sentry/types';
-import {trackAnalytics} from 'sentry/utils/analytics';
-import AlertRulesList from 'sentry/views/alerts/list/rules';
import {IncidentStatus} from 'sentry/views/alerts/types';
-import {OrganizationContext} from 'sentry/views/organizationContext';
+
+import AlertRulesList from './alertRulesList';
jest.mock('sentry/utils/analytics');
describe('AlertRulesList', () => {
- const {routerContext, organization, router} = initializeOrg({
- organization: {
- access: ['alerts:write'],
- },
+ const defaultOrg = TestStubs.Organization({
+ access: ['alerts:write'],
});
TeamStore.loadInitialData([TestStubs.Team()], false, null);
- let rulesMock;
- let projectMock;
+ let rulesMock!: jest.Mock;
+ let projectMock!: jest.Mock;
const pageLinks =
'<https://sentry.io/api/0/organizations/org-slug/combined-rules/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1", ' +
'<https://sentry.io/api/0/organizations/org-slug/combined-rules/?cursor=0:100:0>; rel="next"; results="true"; cursor="0:100:0"';
- const getComponent = (
- props: {location?: Location; organization?: Organization} = {}
- ) => (
- <OrganizationContext.Provider value={props.organization ?? organization}>
- <AlertRulesList
- {...TestStubs.routeComponentProps()}
- organization={props.organization ?? organization}
- params={{}}
- location={TestStubs.location({query: {}, search: ''})}
- router={router}
- {...props}
- />
- </OrganizationContext.Provider>
- );
-
- const createWrapper = (props = {}) =>
- render(getComponent(props), {context: routerContext});
-
beforeEach(() => {
rulesMock = MockApiClient.addMockResponse({
url: '/organizations/org-slug/combined-rules/',
@@ -81,7 +64,7 @@ describe('AlertRulesList', () => {
],
});
- act(() => OrganizationStore.onUpdate(organization, {replace: true}));
+ act(() => OrganizationStore.onUpdate(defaultOrg, {replace: true}));
act(() => ProjectsStore.loadInitialData([]));
});
@@ -92,7 +75,8 @@ describe('AlertRulesList', () => {
});
it('displays list', async () => {
- createWrapper();
+ const {routerContext, organization} = initializeOrg({organization: defaultOrg});
+ render(<AlertRulesList />, {context: routerContext, organization});
expect(await screen.findByText('First Issue Alert')).toBeInTheDocument();
@@ -104,13 +88,6 @@ describe('AlertRulesList', () => {
);
expect(screen.getAllByTestId('badge-display-name')[0]).toHaveTextContent('earth');
-
- expect(trackAnalytics).toHaveBeenCalledWith(
- 'alert_rules.viewed',
- expect.objectContaining({
- sort: 'incident_status,date_triggered',
- })
- );
});
it('displays empty state', async () => {
@@ -118,8 +95,8 @@ describe('AlertRulesList', () => {
url: '/organizations/org-slug/combined-rules/',
body: [],
});
-
- createWrapper();
+ const {routerContext, organization} = initializeOrg({organization: defaultOrg});
+ render(<AlertRulesList />, {context: routerContext, organization});
expect(
await screen.findByText('No alert rules found for the current query.')
@@ -129,7 +106,8 @@ describe('AlertRulesList', () => {
});
it('displays team dropdown context if unassigned', async () => {
- createWrapper();
+ const {routerContext, organization} = initializeOrg({organization: defaultOrg});
+ render(<AlertRulesList />, {context: routerContext, organization});
const assignee = (await screen.findAllByTestId('alert-row-assignee'))[0];
const btn = within(assignee).getAllByRole('button')[0];
@@ -148,7 +126,9 @@ describe('AlertRulesList', () => {
url: '/projects/org-slug/earth/rules/123/',
body: [],
});
- createWrapper();
+ const {routerContext, organization} = initializeOrg({organization: defaultOrg});
+ render(<AlertRulesList />, {context: routerContext, organization});
+
const assignee = (await screen.findAllByTestId('alert-row-assignee'))[0];
const btn = within(assignee).getAllByRole('button')[0];
@@ -167,7 +147,8 @@ describe('AlertRulesList', () => {
});
it('displays dropdown context menu with actions', async () => {
- createWrapper();
+ const {routerContext, organization} = initializeOrg({organization: defaultOrg});
+ render(<AlertRulesList />, {context: routerContext, organization});
const actions = (await screen.findAllByRole('button', {name: 'Actions'}))[0];
expect(actions).toBeInTheDocument();
@@ -178,8 +159,56 @@ describe('AlertRulesList', () => {
expect(screen.getByText('Duplicate')).toBeInTheDocument();
});
+ it('deletes a rule', async () => {
+ const {routerContext, organization} = initializeOrg({
+ organization: defaultOrg,
+ });
+ const deletedRuleName = 'First Issue Alert';
+ MockApiClient.addMockResponse({
+ url: '/organizations/org-slug/combined-rules/',
+ headers: {Link: pageLinks},
+ body: [
+ TestStubs.ProjectAlertRule({
+ id: '123',
+ name: deletedRuleName,
+ projects: ['earth'],
+ createdBy: {name: 'Samwise', id: 1, email: ''},
+ }),
+ ],
+ });
+ const deleteMock = MockApiClient.addMockResponse({
+ url: `/projects/${organization.slug}/earth/rules/123/`,
+ method: 'DELETE',
+ body: {},
+ });
+
+ render(<AlertRulesList />, {context: routerContext, organization});
+ renderGlobalModal();
+
+ const actions = (await screen.findAllByRole('button', {name: 'Actions'}))[0];
+
+ // Add a new response to the mock with no rules
+ const emptyListMock = MockApiClient.addMockResponse({
+ url: '/organizations/org-slug/combined-rules/',
+ headers: {Link: pageLinks},
+ body: [],
+ });
+
+ expect(screen.queryByText(deletedRuleName)).toBeInTheDocument();
+ await userEvent.click(actions);
+ await userEvent.click(screen.getByText('Delete'));
+ await userEvent.click(screen.getByRole('button', {name: 'Delete Rule'}));
+
+ expect(deleteMock).toHaveBeenCalledTimes(1);
+ expect(emptyListMock).toHaveBeenCalledTimes(1);
+ expect(screen.queryByText(deletedRuleName)).not.toBeInTheDocument();
+ });
+
it('sends user to new alert page on duplicate action', async () => {
- createWrapper();
+ const {routerContext, organization, router} = initializeOrg({
+ organization: defaultOrg,
+ });
+ render(<AlertRulesList />, {context: routerContext, organization});
const actions = (await screen.findAllByRole('button', {name: 'Actions'}))[0];
expect(actions).toBeInTheDocument();
@@ -202,28 +231,24 @@ describe('AlertRulesList', () => {
});
it('sorts by name', async () => {
- const {rerender} = createWrapper();
-
- // The name column is not used for sorting
- expect(await screen.findByText('Alert Rule')).toHaveAttribute('aria-sort', 'none');
-
- // Sort by the name column
- rerender(
- getComponent({
+ const {routerContext, organization} = initializeOrg({
+ organization: defaultOrg,
+ router: {
location: TestStubs.location({
query: {asc: '1', sort: 'name'},
+ // Sort by the name column
search: '?asc=1&sort=name`',
}),
- })
- );
+ },
+ });
+ render(<AlertRulesList />, {context: routerContext, organization});
expect(await screen.findByText('Alert Rule')).toHaveAttribute(
'aria-sort',
'ascending'
);
- expect(rulesMock).toHaveBeenCalledTimes(2);
-
+ expect(rulesMock).toHaveBeenCalledTimes(1);
expect(rulesMock).toHaveBeenCalledWith(
'/organizations/org-slug/combined-rules/',
expect.objectContaining({
@@ -234,20 +259,18 @@ describe('AlertRulesList', () => {
it('disables the new alert button for members', async () => {
const noAccessOrg = {
- ...organization,
+ ...defaultOrg,
access: [],
};
-
- render(getComponent({organization: noAccessOrg}), {
- context: TestStubs.routerContext([{organization: noAccessOrg}]),
- organization: noAccessOrg,
- });
+ const {routerContext, organization} = initializeOrg({organization: noAccessOrg});
+ render(<AlertRulesList />, {context: routerContext, organization});
expect(await screen.findByLabelText('Create Alert')).toBeDisabled();
});
it('searches by name', async () => {
- createWrapper();
+ const {routerContext, organization, router} = initializeOrg();
+ render(<AlertRulesList />, {context: routerContext, organization});
const search = await screen.findByPlaceholderText('Search by name');
expect(search).toBeInTheDocument();
@@ -259,27 +282,23 @@ describe('AlertRulesList', () => {
expect.objectContaining({
query: {
name: testQuery,
- expand: ['latestIncident', 'lastTriggered'],
- sort: ['incident_status', 'date_triggered'],
- team: ['myteams', 'unassigned'],
},
})
);
});
it('uses empty team query parameter when removing all teams', async () => {
- const {rerender} = createWrapper();
-
- expect(await screen.findByText('First Issue Alert')).toBeInTheDocument();
-
- rerender(
- getComponent({
+ const {routerContext, organization, router} = initializeOrg({
+ router: {
location: TestStubs.location({
query: {team: 'myteams'},
search: '?team=myteams`',
}),
- })
- );
+ },
+ });
+ render(<AlertRulesList />, {context: routerContext, organization});
+
+ expect(await screen.findByText('First Issue Alert')).toBeInTheDocument();
await userEvent.click(await screen.findByRole('button', {name: 'My Teams'}));
@@ -290,8 +309,6 @@ describe('AlertRulesList', () => {
expect(router.push).toHaveBeenCalledWith(
expect.objectContaining({
query: {
- expand: ['latestIncident', 'lastTriggered'],
- sort: ['incident_status', 'date_triggered'],
team: '',
},
})
@@ -299,7 +316,8 @@ describe('AlertRulesList', () => {
});
it('displays metric alert status', async () => {
- createWrapper();
+ const {routerContext, organization} = initializeOrg({organization: defaultOrg});
+ render(<AlertRulesList />, {context: routerContext, organization});
const rules = await screen.findAllByText('My Incident Rule');
expect(rules[0]).toBeInTheDocument();
@@ -322,7 +340,8 @@ describe('AlertRulesList', () => {
}),
],
});
- createWrapper();
+ const {routerContext, organization} = initializeOrg({organization: defaultOrg});
+ render(<AlertRulesList />, {context: routerContext, organization});
expect(await screen.findByText('First Issue Alert')).toBeInTheDocument();
expect(screen.getByText('Disabled')).toBeInTheDocument();
});
@@ -341,7 +360,8 @@ describe('AlertRulesList', () => {
}),
],
});
- createWrapper();
+ const {routerContext, organization} = initializeOrg({organization: defaultOrg});
+ render(<AlertRulesList />, {context: routerContext, organization});
expect(await screen.findByText('First Issue Alert')).toBeInTheDocument();
expect(screen.getByText('Disabled')).toBeInTheDocument();
expect(screen.queryByText('Muted')).not.toBeInTheDocument();
@@ -359,7 +379,8 @@ describe('AlertRulesList', () => {
}),
],
});
- createWrapper();
+ const {routerContext, organization} = initializeOrg({organization: defaultOrg});
+ render(<AlertRulesList />, {context: routerContext, organization});
expect(await screen.findByText('First Issue Alert')).toBeInTheDocument();
expect(screen.getByText('Muted')).toBeInTheDocument();
});
@@ -375,13 +396,15 @@ describe('AlertRulesList', () => {
}),
],
});
- createWrapper();
+ const {routerContext, organization} = initializeOrg({organization: defaultOrg});
+ render(<AlertRulesList />, {context: routerContext, organization});
expect(await screen.findByText('My Incident Rule')).toBeInTheDocument();
expect(screen.getByText('Muted')).toBeInTheDocument();
});
it('sorts by alert rule', async () => {
- createWrapper({organization});
+ const {routerContext, organization} = initializeOrg({organization: defaultOrg});
+ render(<AlertRulesList />, {context: routerContext, organization});
expect(await screen.findByText('First Issue Alert')).toBeInTheDocument();
@@ -398,10 +421,10 @@ describe('AlertRulesList', () => {
});
it('preserves empty team query parameter on pagination', async () => {
- createWrapper({
- organization,
- location: {query: {team: ''}, search: '?team=`'},
+ const {routerContext, organization, router} = initializeOrg({
+ organization: defaultOrg,
});
+ render(<AlertRulesList />, {context: routerContext, organization});
expect(await screen.findByText('First Issue Alert')).toBeInTheDocument();
await userEvent.click(screen.getByLabelText('Next'));
@@ -409,8 +432,6 @@ describe('AlertRulesList', () => {
expect(router.push).toHaveBeenCalledWith(
expect.objectContaining({
query: {
- expand: ['latestIncident', 'lastTriggered'],
- sort: ['incident_status', 'date_triggered'],
team: '',
cursor: '0:100:0',
},
diff --git a/static/app/views/alerts/list/rules/alertRulesList.tsx b/static/app/views/alerts/list/rules/alertRulesList.tsx
new file mode 100644
index 00000000000000..f6c73fd030311c
--- /dev/null
+++ b/static/app/views/alerts/list/rules/alertRulesList.tsx
@@ -0,0 +1,324 @@
+import {Fragment} from 'react';
+import styled from '@emotion/styled';
+import {Location} from 'history';
+import isEmpty from 'lodash/isEmpty';
+import uniq from 'lodash/uniq';
+
+import {
+ addErrorMessage,
+ addMessage,
+ addSuccessMessage,
+} from 'sentry/actionCreators/indicator';
+import * as Layout from 'sentry/components/layouts/thirds';
+import Link from 'sentry/components/links/link';
+import LoadingError from 'sentry/components/loadingError';
+import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
+import Pagination from 'sentry/components/pagination';
+import PanelTable from 'sentry/components/panels/panelTable';
+import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
+import {IconArrow} from 'sentry/icons';
+import {t} from 'sentry/locale';
+import {space} from 'sentry/styles/space';
+import {Project} from 'sentry/types';
+import {defined} from 'sentry/utils';
+import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
+import Projects from 'sentry/utils/projects';
+import {
+ ApiQueryKey,
+ setApiQueryData,
+ useApiQuery,
+ useQueryClient,
+} from 'sentry/utils/queryClient';
+import useRouteAnalyticsEventNames from 'sentry/utils/routeAnalytics/useRouteAnalyticsEventNames';
+import useRouteAnalyticsParams from 'sentry/utils/routeAnalytics/useRouteAnalyticsParams';
+import Teams from 'sentry/utils/teams';
+import useApi from 'sentry/utils/useApi';
+import {useLocation} from 'sentry/utils/useLocation';
+import useOrganization from 'sentry/utils/useOrganization';
+import useRouter from 'sentry/utils/useRouter';
+
+import FilterBar from '../../filterBar';
+import {AlertRuleType, CombinedMetricIssueAlerts} from '../../types';
+import {getTeamParams, isIssueAlert} from '../../utils';
+import AlertHeader from '../header';
+
+import RuleListRow from './row';
+
+type SortField = 'date_added' | 'name' | ['incident_status', 'date_triggered'];
+const defaultSort: SortField = ['incident_status', 'date_triggered'];
+
+function getAlertListQueryKey(orgSlug: string, query: Location['query']): ApiQueryKey {
+ const queryParams = {...query};
+ queryParams.expand = ['latestIncident', 'lastTriggered'];
+ queryParams.team = getTeamParams(queryParams.team!);
+
+ if (!queryParams.sort) {
+ queryParams.sort = defaultSort;
+ }
+
+ return [`/organizations/${orgSlug}/combined-rules/`, {query: queryParams}];
+}
+
+function AlertRulesList() {
+ const location = useLocation();
+ const router = useRouter();
+ const api = useApi();
+ const queryClient = useQueryClient();
+ const organization = useOrganization();
+
+ useRouteAnalyticsEventNames('alert_rules.viewed', 'Alert Rules: Viewed');
+ useRouteAnalyticsParams({
+ sort: Array.isArray(location.query.sort)
+ ? location.query.sort.join(',')
+ : location.query.sort,
+ });
+
+ const {
+ data: ruleListResponse = [],
+ refetch,
+ getResponseHeader,
+ isLoading,
+ isError,
+ } = useApiQuery<Array<CombinedMetricIssueAlerts | null>>(
+ getAlertListQueryKey(organization.slug, location.query),
+ {
+ staleTime: 0,
+ }
+ );
+
+ const handleChangeFilter = (activeFilters: string[]) => {
+ const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
+ router.push({
+ pathname: location.pathname,
+ query: {
+ ...currentQuery,
+ team: activeFilters.length > 0 ? activeFilters : '',
+ },
+ });
+ };
+
+ const handleChangeSearch = (name: string) => {
+ const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
+ router.push({
+ pathname: location.pathname,
+ query: {
+ ...currentQuery,
+ name,
+ },
+ });
+ };
+
+ const handleOwnerChange = (
+ projectId: string,
+ rule: CombinedMetricIssueAlerts,
+ ownerValue: string
+ ) => {
+ const endpoint =
+ rule.type === 'alert_rule'
+ ? `/organizations/${organization.slug}/alert-rules/${rule.id}`
+ : `/projects/${organization.slug}/${projectId}/rules/${rule.id}/`;
+ const updatedRule = {...rule, owner: ownerValue};
+
+ api.request(endpoint, {
+ method: 'PUT',
+ data: updatedRule,
+ success: () => {
+ addMessage(t('Updated alert rule'), 'success');
+ },
+ error: () => {
+ addMessage(t('Unable to save change'), 'error');
+ },
+ });
+ };
+
+ const handleDeleteRule = async (projectId: string, rule: CombinedMetricIssueAlerts) => {
+ try {
+ await api.requestPromise(
+ isIssueAlert(rule)
+ ? `/projects/${organization.slug}/${projectId}/rules/${rule.id}/`
+ : `/organizations/${organization.slug}/alert-rules/${rule.id}/`,
+ {
+ method: 'DELETE',
+ }
+ );
+ setApiQueryData<Array<CombinedMetricIssueAlerts | null>>(
+ queryClient,
+ getAlertListQueryKey(organization.slug, location.query),
+ data => data?.filter(r => r?.id !== rule.id && r?.type !== rule.type)
+ );
+ refetch();
+ addSuccessMessage(t('Deleted rule'));
+ } catch (_err) {
+ addErrorMessage(t('Error deleting rule'));
+ }
+ };
+
+ const hasEditAccess = organization.access.includes('alerts:write');
+
+ const ruleList = ruleListResponse.filter(defined);
+ const projectsFromResults = uniq(ruleList.flatMap(({projects}) => projects));
+ const ruleListPageLinks = getResponseHeader?.('Link');
+
+ const sort: {asc: boolean; field: SortField} = {
+ asc: location.query.asc === '1',
+ field: (location.query.sort as SortField) || defaultSort,
+ };
+ const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
+ const isAlertRuleSort =
+ sort.field.includes('incident_status') || sort.field.includes('date_triggered');
+ const sortArrow = (
+ <IconArrow color="gray300" size="xs" direction={sort.asc ? 'up' : 'down'} />
+ );
+
+ return (
+ <Fragment>
+ <SentryDocumentTitle title={t('Alerts')} orgSlug={organization.slug} />
+
+ <PageFiltersContainer>
+ <AlertHeader router={router} activeTab="rules" />
+ <Layout.Body>
+ <Layout.Main fullWidth>
+ <FilterBar
+ location={location}
+ onChangeFilter={handleChangeFilter}
+ onChangeSearch={handleChangeSearch}
+ />
+ <Teams provideUserTeams>
+ {({initiallyLoaded: loadedTeams, teams}) => (
+ <StyledPanelTable
+ isLoading={isLoading || !loadedTeams}
+ isEmpty={ruleList.length === 0 && !isError}
+ emptyMessage={t('No alert rules found for the current query.')}
+ headers={[
+ <StyledSortLink
+ key="name"
+ role="columnheader"
+ aria-sort={
+ sort.field !== 'name'
+ ? 'none'
+ : sort.asc
+ ? 'ascending'
+ : 'descending'
+ }
+ to={{
+ pathname: location.pathname,
+ query: {
+ ...currentQuery,
+ // sort by name should start by ascending on first click
+ asc: sort.field === 'name' && sort.asc ? undefined : '1',
+ sort: 'name',
+ },
+ }}
+ >
+ {t('Alert Rule')} {sort.field === 'name' ? sortArrow : null}
+ </StyledSortLink>,
+
+ <StyledSortLink
+ key="status"
+ role="columnheader"
+ aria-sort={
+ !isAlertRuleSort ? 'none' : sort.asc ? 'ascending' : 'descending'
+ }
+ to={{
+ pathname: location.pathname,
+ query: {
+ ...currentQuery,
+ asc: isAlertRuleSort && !sort.asc ? '1' : undefined,
+ sort: ['incident_status', 'date_triggered'],
+ },
+ }}
+ >
+ {t('Status')} {isAlertRuleSort ? sortArrow : null}
+ </StyledSortLink>,
+ t('Project'),
+ t('Team'),
+ t('Actions'),
+ ]}
+ >
+ {isError ? (
+ <StyledLoadingError
+ message={t('There was an error loading alerts.')}
+ onRetry={refetch}
+ />
+ ) : null}
+ <VisuallyCompleteWithData
+ id="AlertRules-Body"
+ hasData={loadedTeams && !isEmpty(ruleList)}
+ >
+ <Projects orgId={organization.slug} slugs={projectsFromResults}>
+ {({initiallyLoaded, projects}) =>
+ ruleList.map(rule => (
+ <RuleListRow
+ // Metric and issue alerts can have the same id
+ key={`${
+ isIssueAlert(rule)
+ ? AlertRuleType.METRIC
+ : AlertRuleType.ISSUE
+ }-${rule.id}`}
+ projectsLoaded={initiallyLoaded}
+ projects={projects as Project[]}
+ rule={rule}
+ orgId={organization.slug}
+ onOwnerChange={handleOwnerChange}
+ onDelete={handleDeleteRule}
+ userTeams={new Set(teams.map(team => team.id))}
+ hasEditAccess={hasEditAccess}
+ />
+ ))
+ }
+ </Projects>
+ </VisuallyCompleteWithData>
+ </StyledPanelTable>
+ )}
+ </Teams>
+ <Pagination
+ pageLinks={ruleListPageLinks}
+ onCursor={(cursor, path, _direction) => {
+ let team = currentQuery.team;
+ // Keep team parameter, but empty to remove parameters
+ if (!team || team.length === 0) {
+ team = '';
+ }
+
+ router.push({
+ pathname: path,
+ query: {...currentQuery, team, cursor},
+ });
+ }}
+ />
+ </Layout.Main>
+ </Layout.Body>
+ </PageFiltersContainer>
+ </Fragment>
+ );
+}
+
+export default AlertRulesList;
+
+const StyledLoadingError = styled(LoadingError)`
+ grid-column: 1 / -1;
+ margin-bottom: ${space(4)};
+ border-radius: 0;
+ border-width: 1px 0;
+`;
+
+const StyledSortLink = styled(Link)`
+ color: inherit;
+ display: flex;
+ align-items: center;
+ gap: ${space(0.5)};
+
+ :hover {
+ color: inherit;
+ }
+`;
+
+const StyledPanelTable = styled(PanelTable)`
+ @media (min-width: ${p => p.theme.breakpoints.small}) {
+ overflow: initial;
+ }
+
+ grid-template-columns: minmax(250px, 4fr) auto auto 60px auto;
+ white-space: nowrap;
+ font-size: ${p => p.theme.fontSizeMedium};
+`;
diff --git a/static/app/views/alerts/list/rules/index.tsx b/static/app/views/alerts/list/rules/index.tsx
deleted file mode 100644
index a2c571c5ca5c44..00000000000000
--- a/static/app/views/alerts/list/rules/index.tsx
+++ /dev/null
@@ -1,332 +0,0 @@
-import {Component} from 'react';
-import {RouteComponentProps} from 'react-router';
-import styled from '@emotion/styled';
-import isEmpty from 'lodash/isEmpty';
-import uniq from 'lodash/uniq';
-
-import {addErrorMessage, addMessage} from 'sentry/actionCreators/indicator';
-import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
-import * as Layout from 'sentry/components/layouts/thirds';
-import Link from 'sentry/components/links/link';
-import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
-import Pagination from 'sentry/components/pagination';
-import PanelTable from 'sentry/components/panels/panelTable';
-import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
-import {IconArrow} from 'sentry/icons';
-import {t} from 'sentry/locale';
-import {Organization, PageFilters, Project} from 'sentry/types';
-import {defined} from 'sentry/utils';
-import {trackAnalytics} from 'sentry/utils/analytics';
-import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
-import Projects from 'sentry/utils/projects';
-import Teams from 'sentry/utils/teams';
-import withPageFilters from 'sentry/utils/withPageFilters';
-
-import FilterBar from '../../filterBar';
-import {AlertRuleType, CombinedMetricIssueAlerts} from '../../types';
-import {getTeamParams, isIssueAlert} from '../../utils';
-import AlertHeader from '../header';
-
-import RuleListRow from './row';
-
-type Props = RouteComponentProps<{}, {}> & {
- organization: Organization;
- selection: PageFilters;
-};
-
-type State = {
- ruleList?: Array<CombinedMetricIssueAlerts | null> | null;
- teamFilterSearch?: string;
-};
-
-class AlertRulesList extends DeprecatedAsyncComponent<
- Props,
- State & DeprecatedAsyncComponent['state']
-> {
- getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
- const {organization, location} = this.props;
- const {query} = location;
-
- query.expand = ['latestIncident', 'lastTriggered'];
- query.team = getTeamParams(query.team);
-
- if (!query.sort) {
- query.sort = ['incident_status', 'date_triggered'];
- }
-
- return [
- [
- 'ruleList',
- `/organizations/${organization.slug}/combined-rules/`,
- {
- query,
- },
- ],
- ];
- }
-
- handleChangeFilter = (activeFilters: string[]) => {
- const {router, location} = this.props;
- const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
- router.push({
- pathname: location.pathname,
- query: {
- ...currentQuery,
- team: activeFilters.length > 0 ? activeFilters : '',
- },
- });
- };
-
- handleChangeSearch = (name: string) => {
- const {router, location} = this.props;
- const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
- router.push({
- pathname: location.pathname,
- query: {
- ...currentQuery,
- name,
- },
- });
- };
-
- handleOwnerChange = (
- projectId: string,
- rule: CombinedMetricIssueAlerts,
- ownerValue: string
- ) => {
- const {organization} = this.props;
- const endpoint =
- rule.type === 'alert_rule'
- ? `/organizations/${organization.slug}/alert-rules/${rule.id}`
- : `/projects/${organization.slug}/${projectId}/rules/${rule.id}/`;
- const updatedRule = {...rule, owner: ownerValue};
-
- this.api.request(endpoint, {
- method: 'PUT',
- data: updatedRule,
- success: () => {
- addMessage(t('Updated alert rule'), 'success');
- },
- error: () => {
- addMessage(t('Unable to save change'), 'error');
- },
- });
- };
-
- handleDeleteRule = async (projectId: string, rule: CombinedMetricIssueAlerts) => {
- const {organization} = this.props;
- try {
- await this.api.requestPromise(
- isIssueAlert(rule)
- ? `/projects/${organization.slug}/${projectId}/rules/${rule.id}/`
- : `/organizations/${organization.slug}/alert-rules/${rule.id}/`,
- {
- method: 'DELETE',
- }
- );
- this.reloadData();
- } catch (_err) {
- addErrorMessage(t('Error deleting rule'));
- }
- };
-
- renderLoading() {
- return this.renderBody();
- }
-
- renderList() {
- const {location, organization, router} = this.props;
- const {loading, ruleListPageLinks} = this.state;
- const {query} = location;
- const hasEditAccess = organization.access.includes('alerts:write');
- const ruleList = (this.state.ruleList ?? []).filter(defined);
- const projectsFromResults = uniq(ruleList.flatMap(({projects}) => projects));
-
- const sort: {
- asc: boolean;
- field: 'date_added' | 'name' | ['incident_status', 'date_triggered'];
- } = {
- asc: query.asc === '1',
- field: query.sort || 'date_added',
- };
- const {cursor: _cursor, page: _page, ...currentQuery} = query;
- const isAlertRuleSort =
- sort.field.includes('incident_status') || sort.field.includes('date_triggered');
- const sortArrow = (
- <IconArrow color="gray300" size="xs" direction={sort.asc ? 'up' : 'down'} />
- );
-
- return (
- <Layout.Body>
- <Layout.Main fullWidth>
- <FilterBar
- location={location}
- onChangeFilter={this.handleChangeFilter}
- onChangeSearch={this.handleChangeSearch}
- />
- <Teams provideUserTeams>
- {({initiallyLoaded: loadedTeams, teams}) => (
- <StyledPanelTable
- headers={[
- <StyledSortLink
- key="name"
- role="columnheader"
- aria-sort={
- sort.field !== 'name'
- ? 'none'
- : sort.asc
- ? 'ascending'
- : 'descending'
- }
- to={{
- pathname: location.pathname,
- query: {
- ...currentQuery,
- // sort by name should start by ascending on first click
- asc: sort.field === 'name' && sort.asc ? undefined : '1',
- sort: 'name',
- },
- }}
- >
- {t('Alert Rule')} {sort.field === 'name' && sortArrow}
- </StyledSortLink>,
-
- <StyledSortLink
- key="status"
- role="columnheader"
- aria-sort={
- !isAlertRuleSort ? 'none' : sort.asc ? 'ascending' : 'descending'
- }
- to={{
- pathname: location.pathname,
- query: {
- ...currentQuery,
- asc: isAlertRuleSort && !sort.asc ? '1' : undefined,
- sort: ['incident_status', 'date_triggered'],
- },
- }}
- >
- {t('Status')} {isAlertRuleSort && sortArrow}
- </StyledSortLink>,
-
- t('Project'),
- t('Team'),
- t('Actions'),
- ]}
- isLoading={loading || !loadedTeams}
- isEmpty={ruleList.length === 0}
- emptyMessage={t('No alert rules found for the current query.')}
- >
- <VisuallyCompleteWithData
- id="AlertRules-Body"
- hasData={loadedTeams && !isEmpty(ruleList)}
- >
- <Projects orgId={organization.slug} slugs={projectsFromResults}>
- {({initiallyLoaded, projects}) =>
- ruleList.map(rule => (
- <RuleListRow
- // Metric and issue alerts can have the same id
- key={`${
- isIssueAlert(rule)
- ? AlertRuleType.METRIC
- : AlertRuleType.ISSUE
- }-${rule.id}`}
- projectsLoaded={initiallyLoaded}
- projects={projects as Project[]}
- rule={rule}
- orgId={organization.slug}
- onOwnerChange={this.handleOwnerChange}
- onDelete={this.handleDeleteRule}
- userTeams={new Set(teams.map(team => team.id))}
- hasEditAccess={hasEditAccess}
- />
- ))
- }
- </Projects>
- </VisuallyCompleteWithData>
- </StyledPanelTable>
- )}
- </Teams>
- <Pagination
- pageLinks={ruleListPageLinks}
- onCursor={(cursor, path, _direction) => {
- let team = currentQuery.team;
- // Keep team parameter, but empty to remove parameters
- if (!team || team.length === 0) {
- team = '';
- }
-
- router.push({
- pathname: path,
- query: {...currentQuery, team, cursor},
- });
- }}
- />
- </Layout.Main>
- </Layout.Body>
- );
- }
-
- renderBody() {
- const {organization, router} = this.props;
-
- return (
- <SentryDocumentTitle title={t('Alerts')} orgSlug={organization.slug}>
- <PageFiltersContainer>
- <AlertHeader router={router} activeTab="rules" />
- {this.renderList()}
- </PageFiltersContainer>
- </SentryDocumentTitle>
- );
- }
-}
-
-class AlertRulesListContainer extends Component<Props> {
- componentDidMount() {
- this.trackView();
- }
-
- componentDidUpdate(prevProps: Props) {
- const {location} = this.props;
- if (prevProps.location.query?.sort !== location.query?.sort) {
- this.trackView();
- }
- }
-
- trackView() {
- const {organization, location} = this.props;
-
- trackAnalytics('alert_rules.viewed', {
- organization,
- sort: Array.isArray(location.query.sort)
- ? location.query.sort.join(',')
- : location.query.sort,
- });
- }
-
- render() {
- return <AlertRulesList {...this.props} />;
- }
-}
-
-export default withPageFilters(AlertRulesListContainer);
-
-const StyledSortLink = styled(Link)`
- color: inherit;
-
- :hover {
- color: inherit;
- }
-`;
-
-const StyledPanelTable = styled(PanelTable)`
- position: static;
- overflow: auto;
- @media (min-width: ${p => p.theme.breakpoints.small}) {
- overflow: initial;
- }
-
- grid-template-columns: 4fr auto 140px 60px auto;
- white-space: nowrap;
- font-size: ${p => p.theme.fontSizeMedium};
-`;
diff --git a/static/app/views/alerts/list/rules/row.tsx b/static/app/views/alerts/list/rules/row.tsx
index 0760c53607fc0f..3e244ded372f6a 100644
--- a/static/app/views/alerts/list/rules/row.tsx
+++ b/static/app/views/alerts/list/rules/row.tsx
@@ -443,10 +443,10 @@ const IssueAlertStatusWrapper = styled('div')`
`;
const AlertNameWrapper = styled('div')<{isIssueAlert?: boolean}>`
+ ${p => p.theme.overflowEllipsis}
display: flex;
align-items: center;
gap: ${space(2)};
- position: relative;
${p => p.isIssueAlert && `padding: ${space(3)} ${space(2)}; line-height: 2.4;`}
`;
@@ -458,16 +458,6 @@ const AlertNameAndStatus = styled('div')`
const AlertName = styled('div')`
${p => p.theme.overflowEllipsis}
font-size: ${p => p.theme.fontSizeLarge};
-
- @media (max-width: ${p => p.theme.breakpoints.xlarge}) {
- max-width: 300px;
- }
- @media (max-width: ${p => p.theme.breakpoints.large}) {
- max-width: 165px;
- }
- @media (max-width: ${p => p.theme.breakpoints.medium}) {
- max-width: 100px;
- }
`;
const AlertIncidentDate = styled('div')`
|
eb98a3d0eff18b2754253a6caaec7ef194130592
|
2024-08-08 22:56:01
|
Cathy Teng
|
fix(slack): fix disappearing tags for issue button actions (#75789)
| false
|
fix disappearing tags for issue button actions (#75789)
|
fix
|
diff --git a/src/sentry/integrations/slack/webhooks/action.py b/src/sentry/integrations/slack/webhooks/action.py
index bcce3dfedd7352..8103d456665d98 100644
--- a/src/sentry/integrations/slack/webhooks/action.py
+++ b/src/sentry/integrations/slack/webhooks/action.py
@@ -383,6 +383,7 @@ def open_resolve_dialog(self, slack_request: SlackActionRequest, group: Group) -
"issue": group.id,
"orig_response_url": slack_request.data["response_url"],
"is_message": _is_message(slack_request.data),
+ "tags": list(slack_request.get_tags()),
}
if slack_request.data.get("channel"):
callback_id["channel_id"] = slack_request.data["channel"]["id"]
@@ -426,6 +427,7 @@ def open_archive_dialog(self, slack_request: SlackActionRequest, group: Group) -
"orig_response_url": slack_request.data["response_url"],
"is_message": _is_message(slack_request.data),
"rule": slack_request.callback_data.get("rule"),
+ "tags": list(slack_request.get_tags()),
}
if slack_request.data.get("channel"):
@@ -530,6 +532,10 @@ def _handle_group_actions(
except client.ApiError as error:
return self.api_error(slack_request, group, identity_user, error, "status_dialog")
+ view = View(**slack_request.data["view"])
+ private_metadata = orjson.loads(view.private_metadata)
+ original_tags_from_request = set(private_metadata["tags"])
+
blocks = SlackIssuesMessageBuilder(
group,
identity=identity,
@@ -542,9 +548,7 @@ def _handle_group_actions(
# use the original response_url to update the link attachment
json_blocks = orjson.dumps(blocks.get("blocks")).decode()
- view = View(**slack_request.data["view"])
try:
- private_metadata = orjson.loads(view.private_metadata)
webhook_client = WebhookClient(private_metadata["orig_response_url"])
webhook_client.send(
blocks=json_blocks, delete_original=False, replace_original=True
diff --git a/tests/sentry/integrations/slack/webhooks/actions/test_status.py b/tests/sentry/integrations/slack/webhooks/actions/test_status.py
index 72326ac01a3fbf..396fa3e3095ec1 100644
--- a/tests/sentry/integrations/slack/webhooks/actions/test_status.py
+++ b/tests/sentry/integrations/slack/webhooks/actions/test_status.py
@@ -234,7 +234,8 @@ def test_ask_linking(self):
assert resp.data["response_type"] == "ephemeral"
assert resp.data["text"] == LINK_IDENTITY_MESSAGE.format(associate_url=associate_url)
- def test_archive_issue_until_escalating(self):
+ @patch("sentry.integrations.slack.message_builder.issues.get_tags", return_value=[])
+ def test_archive_issue_until_escalating(self, mock_tags):
original_message = self.get_original_message(self.group.id)
self.archive_issue(original_message, "ignored:archived_until_escalating")
@@ -244,13 +245,16 @@ def test_archive_issue_until_escalating(self):
blocks = orjson.loads(self.mock_post.call_args.kwargs["blocks"])
+ assert mock_tags.call_args.kwargs["tags"] == self.tags
+
expect_status = f"*Issue archived by <@{self.external_id}>*"
assert self.notification_text in blocks[1]["text"]["text"]
assert blocks[2]["text"]["text"].endswith(expect_status)
assert "via" not in blocks[4]["elements"][0]["text"]
assert ":white_circle:" in blocks[0]["text"]["text"]
- def test_archive_issue_until_escalating_through_unfurl(self):
+ @patch("sentry.integrations.slack.message_builder.issues.get_tags", return_value=[])
+ def test_archive_issue_until_escalating_through_unfurl(self, mock_tags):
original_message = self.get_original_message(self.group.id)
payload_data = self.get_unfurl_data(original_message["blocks"])
self.archive_issue(original_message, "ignored:archived_until_escalating", payload_data)
@@ -260,12 +264,14 @@ def test_archive_issue_until_escalating_through_unfurl(self):
assert self.group.substatus == GroupSubStatus.UNTIL_ESCALATING
blocks = orjson.loads(self.mock_post.call_args.kwargs["blocks"])
+ assert mock_tags.call_args.kwargs["tags"] == self.tags
expect_status = f"*Issue archived by <@{self.external_id}>*"
assert self.notification_text in blocks[1]["text"]["text"]
assert blocks[2]["text"]["text"].endswith(expect_status)
- def test_archive_issue_until_condition_met(self):
+ @patch("sentry.integrations.slack.message_builder.issues.get_tags", return_value=[])
+ def test_archive_issue_until_condition_met(self, mock_tags):
original_message = self.get_original_message(self.group.id)
self.archive_issue(original_message, "ignored:archived_until_condition_met:10")
@@ -276,12 +282,14 @@ def test_archive_issue_until_condition_met(self):
assert group_snooze.count == 10
blocks = orjson.loads(self.mock_post.call_args.kwargs["blocks"])
+ assert mock_tags.call_args.kwargs["tags"] == self.tags
expect_status = f"*Issue archived by <@{self.external_id}>*"
assert self.notification_text in blocks[1]["text"]["text"]
assert blocks[2]["text"]["text"].endswith(expect_status)
- def test_archive_issue_until_condition_met_through_unfurl(self):
+ @patch("sentry.integrations.slack.message_builder.issues.get_tags", return_value=[])
+ def test_archive_issue_until_condition_met_through_unfurl(self, mock_tags):
original_message = self.get_original_message(self.group.id)
payload_data = self.get_unfurl_data(original_message["blocks"])
self.archive_issue(
@@ -295,12 +303,14 @@ def test_archive_issue_until_condition_met_through_unfurl(self):
assert group_snooze.count == 100
blocks = orjson.loads(self.mock_post.call_args.kwargs["blocks"])
+ assert mock_tags.call_args.kwargs["tags"] == self.tags
expect_status = f"*Issue archived by <@{self.external_id}>*"
assert self.notification_text in blocks[1]["text"]["text"]
assert blocks[2]["text"]["text"].endswith(expect_status)
- def test_archive_issue_forever_with(self):
+ @patch("sentry.integrations.slack.message_builder.issues.get_tags", return_value=[])
+ def test_archive_issue_forever(self, mock_tags):
original_message = self.get_original_message(self.group.id)
self.archive_issue(original_message, "ignored:archived_forever")
@@ -309,6 +319,7 @@ def test_archive_issue_forever_with(self):
assert self.group.substatus == GroupSubStatus.FOREVER
blocks = orjson.loads(self.mock_post.call_args.kwargs["blocks"])
+ assert mock_tags.call_args.kwargs["tags"] == self.tags
expect_status = f"*Issue archived by <@{self.external_id}>*"
assert self.notification_text in blocks[1]["text"]["text"]
@@ -328,7 +339,8 @@ def test_archive_issue_forever_error(self, mock_access):
assert self.group.get_status() == GroupStatus.UNRESOLVED
assert self.group.substatus == GroupSubStatus.ONGOING
- def test_archive_issue_forever_through_unfurl(self):
+ @patch("sentry.integrations.slack.message_builder.issues.get_tags", return_value=[])
+ def test_archive_issue_forever_through_unfurl(self, mock_tags):
original_message = self.get_original_message(self.group.id)
payload_data = self.get_unfurl_data(original_message["blocks"])
self.archive_issue(original_message, "ignored:archived_forever", payload_data)
@@ -338,6 +350,7 @@ def test_archive_issue_forever_through_unfurl(self):
assert self.group.substatus == GroupSubStatus.FOREVER
blocks = orjson.loads(self.mock_post.call_args.kwargs["blocks"])
+ assert mock_tags.call_args.kwargs["tags"] == self.tags
expect_status = f"*Issue archived by <@{self.external_id}>*"
assert self.notification_text in blocks[1]["text"]["text"]
@@ -389,7 +402,8 @@ def test_archive_issue_with_additional_user_auth_through_unfurl(self):
assert self.notification_text in blocks[1]["text"]["text"]
assert blocks[2]["text"]["text"].endswith(expect_status)
- def test_unarchive_issue(self):
+ @patch("sentry.integrations.slack.message_builder.issues.get_tags", return_value=[])
+ def test_unarchive_issue(self, mock_tags):
self.group.status = GroupStatus.IGNORED
self.group.substatus = GroupSubStatus.UNTIL_ESCALATING
self.group.save(update_fields=["status", "substatus"])
@@ -407,12 +421,14 @@ def test_unarchive_issue(self):
assert self.group.substatus == GroupSubStatus.NEW # the issue is less than 7 days old
blocks = orjson.loads(self.mock_post.call_args.kwargs["blocks"])
+ assert mock_tags.call_args.kwargs["tags"] == self.tags
expect_status = f"*Issue re-opened by <@{self.external_id}>*"
assert self.notification_text in blocks[1]["text"]["text"]
assert blocks[2]["text"]["text"].endswith(expect_status)
- def test_unarchive_issue_through_unfurl(self):
+ @patch("sentry.integrations.slack.message_builder.issues.get_tags", return_value=[])
+ def test_unarchive_issue_through_unfurl(self, mock_tags):
self.group.status = GroupStatus.IGNORED
self.group.substatus = GroupSubStatus.UNTIL_ESCALATING
self.group.save(update_fields=["status", "substatus"])
@@ -431,6 +447,7 @@ def test_unarchive_issue_through_unfurl(self):
assert self.group.substatus == GroupSubStatus.NEW # the issue is less than 7 days old
blocks = orjson.loads(self.mock_post.call_args.kwargs["blocks"])
+ assert mock_tags.call_args.kwargs["tags"] == self.tags
expect_status = f"*Issue re-opened by <@{self.external_id}>*"
assert self.notification_text in blocks[1]["text"]["text"]
@@ -683,7 +700,8 @@ def test_assign_user_with_multiple_identities_through_unfurl(self):
assert self.notification_text in blocks[1]["text"]["text"]
assert blocks[2]["text"]["text"].endswith(expect_status), text
- def test_resolve_issue(self):
+ @patch("sentry.integrations.slack.message_builder.issues.get_tags", return_value=[])
+ def test_resolve_issue(self, mock_tags):
original_message = self.get_original_message(self.group.id)
self.resolve_issue(original_message, "resolved")
@@ -692,13 +710,15 @@ def test_resolve_issue(self):
assert not GroupResolution.objects.filter(group=self.group)
blocks = orjson.loads(self.mock_post.call_args.kwargs["blocks"])
+ assert mock_tags.call_args.kwargs["tags"] == self.tags
expect_status = f"*Issue resolved by <@{self.external_id}>*"
assert self.notification_text in blocks[1]["text"]["text"]
assert blocks[2]["text"]["text"] == expect_status
assert ":white_circle:" in blocks[0]["text"]["text"]
- def test_resolve_perf_issue(self):
+ @patch("sentry.integrations.slack.message_builder.issues.get_tags", return_value=[])
+ def test_resolve_perf_issue(self, mock_tags):
group_fingerprint = f"{PerformanceNPlusOneGroupType.type_id}-group1"
event_data_2 = load_data("transaction-n-plus-one", fingerprint=[group_fingerprint])
@@ -720,6 +740,7 @@ def test_resolve_perf_issue(self):
assert not GroupResolution.objects.filter(group=self.group)
blocks = orjson.loads(self.mock_post.call_args.kwargs["blocks"])
+ assert mock_tags.call_args.kwargs["tags"] == self.tags
expect_status = f"*Issue resolved by <@{self.external_id}>*"
assert (
@@ -729,7 +750,8 @@ def test_resolve_perf_issue(self):
assert blocks[3]["text"]["text"] == expect_status
assert ":white_circle: :chart_with_upwards_trend:" in blocks[0]["text"]["text"]
- def test_resolve_issue_through_unfurl(self):
+ @patch("sentry.integrations.slack.message_builder.issues.get_tags", return_value=[])
+ def test_resolve_issue_through_unfurl(self, mock_tags):
original_message = self.get_original_message(self.group.id)
payload_data = self.get_unfurl_data(original_message["blocks"])
self.resolve_issue(original_message, "resolved", payload_data)
@@ -739,12 +761,14 @@ def test_resolve_issue_through_unfurl(self):
assert not GroupResolution.objects.filter(group=self.group)
blocks = orjson.loads(self.mock_post.call_args.kwargs["blocks"])
+ assert mock_tags.call_args.kwargs["tags"] == self.tags
expect_status = f"*Issue resolved by <@{self.external_id}>*"
assert self.notification_text in blocks[1]["text"]["text"]
assert blocks[2]["text"]["text"] == expect_status
- def test_resolve_issue_in_current_release(self):
+ @patch("sentry.integrations.slack.message_builder.issues.get_tags", return_value=[])
+ def test_resolve_issue_in_current_release(self, mock_tags):
release = Release.objects.create(
organization_id=self.organization.id,
version="1.0",
@@ -761,12 +785,14 @@ def test_resolve_issue_in_current_release(self):
assert resolution.release == release
blocks = orjson.loads(self.mock_post.call_args.kwargs["blocks"])
+ assert mock_tags.call_args.kwargs["tags"] == self.tags
expect_status = f"*Issue resolved by <@{self.external_id}>*"
assert self.notification_text in blocks[1]["text"]["text"]
assert blocks[2]["text"]["text"].endswith(expect_status)
- def test_resolve_issue_in_current_release_through_unfurl(self):
+ @patch("sentry.integrations.slack.message_builder.issues.get_tags", return_value=[])
+ def test_resolve_issue_in_current_release_through_unfurl(self, mock_tags):
release = Release.objects.create(
organization_id=self.organization.id,
version="1.0",
@@ -784,12 +810,14 @@ def test_resolve_issue_in_current_release_through_unfurl(self):
assert resolution.release == release
blocks = orjson.loads(self.mock_post.call_args.kwargs["blocks"])
+ assert mock_tags.call_args.kwargs["tags"] == self.tags
expect_status = f"*Issue resolved by <@{self.external_id}>*"
assert self.notification_text in blocks[1]["text"]["text"]
assert blocks[2]["text"]["text"].endswith(expect_status)
- def test_resolve_in_next_release(self):
+ @patch("sentry.integrations.slack.message_builder.issues.get_tags", return_value=[])
+ def test_resolve_in_next_release(self, mock_tags):
release = Release.objects.create(
organization_id=self.organization.id,
version="1.0",
@@ -805,12 +833,14 @@ def test_resolve_in_next_release(self):
assert resolution.release == release
blocks = orjson.loads(self.mock_post.call_args.kwargs["blocks"])
+ assert mock_tags.call_args.kwargs["tags"] == self.tags
expect_status = f"*Issue resolved by <@{self.external_id}>*"
assert self.notification_text in blocks[1]["text"]["text"]
assert blocks[2]["text"]["text"].endswith(expect_status)
- def test_resolve_in_next_release_through_unfurl(self):
+ @patch("sentry.integrations.slack.message_builder.issues.get_tags", return_value=[])
+ def test_resolve_in_next_release_through_unfurl(self, mock_tags):
release = Release.objects.create(
organization_id=self.organization.id,
version="1.0",
@@ -827,6 +857,7 @@ def test_resolve_in_next_release_through_unfurl(self):
assert resolution.release == release
blocks = orjson.loads(self.mock_post.call_args.kwargs["blocks"])
+ assert mock_tags.call_args.kwargs["tags"] == self.tags
expect_status = f"*Issue resolved by <@{self.external_id}>*"
assert self.notification_text in blocks[1]["text"]["text"]
|
b1ce765f0a3288949e8f17c87645f93c5f1f7858
|
2023-03-23 22:11:09
|
Armen Zambrano G
|
feat(codecov): Bump timeout to 10 seconds (#46257)
| false
|
Bump timeout to 10 seconds (#46257)
|
feat
|
diff --git a/src/sentry/integrations/utils/codecov.py b/src/sentry/integrations/utils/codecov.py
index 0160c191a3b083..d24b9e7a164b28 100644
--- a/src/sentry/integrations/utils/codecov.py
+++ b/src/sentry/integrations/utils/codecov.py
@@ -17,7 +17,7 @@
"https://api.codecov.io/api/v2/{service}/{owner_username}/repos/{repo_name}/file_report/{path}"
)
CODECOV_REPOS_URL = "https://api.codecov.io/api/v2/{service}/{owner_username}"
-CODECOV_TIMEOUT = 2
+CODECOV_TIMEOUT = 10
logger = logging.getLogger(__name__)
@@ -161,6 +161,7 @@ def fetch_codecov_data(config: Any) -> Tuple[Optional[Dict[str, Any]], Optional[
except requests.Timeout:
with configure_scope() as scope:
scope.set_tag("codecov.timeout", True)
+ scope.set_tag("codecov.timeout_secs", CODECOV_TIMEOUT)
return {
"status": status.HTTP_408_REQUEST_TIMEOUT,
}, "Codecov request timed out. Continuing execution."
|
322c0a7c18b791e9a98cf1310cfab0bf7cd3d85a
|
2019-09-03 23:21:16
|
Billy Vong
|
feat(ui): Change threshold UX in Incident Rules (#14488)
| false
|
Change threshold UX in Incident Rules (#14488)
|
feat
|
diff --git a/src/sentry/static/sentry/app/views/settings/projectIncidentRules/chart.tsx b/src/sentry/static/sentry/app/views/settings/projectIncidentRules/chart.tsx
index bb95cde4ba96ce..a4a8f369a78e2b 100644
--- a/src/sentry/static/sentry/app/views/settings/projectIncidentRules/chart.tsx
+++ b/src/sentry/static/sentry/app/views/settings/projectIncidentRules/chart.tsx
@@ -18,6 +18,7 @@ type Props = {
isInverted: boolean;
onChangeIncidentThreshold: (alertThreshold: number) => void;
onChangeResolutionThreshold: (resolveThreshold: number) => void;
+ maxValue?: number;
};
type State = {
diff --git a/src/sentry/static/sentry/app/views/settings/projectIncidentRules/ruleForm.tsx b/src/sentry/static/sentry/app/views/settings/projectIncidentRules/ruleForm.tsx
index 2aa5827b6f9d32..eec27064bc459d 100644
--- a/src/sentry/static/sentry/app/views/settings/projectIncidentRules/ruleForm.tsx
+++ b/src/sentry/static/sentry/app/views/settings/projectIncidentRules/ruleForm.tsx
@@ -1,11 +1,13 @@
-import {debounce} from 'lodash';
+import {debounce, maxBy} from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
+import moment from 'moment-timezone';
import styled from 'react-emotion';
import {Client} from 'app/api';
import {Config, EventsStatsData, Organization, Project} from 'app/types';
import {PanelAlert} from 'app/components/panels';
+import {SeriesDataUnit} from 'app/types/echarts';
import {addErrorMessage} from 'app/actionCreators/indicator';
import {getFormattedDate} from 'app/utils/dates';
import {t} from 'app/locale';
@@ -29,24 +31,6 @@ import {
import {IncidentRule} from './types';
import IncidentRulesChart from './chart';
-type Props = {
- api: Client;
- config: Config;
- data: EventsStatsData;
- organization: Organization;
- project: Project;
- initialData?: IncidentRule;
-};
-
-type State = {
- width?: number;
- aggregations: AlertRuleAggregations[];
- isInverted: boolean;
- timeWindow: number;
- alertThreshold: number | null;
- resolveThreshold: number | null;
-};
-
type AlertRuleThresholdKey = {
[AlertRuleThreshold.INCIDENT]: 'alertThreshold';
[AlertRuleThreshold.RESOLUTION]: 'resolveThreshold';
@@ -92,6 +76,26 @@ const TIME_WINDOW_TO_PERIOD: TimeWindowMapType = {
const DEFAULT_TIME_WINDOW = 60;
const DEFAULT_METRIC = [AlertRuleAggregations.TOTAL];
+const DEFAULT_MAX_THRESHOLD = 100;
+
+type Props = {
+ api: Client;
+ config: Config;
+ data: EventsStatsData;
+ organization: Organization;
+ project: Project;
+ initialData?: IncidentRule;
+};
+
+type State = {
+ width?: number;
+ aggregations: AlertRuleAggregations[];
+ isInverted: boolean;
+ timeWindow: number;
+ alertThreshold: number | null;
+ resolveThreshold: number | null;
+ maxThreshold: number | null;
+};
class RuleForm extends React.Component<Props, State> {
static contextTypes = {
@@ -116,6 +120,12 @@ class RuleForm extends React.Component<Props, State> {
resolveThreshold: this.props.initialData
? this.props.initialData.resolveThreshold
: null,
+ maxThreshold: this.props.initialData
+ ? Math.max(
+ this.props.initialData.alertThreshold,
+ this.props.initialData.resolveThreshold
+ ) || null
+ : null,
};
getThresholdKey = (
@@ -158,6 +168,14 @@ class RuleForm extends React.Component<Props, State> {
: value >= otherValue;
};
+ /**
+ * Happens if the target threshold value is in valid. We do not pre-validate because
+ * it's difficult to do so with our charting library, so we validate after the
+ * change propagates.
+ *
+ * Show an error message and reset form value, as well as force a re-rendering of chart
+ * with old values (so the dragged line "resets")
+ */
revertThresholdUpdate = (type: AlertRuleThreshold) => {
const isIncident = type === AlertRuleThreshold.INCIDENT;
const typeDisplay = isIncident ? t('Incident boundary') : t('Resolution boundary');
@@ -180,17 +198,25 @@ class RuleForm extends React.Component<Props, State> {
this.context.form.setValue(thresholdKey, this.state[thresholdKey]);
};
+ /**
+ * Handler for the range slider input. Needs to update state (as well as max threshold)
+ */
updateThresholdInput = (type: AlertRuleThreshold, value: number) => {
if (this.canUpdateThreshold(type, value)) {
this.setState(state => ({
...state,
[this.getThresholdKey(type)]: value,
+ ...(value > (state.maxThreshold || 0) && {maxThreshold: value}),
}));
} else {
this.revertThresholdUpdate(type);
}
};
+ /**
+ * Handler for threshold changes coming from slider or chart.
+ * Needs to sync state with the form.
+ */
updateThreshold = (type: AlertRuleThreshold, value: number) => {
if (this.canUpdateThreshold(type, value)) {
const thresholdKey = this.getThresholdKey(type);
@@ -198,6 +224,7 @@ class RuleForm extends React.Component<Props, State> {
this.setState(state => ({
...state,
[thresholdKey]: newValue,
+ ...(newValue > (state.maxThreshold || 0) && {maxThreshold: newValue}),
}));
this.context.form.setValue(thresholdKey, Math.round(newValue));
} else {
@@ -256,6 +283,7 @@ class RuleForm extends React.Component<Props, State> {
aggregations,
alertThreshold,
resolveThreshold,
+ maxThreshold,
isInverted,
timeWindow,
} = this.state;
@@ -273,152 +301,205 @@ class RuleForm extends React.Component<Props, State> {
}
includePrevious={false}
>
- {({loading, reloading, timeseriesData}) =>
- loading ? (
- <Placeholder height="200px" bottomGutter={1} />
- ) : (
+ {({loading, reloading, timeseriesData}) => {
+ let maxValue: SeriesDataUnit | undefined;
+ if (timeseriesData && timeseriesData.length && timeseriesData[0].data) {
+ maxValue = maxBy(timeseriesData[0].data, ({value}) => value);
+ }
+
+ // Take the max value from chart data OR use a static default value
+ const defaultMaxThresholdOrDefault =
+ (maxValue && maxValue.value) || DEFAULT_MAX_THRESHOLD;
+
+ // If not inverted, the alert threshold will be the upper bound
+ // If we have a stateful max threshold (e.g. from input field), use that value, otherwise use a default
+ // If this is the lower bound, then max should be the max of: stateful max threshold, or the default
+ // This logic is inverted for the resolve threshold
+ const alertMaxThreshold = !isInverted
+ ? {
+ max:
+ maxThreshold === null ? defaultMaxThresholdOrDefault : maxThreshold,
+ }
+ : resolveThreshold !== null && {
+ max:
+ maxThreshold && maxThreshold > defaultMaxThresholdOrDefault
+ ? maxThreshold
+ : defaultMaxThresholdOrDefault,
+ };
+ const resolveMaxThreshold = !isInverted
+ ? alertThreshold !== null && {
+ max:
+ maxThreshold && maxThreshold > defaultMaxThresholdOrDefault
+ ? maxThreshold
+ : defaultMaxThresholdOrDefault,
+ }
+ : {
+ max:
+ maxThreshold === null ? defaultMaxThresholdOrDefault : maxThreshold,
+ };
+
+ return (
<React.Fragment>
- <TransparentLoadingMask visible={reloading} />
- <IncidentRulesChart
- xAxis={{
- axisLabel: {
- formatter: (value, index) => {
- const firstItem = index === 0;
- const format =
- timeWindow <= TimeWindow.FIVE_MINUTES && !firstItem
- ? 'LT'
- : 'MMM Do';
- return getFormattedDate(value, format, {
- local: config.user.options.timezone !== 'UTC',
- });
+ {loading ? (
+ <Placeholder height="200px" bottomGutter={1} />
+ ) : (
+ <React.Fragment>
+ <TransparentLoadingMask visible={reloading} />
+ <IncidentRulesChart
+ xAxis={{
+ axisLabel: {
+ formatter: (value: moment.MomentInput, index: number) => {
+ const firstItem = index === 0;
+ const format =
+ timeWindow <= TimeWindow.FIVE_MINUTES && !firstItem
+ ? 'LT'
+ : 'MMM Do';
+ return getFormattedDate(value, format, {
+ local: config.user.options.timezone !== 'UTC',
+ });
+ },
+ },
+ }}
+ maxValue={maxValue ? maxValue.value : maxValue}
+ onChangeIncidentThreshold={this.handleChangeIncidentThreshold}
+ alertThreshold={alertThreshold}
+ onChangeResolutionThreshold={this.handleChangeResolutionThreshold}
+ resolveThreshold={resolveThreshold}
+ isInverted={isInverted}
+ data={timeseriesData}
+ />
+ </React.Fragment>
+ )}
+
+ <div>
+ <TransparentLoadingMask visible={loading} />
+ <JsonForm
+ renderHeader={() => {
+ return (
+ <PanelAlert type="warning">
+ {t(
+ 'Sentry will automatically digest alerts sent by some services to avoid flooding your inbox with individual issue notifications. Use the sliders to control frequency.'
+ )}
+ </PanelAlert>
+ );
+ }}
+ forms={[
+ {
+ title: t('Metric'),
+ fields: [
+ {
+ name: 'aggregations',
+ type: 'select',
+ label: t('Metric'),
+ help: t('Choose which metric to display on the Y-axis'),
+ choices: [
+ [AlertRuleAggregations.UNIQUE_USERS, 'Users Affected'],
+ [AlertRuleAggregations.TOTAL, 'Events'],
+ ],
+ required: true,
+ setValue: value => (value && value.length ? value[0] : value),
+ getValue: value => [value],
+ onChange: this.handleChangeMetric,
+ },
+ {
+ name: 'query',
+ type: 'custom',
+ label: t('Filter'),
+ defaultValue: '',
+ placeholder: 'error.type:TypeError',
+ help: t(
+ 'You can apply standard Sentry filter syntax to filter by status, user, etc.'
+ ),
+ Component: props => {
+ return (
+ <FormField {...props}>
+ {({onChange, onBlur, onKeyDown}) => {
+ return (
+ <SearchBar
+ organization={organization}
+ onChange={onChange}
+ onBlur={onBlur}
+ onKeyDown={onKeyDown}
+ onSearch={query => onChange(query, {})}
+ />
+ );
+ }}
+ </FormField>
+ );
+ },
+ },
+ {
+ name: 'alertThreshold',
+ type: 'range',
+ label: t('Incident Boundary'),
+ help: !isInverted
+ ? t(
+ 'Anything trending above this limit will trigger an Incident'
+ )
+ : t(
+ 'Anything trending below this limit will trigger an Incident'
+ ),
+ onChange: this.handleChangeIncidentThresholdInput,
+ showCustomInput: true,
+ required: true,
+ min: 1,
+ ...alertMaxThreshold,
+ },
+ {
+ name: 'resolveThreshold',
+ type: 'range',
+ label: t('Resolution Boundary'),
+ help: !isInverted
+ ? t(
+ 'Anything trending below this limit will resolve an Incident'
+ )
+ : t(
+ 'Anything trending above this limit will resolve an Incident'
+ ),
+ onChange: this.handleChangeResolutionThresholdInput,
+ showCustomInput: true,
+ placeholder: resolveThreshold === null ? t('Off') : '',
+ min: 1,
+ ...resolveMaxThreshold,
+ },
+ {
+ name: 'thresholdType',
+ type: 'boolean',
+ label: t('Reverse the Boundaries'),
+ defaultValue: AlertRuleThresholdType.ABOVE,
+ help: t(
+ 'This is a metric that needs to stay above a certain threshold'
+ ),
+ onChange: this.handleChangeThresholdType,
+ },
+ {
+ name: 'timeWindow',
+ type: 'select',
+ label: t('Time Window'),
+ help: t('The time window to use when evaluating the Metric'),
+ onChange: this.handleTimeWindowChange,
+ choices: Object.entries(TIME_WINDOW_MAP),
+ required: true,
+ },
+ {
+ name: 'name',
+ type: 'text',
+ label: t('Name'),
+ help: t(
+ 'Give your Incident Rule a name so it is easy to manage later'
+ ),
+ placeholder: t('My Incident Rule Name'),
+ required: true,
+ },
+ ],
},
- },
- }}
- onChangeIncidentThreshold={this.handleChangeIncidentThreshold}
- alertThreshold={alertThreshold}
- onChangeResolutionThreshold={this.handleChangeResolutionThreshold}
- resolveThreshold={resolveThreshold}
- isInverted={isInverted}
- data={timeseriesData}
- />
+ ]}
+ />
+ </div>
</React.Fragment>
- )
- }
- </EventsRequest>
- <JsonForm
- renderHeader={() => {
- return (
- <PanelAlert type="info">
- {t(
- 'Sentry will automatically digest alerts sent by some services to avoid flooding your inbox with individual issue notifications. Use the sliders to control frequency.'
- )}
- </PanelAlert>
);
}}
- forms={[
- {
- title: t('Metric'),
- fields: [
- {
- name: 'aggregations',
- type: 'select',
- label: t('Metric'),
- help: t('Choose which metric to display on the Y-axis'),
- choices: [
- [AlertRuleAggregations.UNIQUE_USERS, 'Users Affected'],
- [AlertRuleAggregations.TOTAL, 'Events'],
- ],
- required: true,
- setValue: value => (value && value.length ? value[0] : value),
- getValue: value => [value],
- onChange: this.handleChangeMetric,
- },
- {
- name: 'query',
- type: 'custom',
- label: t('Filter'),
- defaultValue: '',
- placeholder: 'error.type:TypeError',
- help: t(
- 'You can apply standard Sentry filter syntax to filter by status, user, etc.'
- ),
- Component: props => {
- return (
- <FormField {...props}>
- {({onChange, onBlur, onKeyDown}) => {
- return (
- <SearchBar
- useFormWrapper={false}
- organization={organization}
- onChange={onChange}
- onBlur={onBlur}
- onKeyDown={onKeyDown}
- onSearch={query => onChange(query, {})}
- />
- );
- }}
- </FormField>
- );
- },
- },
- {
- name: 'alertThreshold',
- type: 'range',
- label: t('Incident Boundary'),
- help: !isInverted
- ? t('Anything trending above this limit will trigger an Incident')
- : t('Anything trending below this limit will trigger an Incident'),
- onChange: this.handleChangeIncidentThresholdInput,
- showCustomInput: true,
- required: true,
- min: 1,
- },
- {
- name: 'resolveThreshold',
- type: 'range',
- label: t('Resolution Boundary'),
- help: !isInverted
- ? t('Anything trending below this limit will resolve an Incident')
- : t('Anything trending above this limit will resolve an Incident'),
- onChange: this.handleChangeResolutionThresholdInput,
- showCustomInput: true,
- placeholder: resolveThreshold === null ? t('Off') : '',
- ...(!isInverted &&
- alertThreshold !== null && {min: 1, max: alertThreshold}),
- ...(isInverted &&
- alertThreshold !== null && {min: alertThreshold || 1}),
- },
- {
- name: 'thresholdType',
- type: 'boolean',
- label: t('Reverse the Boundaries'),
- defaultValue: AlertRuleThresholdType.ABOVE,
- help: t(
- 'This is a metric that needs to stay above a certain threshold'
- ),
- onChange: this.handleChangeThresholdType,
- },
- {
- name: 'timeWindow',
- type: 'select',
- label: t('Time Window'),
- help: t('The time window to use when evaluating the Metric'),
- onChange: this.handleTimeWindowChange,
- choices: Object.entries(TIME_WINDOW_MAP),
- required: true,
- },
- {
- name: 'name',
- type: 'text',
- label: t('Name'),
- help: t('Give your Incident Rule a name so it is easy to manage later'),
- placeholder: t('My Incident Rule Name'),
- required: true,
- },
- ],
- },
- ]}
- />
+ </EventsRequest>
</React.Fragment>
);
}
@@ -435,6 +516,7 @@ type RuleFormContainerProps = {
initialData?: IncidentRule;
onSubmitSuccess?: Function;
};
+
function RuleFormContainer({
api,
organization,
|
848829c51145539e90c22717fff88d969505e327
|
2022-07-27 23:45:24
|
Lyn Nagara
|
ref: Remove dead code from post process forwarder (#37119)
| false
|
Remove dead code from post process forwarder (#37119)
|
ref
|
diff --git a/src/sentry/eventstream/kafka/backend.py b/src/sentry/eventstream/kafka/backend.py
index 6839bd6461c9e5..630a8f6f75bd1e 100644
--- a/src/sentry/eventstream/kafka/backend.py
+++ b/src/sentry/eventstream/kafka/backend.py
@@ -14,10 +14,9 @@
PostProcessForwarderWorker,
TransactionsPostProcessForwarderWorker,
)
-from sentry.eventstream.kafka.protocol import get_task_kwargs_for_message
from sentry.eventstream.snuba import KW_SKIP_SEMANTIC_PARTITIONING, SnubaProtocolEventStream
from sentry.killswitches import killswitch_matches_context
-from sentry.utils import json, kafka, metrics
+from sentry.utils import json, kafka
from sentry.utils.batching_kafka_consumer import BatchingKafkaConsumer
logger = logging.getLogger(__name__)
@@ -264,24 +263,6 @@ def handler(signum, frame):
consumer.run()
- def _get_task_kwargs_and_dispatch(self, message) -> None:
- with metrics.timer("eventstream.duration", instance="get_task_kwargs_for_message"):
- task_kwargs = get_task_kwargs_for_message(message.value())
-
- if task_kwargs is not None:
- if task_kwargs["group_id"] is None:
- metrics.incr(
- "eventstream.messages",
- tags={"partition": message.partition(), "type": "transactions"},
- )
- else:
- metrics.incr(
- "eventstream.messages",
- tags={"partition": message.partition(), "type": "errors"},
- )
- with metrics.timer("eventstream.duration", instance="dispatch_post_process_group_task"):
- self._dispatch_post_process_group_task(**task_kwargs)
-
def run_post_process_forwarder(
self,
entity: Union[Literal["all"], Literal["errors"], Literal["transactions"]],
|
dc0fddedd60a8e90b27424328beae5f6872777a1
|
2021-03-10 00:41:50
|
Alex Xu @ Sentry
|
perf: make transaction summary not wait for top-level query (#24298)
| false
|
make transaction summary not wait for top-level query (#24298)
|
perf
|
diff --git a/src/sentry/static/sentry/app/components/discover/transactionsList.tsx b/src/sentry/static/sentry/app/components/discover/transactionsList.tsx
index 01f6bbaa34818b..56005d520f77c4 100644
--- a/src/sentry/static/sentry/app/components/discover/transactionsList.tsx
+++ b/src/sentry/static/sentry/app/components/discover/transactionsList.tsx
@@ -121,6 +121,10 @@ type Props = {
* The callback for when Open in Discover is clicked.
*/
handleOpenInDiscoverClick?: (e: React.MouseEvent<Element>) => void;
+ /**
+ * Show a loading indicator instead of the table, used for transaction summary p95.
+ */
+ forceLoading?: boolean;
};
class TransactionsList extends React.Component<Props> {
@@ -204,6 +208,7 @@ class TransactionsList extends React.Component<Props> {
titles,
generateLink,
baseline,
+ forceLoading,
} = this.props;
const sortedEventView = eventView.withSorts([selected.sort]);
const columnOrder = sortedEventView.getColumns();
@@ -243,6 +248,15 @@ class TransactionsList extends React.Component<Props> {
</React.Fragment>
);
+ if (forceLoading) {
+ return tableRenderer({
+ isLoading: true,
+ pageLinks: null,
+ tableData: null,
+ baselineData: null,
+ });
+ }
+
if (baselineTransactionName) {
const orgTableRenderer = tableRenderer;
tableRenderer = ({isLoading, pageLinks, tableData}) => (
diff --git a/src/sentry/static/sentry/app/views/performance/transactionSummary/charts.tsx b/src/sentry/static/sentry/app/views/performance/transactionSummary/charts.tsx
index 8f50501ba49e8f..654860da98bb55 100644
--- a/src/sentry/static/sentry/app/views/performance/transactionSummary/charts.tsx
+++ b/src/sentry/static/sentry/app/views/performance/transactionSummary/charts.tsx
@@ -11,6 +11,7 @@ import {
SectionValue,
} from 'app/components/charts/styles';
import {Panel} from 'app/components/panels';
+import Placeholder from 'app/components/placeholder';
import {t} from 'app/locale';
import {OrganizationSummary, SelectValue} from 'app/types';
import EventView from 'app/utils/discover/eventView';
@@ -193,7 +194,13 @@ class TransactionSummaryCharts extends React.Component<Props> {
<ChartControls>
<InlineContainer>
<SectionHeading key="total-heading">{t('Total Transactions')}</SectionHeading>
- <SectionValue key="total-value">{calculateTotal(totalValues)}</SectionValue>
+ <SectionValue key="total-value">
+ {totalValues === null ? (
+ <Placeholder height="24px" />
+ ) : (
+ totalValues.toLocaleString()
+ )}
+ </SectionValue>
</InlineContainer>
<InlineContainer>
{display === DisplayModes.TREND && (
@@ -225,11 +232,4 @@ class TransactionSummaryCharts extends React.Component<Props> {
}
}
-function calculateTotal(total: number | null) {
- if (total === null) {
- return '\u2014';
- }
- return total.toLocaleString();
-}
-
export default TransactionSummaryCharts;
diff --git a/src/sentry/static/sentry/app/views/performance/transactionSummary/content.tsx b/src/sentry/static/sentry/app/views/performance/transactionSummary/content.tsx
index 48f6e97c1405ed..771aea9df8d41f 100644
--- a/src/sentry/static/sentry/app/views/performance/transactionSummary/content.tsx
+++ b/src/sentry/static/sentry/app/views/performance/transactionSummary/content.tsx
@@ -45,7 +45,7 @@ type Props = {
eventView: EventView;
transactionName: string;
organization: Organization;
- totalValues: Record<string, number>;
+ totalValues: Record<string, number> | null;
projects: Project[];
};
@@ -157,21 +157,18 @@ class SummaryContent extends React.Component<Props, State> {
} = this.props;
const {incompatibleAlertNotice} = this.state;
const query = decodeScalar(location.query.query, '');
- const totalCount = totalValues.count;
- const slowDuration = totalValues?.p95;
+ const totalCount = totalValues === null ? null : totalValues.count;
// NOTE: This is not a robust check for whether or not a transaction is a front end
// transaction, however it will suffice for now.
- const hasWebVitals = VITAL_GROUPS.some(group =>
- group.vitals.some(vital => {
- const alias = getAggregateAlias(`percentile(${vital}, ${VITAL_PERCENTILE})`);
- return Number.isFinite(totalValues[alias]);
- })
- );
-
- const {selectedSort, sortOptions} = getTransactionsListSort(location, {
- p95: slowDuration,
- });
+ const hasWebVitals =
+ totalValues !== null &&
+ VITAL_GROUPS.some(group =>
+ group.vitals.some(vital => {
+ const alias = getAggregateAlias(`percentile(${vital}, ${VITAL_PERCENTILE})`);
+ return Number.isFinite(totalValues[alias]);
+ })
+ );
return (
<React.Fragment>
@@ -208,8 +205,6 @@ class SummaryContent extends React.Component<Props, State> {
location={location}
organization={organization}
eventView={eventView}
- selected={selectedSort}
- options={sortOptions}
titles={[t('id'), t('user'), t('duration'), t('timestamp')]}
handleDropdownChange={this.handleTransactionsListSortChange}
generateLink={{
@@ -219,6 +214,10 @@ class SummaryContent extends React.Component<Props, State> {
handleBaselineClick={this.handleViewDetailsClick}
handleCellAction={this.handleCellAction}
handleOpenInDiscoverClick={this.handleDiscoverViewClick}
+ {...getTransactionsListSort(location, {
+ p95: totalValues?.p95 ?? 0,
+ })}
+ forceLoading={!totalValues}
/>
<RelatedIssues
organization={organization}
@@ -297,14 +296,14 @@ function getFilterOptions({p95}: {p95: number}): DropdownOption[] {
function getTransactionsListSort(
location: Location,
options: {p95: number}
-): {selectedSort: DropdownOption; sortOptions: DropdownOption[]} {
+): {selected: DropdownOption; options: DropdownOption[]} {
const sortOptions = getFilterOptions(options);
const urlParam = decodeScalar(
location.query.showTransactions,
TransactionFilterOptions.SLOW
);
const selectedSort = sortOptions.find(opt => opt.value === urlParam) || sortOptions[0];
- return {selectedSort, sortOptions};
+ return {selected: selectedSort, options: sortOptions};
}
const StyledSearchBar = styled(SearchBar)`
diff --git a/src/sentry/static/sentry/app/views/performance/transactionSummary/index.tsx b/src/sentry/static/sentry/app/views/performance/transactionSummary/index.tsx
index b2073f9d113ff2..9f0b2e531ba87b 100644
--- a/src/sentry/static/sentry/app/views/performance/transactionSummary/index.tsx
+++ b/src/sentry/static/sentry/app/views/performance/transactionSummary/index.tsx
@@ -8,7 +8,6 @@ import isEqual from 'lodash/isEqual';
import {loadOrganizationTags} from 'app/actionCreators/tags';
import {Client} from 'app/api';
import LightWeightNoProjectMessage from 'app/components/lightWeightNoProjectMessage';
-import LoadingIndicator from 'app/components/loadingIndicator';
import GlobalSelectionHeader from 'app/components/organizations/globalSelectionHeader';
import SentryDocumentTitle from 'app/components/sentryDocumentTitle';
import {t} from 'app/locale';
@@ -16,12 +15,7 @@ import {PageContent} from 'app/styles/organization';
import {GlobalSelection, Organization, Project} from 'app/types';
import DiscoverQuery from 'app/utils/discover/discoverQuery';
import EventView from 'app/utils/discover/eventView';
-import {
- Column,
- getAggregateAlias,
- isAggregateField,
- WebVital,
-} from 'app/utils/discover/fields';
+import {Column, isAggregateField, WebVital} from 'app/utils/discover/fields';
import {decodeScalar} from 'app/utils/queryString';
import {stringifyQueryObject, tokenizeSearch} from 'app/utils/tokenizeSearch';
import withApi from 'app/utils/withApi';
@@ -103,10 +97,7 @@ class TransactionSummary extends React.Component<Props, State> {
return [t('Summary'), t('Performance')].join(' - ');
}
- getTotalsEventView(
- organization: Organization,
- eventView: EventView
- ): [EventView, TotalValues] {
+ getTotalsEventView(organization: Organization, eventView: EventView): EventView {
const threshold = organization.apdexThreshold.toString();
const vitals = VITAL_GROUPS.map(({vitals: vs}) => vs).reduce(
@@ -117,7 +108,7 @@ class TransactionSummary extends React.Component<Props, State> {
[]
);
- const totalsView = eventView.withColumns([
+ return eventView.withColumns([
{
kind: 'function',
function: ['apdex', threshold, undefined],
@@ -146,11 +137,6 @@ class TransactionSummary extends React.Component<Props, State> {
} as Column)
),
]);
- const emptyValues = totalsView.fields.reduce((values, field) => {
- values[getAggregateAlias(field.field)] = 0;
- return values;
- }, {});
- return [totalsView, emptyValues];
}
render() {
@@ -168,7 +154,7 @@ class TransactionSummary extends React.Component<Props, State> {
});
return null;
}
- const [totalsView, emptyValues] = this.getTotalsEventView(organization, eventView);
+ const totalsView = this.getTotalsEventView(organization, eventView);
const shouldForceProject = eventView.project.length === 1;
const forceProject = shouldForceProject
@@ -196,13 +182,10 @@ class TransactionSummary extends React.Component<Props, State> {
orgSlug={organization.slug}
location={location}
>
- {({tableData, isLoading}) => {
- if (isLoading) {
- return <LoadingIndicator />;
- }
+ {({tableData}) => {
const totals = (tableData && tableData.data.length
? tableData.data[0]
- : emptyValues) as TotalValues;
+ : null) as TotalValues | null;
return (
<SummaryContent
location={location}
diff --git a/src/sentry/static/sentry/app/views/performance/transactionSummary/userStats.tsx b/src/sentry/static/sentry/app/views/performance/transactionSummary/userStats.tsx
index bef8470961da7d..b084737f51e6eb 100644
--- a/src/sentry/static/sentry/app/views/performance/transactionSummary/userStats.tsx
+++ b/src/sentry/static/sentry/app/views/performance/transactionSummary/userStats.tsx
@@ -5,6 +5,7 @@ import {Location} from 'history';
import Feature from 'app/components/acl/feature';
import {SectionHeading} from 'app/components/charts/styles';
import Link from 'app/components/links/link';
+import Placeholder from 'app/components/placeholder';
import QuestionTooltip from 'app/components/questionTooltip';
import UserMisery from 'app/components/userMisery';
import {IconOpen} from 'app/icons';
@@ -27,16 +28,16 @@ import VitalInfo from '../vitalDetail/vitalInfo';
type Props = {
eventView: EventView;
- totals: Record<string, number>;
+ totals: Record<string, number> | null;
location: Location;
organization: Organization;
transactionName: string;
};
function UserStats({eventView, totals, location, organization, transactionName}: Props) {
- let userMisery = <StatNumber>{'\u2014'}</StatNumber>;
+ let userMisery = <Placeholder height="34px" />;
const threshold = organization.apdexThreshold;
- let apdex: React.ReactNode = <StatNumber>{'\u2014'}</StatNumber>;
+ let apdex: React.ReactNode = <Placeholder height="24px" />;
let vitalsPassRate: React.ReactNode = null;
if (totals) {
diff --git a/tests/js/spec/components/discover/transactionsList.spec.jsx b/tests/js/spec/components/discover/transactionsList.spec.jsx
index 3cb774b91d953b..bed6b916beb358 100644
--- a/tests/js/spec/components/discover/transactionsList.spec.jsx
+++ b/tests/js/spec/components/discover/transactionsList.spec.jsx
@@ -301,6 +301,38 @@ describe('TransactionsList', function () {
})
);
});
+
+ it('handles forceLoading correctly', async function () {
+ wrapper = mountWithTheme(
+ <TransactionsList
+ api={null}
+ location={location}
+ organization={organization}
+ eventView={eventView}
+ selected={options[0]}
+ options={options}
+ handleDropdownChange={handleDropdownChange}
+ forceLoading
+ />
+ );
+
+ expect(wrapper.find('LoadingIndicator')).toHaveLength(1);
+ wrapper.setProps({api, forceLoading: false});
+
+ await tick();
+ wrapper.update();
+
+ expect(wrapper.find('LoadingIndicator')).toHaveLength(0);
+ expect(wrapper.find('DropdownControl')).toHaveLength(1);
+ expect(wrapper.find('DropdownItem')).toHaveLength(2);
+ expect(wrapper.find('DiscoverButton')).toHaveLength(1);
+ expect(wrapper.find('Pagination')).toHaveLength(1);
+ expect(wrapper.find('PanelTable')).toHaveLength(1);
+ // 2 for the transaction names
+ expect(wrapper.find('GridCell')).toHaveLength(2);
+ // 2 for the counts
+ expect(wrapper.find('GridCellNumber')).toHaveLength(2);
+ });
});
describe('Baseline', function () {
|
4b54b4e286cec03905b6aea049dd1e60dd2659cf
|
2024-02-21 23:21:17
|
Josh Ferge
|
fix(feedback): better metrics in create_feedback (#65494)
| false
|
better metrics in create_feedback (#65494)
|
fix
|
diff --git a/src/sentry/feedback/usecases/create_feedback.py b/src/sentry/feedback/usecases/create_feedback.py
index adfe8831a83be7..b650c7905aa103 100644
--- a/src/sentry/feedback/usecases/create_feedback.py
+++ b/src/sentry/feedback/usecases/create_feedback.py
@@ -125,25 +125,32 @@ def should_filter_feedback(event, project_id, source: FeedbackCreationSource):
or event["contexts"].get("feedback") is None
or event["contexts"]["feedback"].get("message") is None
):
- metrics.incr("feedback.filtered", tags={"reason": "missing_context"}, sample_rate=1.0)
+ metrics.incr(
+ "feedback.create_feedback_issue.filtered",
+ tags={"reason": "missing_context"},
+ )
return True
if event["contexts"]["feedback"]["message"] == UNREAL_FEEDBACK_UNATTENDED_MESSAGE:
- metrics.incr("feedback.filtered", tags={"reason": "unreal.unattended"}, sample_rate=1.0)
+ metrics.incr(
+ "feedback.create_feedback_issue.filtered",
+ tags={"reason": "unreal.unattended"},
+ )
return True
if event["contexts"]["feedback"]["message"].strip() == "":
- metrics.incr("feedback.filtered", tags={"reason": "empty"}, sample_rate=1.0)
+ metrics.incr("feedback.create_feedback_issue.filtered", tags={"reason": "empty"})
return True
return False
def create_feedback_issue(event, project_id, source: FeedbackCreationSource):
+ metrics.incr("feedback.create_feedback_issue.entered")
+
if should_filter_feedback(event, project_id, source):
return
- metrics.incr("feedback.created", tags={"referrer": source.value}, sample_rate=1.0)
# Note that some of the fields below like title and subtitle
# are not used by the feedback UI, but are required.
event["event_id"] = event.get("event_id") or uuid4().hex
@@ -197,7 +204,11 @@ def create_feedback_issue(event, project_id, source: FeedbackCreationSource):
produce_occurrence_to_kafka(
payload_type=PayloadType.OCCURRENCE, occurrence=occurrence, event_data=event_fixed
)
-
+ metrics.incr(
+ "feedback.create_feedback_issue.produced_occurrence",
+ tags={"referrer": source.value},
+ sample_rate=1.0,
+ )
track_outcome(
org_id=project.organization_id,
project_id=project_id,
@@ -219,7 +230,11 @@ def validate_issue_platform_event_schema(event_data):
try:
jsonschema.validate(event_data, EVENT_PAYLOAD_SCHEMA)
except jsonschema.exceptions.ValidationError:
- jsonschema.validate(event_data, LEGACY_EVENT_PAYLOAD_SCHEMA)
+ try:
+ jsonschema.validate(event_data, LEGACY_EVENT_PAYLOAD_SCHEMA)
+ except jsonschema.exceptions.ValidationError:
+ metrics.incr("feedback.create_feedback_issue.invalid_schema")
+ raise
class UserReportShimDict(TypedDict):
|
61f0f3ef082b9f148eceaf950daa1a59ff736a59
|
2024-12-31 00:00:28
|
anthony sottile
|
ref: add more modules to the mypy stronglist (#82664)
| false
|
add more modules to the mypy stronglist (#82664)
|
ref
|
diff --git a/pyproject.toml b/pyproject.toml
index 35e10994f44637..0e08cd5e45ddd2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -345,13 +345,22 @@ disable_error_code = [
# begin: stronger typing
[[tool.mypy.overrides]]
module = [
+ "fixtures.safe_migrations_apps.*",
+ "sentry.analytics.*",
+ "sentry.api.endpoints.integrations.sentry_apps.installation.external_issue.*",
"sentry.api.endpoints.project_backfill_similar_issues_embeddings_records",
+ "sentry.api.endpoints.release_thresholds.health_checks.*",
+ "sentry.api.endpoints.relocations.artifacts.*",
"sentry.api.helpers.deprecation",
"sentry.api.helpers.source_map_helper",
+ "sentry.api.serializers.models.organization_member.*",
+ "sentry.audit_log.services.*",
"sentry.auth.services.*",
"sentry.auth.view",
"sentry.buffer.*",
"sentry.build.*",
+ "sentry.data_secrecy.models.*",
+ "sentry.data_secrecy.service.*",
"sentry.db.models.fields.citext",
"sentry.db.models.fields.foreignkey",
"sentry.db.models.fields.hybrid_cloud_foreign_key",
@@ -360,21 +369,56 @@ module = [
"sentry.db.models.paranoia",
"sentry.db.models.utils",
"sentry.deletions.*",
+ "sentry.digests.*",
"sentry.digests.notifications",
+ "sentry.dynamic_sampling.models.*",
+ "sentry.dynamic_sampling.rules.biases.*",
+ "sentry.dynamic_sampling.rules.combinators.*",
+ "sentry.dynamic_sampling.rules.helpers.*",
+ "sentry.dynamic_sampling.tasks.helpers.*",
+ "sentry.eventstore.reprocessing.*",
"sentry.eventstore.reprocessing.redis",
+ "sentry.eventstream.*",
"sentry.eventtypes.error",
+ "sentry.feedback.migrations.*",
+ "sentry.flags.migrations.*",
"sentry.grouping.api",
"sentry.grouping.component",
"sentry.grouping.fingerprinting",
+ "sentry.grouping.fingerprinting.*",
"sentry.grouping.grouping_info",
"sentry.grouping.ingest.*",
"sentry.grouping.parameterization",
"sentry.grouping.utils",
"sentry.grouping.variants",
"sentry.hybridcloud.*",
+ "sentry.identity.discord.*",
"sentry.identity.github_enterprise.*",
+ "sentry.identity.services.*",
+ "sentry.identity.vsts_extension.*",
+ "sentry.incidents.utils.*",
"sentry.ingest.slicing",
+ "sentry.integrations.discord.actions.*",
+ "sentry.integrations.discord.message_builder.base.component.*",
+ "sentry.integrations.discord.message_builder.base.embed.*",
+ "sentry.integrations.discord.utils.*",
+ "sentry.integrations.discord.views.*",
+ "sentry.integrations.discord.webhooks.*",
+ "sentry.integrations.github.actions.*",
+ "sentry.integrations.github_enterprise.actions.*",
+ "sentry.integrations.jira.endpoints.*",
+ "sentry.integrations.jira.models.*",
+ "sentry.integrations.jira_server.actions.*",
+ "sentry.integrations.jira_server.utils.*",
"sentry.integrations.models.integration_feature",
+ "sentry.integrations.project_management.*",
+ "sentry.integrations.repository.*",
+ "sentry.integrations.services.*",
+ "sentry.integrations.slack.threads.*",
+ "sentry.integrations.slack.views.*",
+ "sentry.integrations.vsts.actions.*",
+ "sentry.integrations.vsts.tasks.*",
+ "sentry.integrations.web.debug.*",
"sentry.issues",
"sentry.issues.analytics",
"sentry.issues.apps",
@@ -431,27 +475,55 @@ module = [
"sentry.models.event",
"sentry.models.eventattachment",
"sentry.models.groupsubscription",
- "sentry.monkey",
+ "sentry.models.options.*",
+ "sentry.monkey.*",
+ "sentry.nodestore.*",
"sentry.nodestore.base",
"sentry.nodestore.bigtable.backend",
"sentry.nodestore.django.backend",
"sentry.nodestore.django.models",
"sentry.nodestore.filesystem.backend",
"sentry.nodestore.models",
+ "sentry.notifications.services.*",
"sentry.organizations.*",
"sentry.ownership.*",
"sentry.plugins.base.response",
"sentry.plugins.base.view",
+ "sentry.plugins.validators.*",
+ "sentry.post_process_forwarder.*",
"sentry.profiles.*",
- "sentry.projects.services.*",
+ "sentry.projects.*",
+ "sentry.queue.*",
"sentry.ratelimits.leaky_bucket",
"sentry.relay.config.metric_extraction",
+ "sentry.relay.types.*",
+ "sentry.release_health.release_monitor.*",
+ "sentry.relocation.services.relocation_export.*",
+ "sentry.remote_subscriptions.migrations.*",
+ "sentry.replays.consumers.*",
+ "sentry.replays.lib.new_query.*",
+ "sentry.replays.migrations.*",
"sentry.reprocessing2",
+ "sentry.roles.*",
+ "sentry.rules.actions.sentry_apps.*",
+ "sentry.rules.conditions.*",
+ "sentry.rules.history.endpoints.*",
"sentry.runner.*",
"sentry.search.snuba.backend",
- "sentry.seer.similarity.utils",
- "sentry.sentry_metrics.consumers.indexer.slicing_router",
+ "sentry.security.*",
+ "sentry.seer.similarity.*",
+ "sentry.sentry_apps.external_issues.*",
+ "sentry.sentry_apps.services.*",
+ "sentry.sentry_apps.utils.*",
+ "sentry.sentry_apps.web.*",
+ "sentry.sentry_metrics.consumers.indexer.*",
+ "sentry.sentry_metrics.indexer.limiters.*",
+ "sentry.shared_integrations.exceptions.*",
+ "sentry.slug.*",
"sentry.snuba.metrics.extraction",
+ "sentry.snuba.metrics.naming_layer.*",
+ "sentry.snuba.query_subscriptions.*",
+ "sentry.spans.grouping.*",
"sentry.stacktraces.platform",
"sentry.tasks.beacon",
"sentry.tasks.commit_context",
@@ -460,10 +532,15 @@ module = [
"sentry.tasks.reprocessing2",
"sentry.tasks.store",
"sentry.taskworker.*",
+ "sentry.tempest.endpoints.*",
+ "sentry.tempest.migrations.*",
"sentry.testutils.helpers.task_runner",
"sentry.testutils.skips",
- "sentry.types.actor",
- "sentry.types.region",
+ "sentry.toolbar.utils.*",
+ "sentry.trash.*",
+ "sentry.types.*",
+ "sentry.uptime.migrations.*",
+ "sentry.usage_accountant.*",
"sentry.users.*",
"sentry.utils.arroyo",
"sentry.utils.assets",
@@ -480,6 +557,7 @@ module = [
"sentry.utils.imports",
"sentry.utils.iterators",
"sentry.utils.javascript",
+ "sentry.utils.kvstore.*",
"sentry.utils.lazy_service_wrapper",
"sentry.utils.locking.*",
"sentry.utils.migrations",
@@ -490,6 +568,7 @@ module = [
"sentry.utils.pubsub",
"sentry.utils.redis",
"sentry.utils.redis_metrics",
+ "sentry.utils.sdk_crashes.*",
"sentry.utils.sentry_apps.*",
"sentry.utils.services",
"sentry.utils.sms",
@@ -500,12 +579,24 @@ module = [
"sentry.web.frontend.auth_provider_login",
"sentry.web.frontend.cli",
"sentry.web.frontend.csv",
+ "sentry.web.frontend.mixins.*",
+ "sentry.workflow_engine.handlers.action.*",
+ "sentry.workflow_engine.handlers.condition.*",
+ "sentry.workflow_engine.migrations.*",
"sentry_plugins.base",
+ "social_auth.migrations.*",
+ "sudo.*",
+ "tests.sentry.audit_log.services.*",
"tests.sentry.deletions.test_group",
"tests.sentry.event_manager.test_event_manager",
"tests.sentry.grouping.ingest.test_seer",
"tests.sentry.grouping.test_fingerprinting",
"tests.sentry.hybridcloud.*",
+ "tests.sentry.incidents.serializers.*",
+ "tests.sentry.integrations.msteams.webhook.*",
+ "tests.sentry.integrations.repository.base.*",
+ "tests.sentry.integrations.repository.issue_alert.*",
+ "tests.sentry.integrations.slack.threads.*",
"tests.sentry.issues",
"tests.sentry.issues.endpoints",
"tests.sentry.issues.endpoints.test_actionable_items",
@@ -549,12 +640,25 @@ module = [
"tests.sentry.issues.test_status_change",
"tests.sentry.issues.test_status_change_consumer",
"tests.sentry.issues.test_update_inbox",
+ "tests.sentry.organizations.*",
"tests.sentry.ownership.*",
+ "tests.sentry.post_process_forwarder.*",
+ "tests.sentry.profiling.*",
+ "tests.sentry.queue.*",
"tests.sentry.ratelimits.test_leaky_bucket",
"tests.sentry.relay.config.test_metric_extraction",
+ "tests.sentry.replays.unit.lib.*",
+ "tests.sentry.rules.actions.base.*",
+ "tests.sentry.security.*",
+ "tests.sentry.snuba.metrics.test_metrics_query_layer.*",
+ "tests.sentry.tasks.integrations.*",
"tests.sentry.tasks.test_on_demand_metrics",
+ "tests.sentry.types.*",
"tests.sentry.types.test_actor",
"tests.sentry.types.test_region",
+ "tests.sentry.usage_accountant.*",
+ "tests.sentry.users.services.*",
+ "tests.sentry.utils.mockdata.*",
"tests.sentry.web.frontend.test_cli",
"tools.*",
]
|
47b1205f78e0efd32b56b6ac60ea4a6b0b805204
|
2022-01-06 03:51:48
|
Ryan Skonnord
|
ref(auth): Explicitly capture arbitrary user choice (#30940)
| false
|
Explicitly capture arbitrary user choice (#30940)
|
ref
|
diff --git a/src/sentry/auth/email.py b/src/sentry/auth/email.py
index b3d7e357824e23..1f09e20bf4f9e7 100644
--- a/src/sentry/auth/email.py
+++ b/src/sentry/auth/email.py
@@ -17,9 +17,11 @@ def resolve_email_to_user(email: str) -> Optional[User]:
if len(candidate_users) == 1:
return candidate_users[0]
+ arbitrary_choice = candidate_users[0]
with sentry_sdk.push_scope() as scope:
scope.level = "warning"
scope.set_tag("email", email)
scope.set_extra("user_ids", sorted(user.id for user in candidate_users))
+ scope.set_extra("chosen_user", arbitrary_choice.id)
sentry_sdk.capture_message("Ambiguous email resolution")
- return candidate_users[0]
+ return arbitrary_choice
|
5ca6f993eb0478825c7fc104a264235263303ca0
|
2024-02-29 19:57:54
|
ArthurKnaus
|
fix(ddm): Operation disabled state (#66058)
| false
|
Operation disabled state (#66058)
|
fix
|
diff --git a/static/app/views/ddm/queryBuilder.tsx b/static/app/views/ddm/queryBuilder.tsx
index 7e144991f88fa3..8d6e923ec56f73 100644
--- a/static/app/views/ddm/queryBuilder.tsx
+++ b/static/app/views/ddm/queryBuilder.tsx
@@ -196,8 +196,6 @@ export const QueryBuilder = memo(function QueryBuilder({
breakpoints.large ? (breakpoints.xlarge ? 70 : 45) : 30,
/\.|-|_/
)}
- // TODO(TS): Is this used anywhere?
- aria-placeholder={t('Select a metric')}
options={mriOptions}
value={metricsQuery.mri}
onChange={handleMRIChange}
@@ -213,7 +211,8 @@ export const QueryBuilder = memo(function QueryBuilder({
value: op,
})) ?? []
}
- disabled={!metricsQuery.mri}
+ triggerLabel={metricsQuery.op}
+ disabled={!selectedMeta}
value={metricsQuery.op}
onChange={handleOpChange}
/>
|
27658b8368274e12a0d9b74d4a4276957d71f58b
|
2024-04-03 23:55:59
|
Snigdha Sharma
|
fix(severity): Update default rate limits (#68188)
| false
|
Update default rate limits (#68188)
|
fix
|
diff --git a/src/sentry/event_manager.py b/src/sentry/event_manager.py
index b8c4213e8a9126..f26b3826452f43 100644
--- a/src/sentry/event_manager.py
+++ b/src/sentry/event_manager.py
@@ -146,8 +146,6 @@
HIGH_SEVERITY_THRESHOLD = 0.1
-SEER_GLOBAL_RATE_LIMIT_DEFAULT = 20 # 20 requests per second
-SEER_PROJECT_RATE_LIMIT_DEFAULT = 5 # 5 requests per second
SEER_ERROR_COUNT_KEY = ERROR_COUNT_CACHE_KEY("sentry.seer.severity-failures")
@@ -2212,25 +2210,39 @@ def _get_severity_metadata_for_group(
from sentry import ratelimits as ratelimiter
- limit = options.get("issues.severity.seer-global-rate-limit", SEER_GLOBAL_RATE_LIMIT_DEFAULT)
+ ratelimit = options.get("issues.severity.seer-global-rate-limit")
+ # This is temporary until we update the option values to be a dict
+ if "limit" not in ratelimit or "window" not in ratelimit:
+ return {}
+
if ratelimiter.backend.is_limited(
- "seer:severity-calculation:global-limit", limit=limit, window=1
+ "seer:severity-calculation:global-limit",
+ limit=ratelimit["limit"],
+ window=ratelimit["window"],
):
logger.warning(
"get_severity_metadata_for_group.rate_limited_globally",
extra={"event_id": event.event_id, "project_id": project_id},
)
metrics.incr("issues.severity.rate_limited_globally")
+ return {}
+
+ ratelimit = options.get("issues.severity.seer-project-rate-limit")
+ # This is temporary until we update the option values to be a dict
+ if "limit" not in ratelimit or "window" not in ratelimit:
+ return {}
- limit = options.get("issues.severity.seer-project-rate-limit", SEER_PROJECT_RATE_LIMIT_DEFAULT)
if ratelimiter.backend.is_limited(
- f"seer:severity-calculation:{project_id}", limit=limit, window=1
+ f"seer:severity-calculation:{project_id}",
+ limit=ratelimit["limit"],
+ window=ratelimit["window"],
):
logger.warning(
"get_severity_metadata_for_group.rate_limited_for_project",
extra={"event_id": event.event_id, "project_id": project_id},
)
metrics.incr("issues.severity.rate_limited_for_project", tags={"project_id": project_id})
+ return {}
try:
severity, reason = _get_severity_score(event)
diff --git a/src/sentry/options/defaults.py b/src/sentry/options/defaults.py
index 4ab49ebad75c26..9291291609a36b 100644
--- a/src/sentry/options/defaults.py
+++ b/src/sentry/options/defaults.py
@@ -779,15 +779,15 @@
register(
"issues.severity.seer-project-rate-limit",
- type=Int,
- default=5,
+ type=Any,
+ default={"limit": 5, "window": 1},
flags=FLAG_ALLOW_EMPTY | FLAG_AUTOMATOR_MODIFIABLE,
)
register(
"issues.severity.seer-global-rate-limit",
- type=Int,
- default=25,
+ type=Any,
+ default={"limit": 20, "window": 1},
flags=FLAG_ALLOW_EMPTY | FLAG_AUTOMATOR_MODIFIABLE,
)
|
a15a37e760c6e620ad58850ca148db540559a426
|
2021-03-16 00:57:53
|
Chris Fuller
|
feat(workflow): Issue rule owner support (#24100)
| false
|
Issue rule owner support (#24100)
|
feat
|
diff --git a/src/sentry/api/endpoints/project_rule_details.py b/src/sentry/api/endpoints/project_rule_details.py
index fb4146bda8c590..47c08606df6d75 100644
--- a/src/sentry/api/endpoints/project_rule_details.py
+++ b/src/sentry/api/endpoints/project_rule_details.py
@@ -7,7 +7,15 @@
from sentry.api.serializers.rest_framework.rule import RuleSerializer
from sentry.integrations.slack import tasks
from sentry.mediators import project_rules
-from sentry.models import AuditLogEntryEvent, Rule, RuleActivity, RuleActivityType, RuleStatus
+from sentry.models import (
+ AuditLogEntryEvent,
+ Rule,
+ RuleActivity,
+ RuleActivityType,
+ RuleStatus,
+ Team,
+ User,
+)
from sentry.web.decorators import transaction_start
@@ -82,6 +90,15 @@ def put(self, request, project, rule):
"actions": data["actions"],
"frequency": data.get("frequency"),
}
+ owner = data.get("owner")
+ if owner:
+ try:
+ kwargs["owner"] = owner.resolve_to_actor().id
+ except (User.DoesNotExist, Team.DoesNotExist):
+ return Response(
+ "Could not resolve owner",
+ status=status.HTTP_400_BAD_REQUEST,
+ )
if data.get("pending_save"):
client = tasks.RedisRuleStatus()
diff --git a/src/sentry/api/endpoints/project_rules.py b/src/sentry/api/endpoints/project_rules.py
index bbe18e4e015e45..c42284f3a6e9a8 100644
--- a/src/sentry/api/endpoints/project_rules.py
+++ b/src/sentry/api/endpoints/project_rules.py
@@ -6,7 +6,15 @@
from sentry.api.serializers.rest_framework import RuleSerializer
from sentry.integrations.slack import tasks
from sentry.mediators import project_rules
-from sentry.models import AuditLogEntryEvent, Rule, RuleActivity, RuleActivityType, RuleStatus
+from sentry.models import (
+ AuditLogEntryEvent,
+ Rule,
+ RuleActivity,
+ RuleActivityType,
+ RuleStatus,
+ Team,
+ User,
+)
from sentry.signals import alert_rule_created
from sentry.web.decorators import transaction_start
@@ -45,6 +53,7 @@ def post(self, request, project):
{method} {path}
{{
"name": "My rule name",
+ "owner": "type:id",
"conditions": [],
"filters": [],
"actions": [],
@@ -57,7 +66,6 @@ def post(self, request, project):
if serializer.is_valid():
data = serializer.validated_data
-
# combine filters and conditions into one conditions criteria for the rule object
conditions = data.get("conditions", [])
if "filters" in data:
@@ -74,6 +82,15 @@ def post(self, request, project):
"frequency": data.get("frequency"),
"user_id": request.user.id,
}
+ owner = data.get("owner")
+ if owner:
+ try:
+ kwargs["owner"] = owner.resolve_to_actor().id
+ except (User.DoesNotExist, Team.DoesNotExist):
+ return Response(
+ "Could not resolve owner",
+ status=status.HTTP_400_BAD_REQUEST,
+ )
if data.get("pending_save"):
client = tasks.RedisRuleStatus()
diff --git a/src/sentry/api/serializers/models/rule.py b/src/sentry/api/serializers/models/rule.py
index 9bcfe62213430d..bc3c217de3cd92 100644
--- a/src/sentry/api/serializers/models/rule.py
+++ b/src/sentry/api/serializers/models/rule.py
@@ -1,5 +1,14 @@
+from collections import defaultdict
from sentry.api.serializers import Serializer, register
-from sentry.models import Environment, Rule, RuleActivity, RuleActivityType
+from sentry.models import (
+ ACTOR_TYPES,
+ actor_type_to_class,
+ actor_type_to_string,
+ Environment,
+ Rule,
+ RuleActivity,
+ RuleActivityType,
+)
from sentry.utils.compat import filter
@@ -43,6 +52,23 @@ def get_attrs(self, item_list, user, **kwargs):
result[rule_activity.rule].update({"created_by": user})
+ rules = {item.id: item for item in item_list}
+ resolved_actors = {}
+ owners_by_type = defaultdict(list)
+ for item in item_list:
+ if item.owner_id is not None:
+ owners_by_type[actor_type_to_string(item.owner.type)].append(item.owner_id)
+
+ for k, v in ACTOR_TYPES.items():
+ resolved_actors[k] = {
+ a.actor_id: a.id
+ for a in actor_type_to_class(v).objects.filter(actor_id__in=owners_by_type[k])
+ }
+ for rule in rules.values():
+ if rule.owner_id:
+ type = actor_type_to_string(rule.owner.type)
+ result[rule]["owner"] = f"{type}:{resolved_actors[type][rule.owner_id]}"
+
return result
def serialize(self, obj, attrs, user):
@@ -69,6 +95,7 @@ def serialize(self, obj, attrs, user):
"frequency": obj.data.get("frequency") or Rule.DEFAULT_FREQUENCY,
"name": obj.label,
"dateCreated": obj.date_added,
+ "owner": attrs.get("owner", None),
"createdBy": attrs.get("created_by", None),
"environment": environment.name if environment is not None else None,
"projects": [obj.project.slug],
diff --git a/src/sentry/api/serializers/rest_framework/rule.py b/src/sentry/api/serializers/rest_framework/rule.py
index 4264fc0e56036e..83af5273e7c353 100644
--- a/src/sentry/api/serializers/rest_framework/rule.py
+++ b/src/sentry/api/serializers/rest_framework/rule.py
@@ -2,7 +2,7 @@
from sentry import features
from sentry.constants import MIGRATED_CONDITIONS, TICKET_ACTIONS
-from sentry.models import Environment
+from sentry.models import ActorTuple, Environment, Team, User
from sentry.rules import rules
from . import ListField
@@ -70,6 +70,22 @@ class RuleSerializer(serializers.Serializer):
conditions = ListField(child=RuleNodeField(type="condition/event"), required=False)
filters = ListField(child=RuleNodeField(type="filter/event"), required=False)
frequency = serializers.IntegerField(min_value=5, max_value=60 * 24 * 30)
+ owner = serializers.CharField(required=False)
+
+ def validate_owner(self, owner):
+ # owner_id should be team:id or user:id
+ try:
+ actor = ActorTuple.from_actor_identifier(owner)
+ except Exception:
+ raise serializers.ValidationError(
+ "Could not parse owner. Format should be `type:id` where type is `team` or `user`."
+ )
+
+ try:
+ if actor.resolve():
+ return actor
+ except (User.DoesNotExist, Team.DoesNotExist):
+ raise serializers.ValidationError("Could not resolve owner to existing team or user.")
def validate_environment(self, environment):
if environment is None:
@@ -156,5 +172,7 @@ def save(self, rule):
rule.data["conditions"] = self.validated_data["conditions"]
if self.validated_data.get("frequency"):
rule.data["frequency"] = self.validated_data["frequency"]
+ if self.validated_data.get("owner"):
+ rule.owner = self.validated_data["owner"].resolve_to_actor()
rule.save()
return rule
diff --git a/src/sentry/mediators/project_rules/creator.py b/src/sentry/mediators/project_rules/creator.py
index c561a30c38d4d5..a282cff9c6d0c2 100644
--- a/src/sentry/mediators/project_rules/creator.py
+++ b/src/sentry/mediators/project_rules/creator.py
@@ -1,11 +1,12 @@
from collections import Iterable
from sentry.mediators import Mediator, Param
-from sentry.models import Rule
+from sentry.models import Actor, Rule
class Creator(Mediator):
name = Param((str,))
environment = Param(int, required=False)
+ owner = Param("sentry.models.Actor", required=False)
project = Param("sentry.models.Project")
action_match = Param((str,))
filter_match = Param((str,), required=False)
@@ -33,6 +34,7 @@ def _get_kwargs(self):
}
_kwargs = {
"label": self.name,
+ "owner": Actor.objects.get(id=self.owner) if self.owner else None,
"environment_id": self.environment or None,
"project": self.project,
"data": data,
diff --git a/src/sentry/mediators/project_rules/updater.py b/src/sentry/mediators/project_rules/updater.py
index 3f8ed5cd2e5a5f..7bac1975bd40a5 100644
--- a/src/sentry/mediators/project_rules/updater.py
+++ b/src/sentry/mediators/project_rules/updater.py
@@ -1,11 +1,13 @@
from collections import Iterable
from sentry.mediators import Mediator, Param
from sentry.mediators.param import if_param
+from sentry.models import Actor
class Updater(Mediator):
rule = Param("sentry.models.Rule")
name = Param((str,), required=False)
+ owner = Param("sentry.models.Actor", required=False)
environment = Param(int, required=False)
project = Param("sentry.models.Project")
action_match = Param((str,), required=False)
@@ -17,6 +19,7 @@ class Updater(Mediator):
def call(self):
self._update_name()
+ self._update_owner()
self._update_environment()
self._update_project()
self._update_actions()
@@ -31,6 +34,9 @@ def call(self):
def _update_name(self):
self.rule.label = self.name
+ def _update_owner(self):
+ self.rule.owner = Actor.objects.get(id=self.owner) if self.owner else None
+
def _update_environment(self):
# environment can be None so we don't use the if_param decorator
self.rule.environment_id = self.environment
diff --git a/tests/sentry/api/endpoints/test_project_rule_details.py b/tests/sentry/api/endpoints/test_project_rule_details.py
index f5190d900f3c27..6898c2d133d2da 100644
--- a/tests/sentry/api/endpoints/test_project_rule_details.py
+++ b/tests/sentry/api/endpoints/test_project_rule_details.py
@@ -167,6 +167,7 @@ def test_simple(self):
url,
data={
"name": "hello world",
+ "owner": self.user.id,
"actionMatch": "any",
"filterMatch": "any",
"actions": [{"id": "sentry.rules.actions.notify_event.NotifyEventAction"}],
@@ -180,6 +181,7 @@ def test_simple(self):
rule = Rule.objects.get(id=rule.id)
assert rule.label == "hello world"
+ assert rule.owner == self.user.actor
assert rule.environment_id is None
assert rule.data["action_match"] == "any"
assert rule.data["filter_match"] == "any"
diff --git a/tests/sentry/api/endpoints/test_project_rules.py b/tests/sentry/api/endpoints/test_project_rules.py
index e3b4d23152a5f3..47697f4b6f9efc 100644
--- a/tests/sentry/api/endpoints/test_project_rules.py
+++ b/tests/sentry/api/endpoints/test_project_rules.py
@@ -44,6 +44,7 @@ def test_simple(self):
url,
data={
"name": "hello world",
+ "owner": self.user.actor.get_actor_identifier(),
"actionMatch": "any",
"filterMatch": "any",
"actions": actions,
@@ -55,6 +56,7 @@ def test_simple(self):
assert response.status_code == 200, response.content
assert response.data["id"]
+ assert response.data["owner"] == self.user.actor.get_actor_identifier()
assert response.data["createdBy"] == {
"id": self.user.id,
"name": self.user.get_display_name(),
@@ -63,6 +65,7 @@ def test_simple(self):
rule = Rule.objects.get(id=response.data["id"])
assert rule.label == "hello world"
+ assert rule.owner == self.user.actor
assert rule.data["action_match"] == "any"
assert rule.data["filter_match"] == "any"
assert rule.data["actions"] == actions
@@ -128,6 +131,7 @@ def test_with_null_environment(self):
url,
data={
"name": "hello world",
+ "owner": f"user:{self.user.id}",
"environment": None,
"conditions": conditions,
"actions": actions,
@@ -166,6 +170,7 @@ def test_slack_channel_id_saved(self):
url,
data={
"name": "hello world",
+ "owner": f"user:{self.user.id}",
"environment": None,
"actionMatch": "any",
"frequency": 5,
@@ -204,6 +209,7 @@ def test_missing_name(self):
response = self.client.post(
url,
data={
+ "owner": f"user:{self.user.id}",
"actionMatch": "any",
"filterMatch": "any",
"actions": actions,
@@ -237,6 +243,7 @@ def test_match_values(self):
url,
data={
"name": "hello world",
+ "owner": f"user:{self.user.id}",
"actionMatch": "any",
"filterMatch": "any",
"actions": actions,
@@ -261,6 +268,7 @@ def test_match_values(self):
url,
data={
"name": "hello world",
+ "owner": f"user:{self.user.id}",
"actionMatch": "any",
"filterMatch": "any",
"actions": actions,
@@ -291,6 +299,7 @@ def test_with_filters(self):
url,
data={
"name": "hello world",
+ "owner": f"user:{self.user.id}",
"conditions": conditions,
"filters": filters,
"actions": actions,
@@ -325,6 +334,7 @@ def test_with_no_filter_match(self):
url,
data={
"name": "hello world",
+ "owner": f"user:{self.user.id}",
"conditions": conditions,
"actions": actions,
"actionMatch": "any",
@@ -358,6 +368,7 @@ def test_with_filters_without_match(self):
url,
data={
"name": "hello world",
+ "owner": f"user:{self.user.id}",
"conditions": conditions,
"filters": filters,
"actions": actions,
@@ -387,6 +398,7 @@ def test_no_actions(self):
url,
data={
"name": "no action rule",
+ "owner": f"user:{self.user.id}",
"actionMatch": "any",
"filterMatch": "any",
"conditions": conditions,
@@ -450,6 +462,7 @@ class uuid:
)
data = {
"name": "hello world",
+ "owner": f"user:{self.user.id}",
"environment": None,
"actionMatch": "any",
"frequency": 5,
@@ -475,6 +488,7 @@ class uuid:
assert not Rule.objects.filter(label="hello world").exists()
kwargs = {
"name": data["name"],
+ "owner": self.user.actor.id,
"environment": data.get("environment"),
"action_match": data["actionMatch"],
"filter_match": data.get("filterMatch"),
diff --git a/tests/sentry/api/serializers/test_alert_rule.py b/tests/sentry/api/serializers/test_alert_rule.py
index 2ca7634e9d62c4..1fa7422ef98813 100644
--- a/tests/sentry/api/serializers/test_alert_rule.py
+++ b/tests/sentry/api/serializers/test_alert_rule.py
@@ -118,13 +118,12 @@ def test_created_by(self):
def test_owner(self):
user = self.create_user("[email protected]")
- print(self.team.actor.get_actor_tuple())
alert_rule = self.create_alert_rule(
environment=self.environment, user=user, owner=self.team.actor.get_actor_tuple()
)
result = serialize(alert_rule)
self.assert_alert_rule_serialized(alert_rule, result)
- # assert alert_rule.owner == self.team.actor.get_actor_identifier()
+ assert alert_rule.owner == self.team.actor
class DetailedAlertRuleSerializerTest(BaseAlertRuleSerializerTest, TestCase):
diff --git a/tests/sentry/integrations/test_ticket_rules.py b/tests/sentry/integrations/test_ticket_rules.py
index b2e467055ecb95..f9ecf88bbf2e11 100644
--- a/tests/sentry/integrations/test_ticket_rules.py
+++ b/tests/sentry/integrations/test_ticket_rules.py
@@ -78,6 +78,7 @@ def test_ticket_rules(self):
format="json",
data={
"name": "hello world",
+ "owner": self.user.id,
"environment": None,
"actionMatch": "any",
"frequency": 5,
diff --git a/tests/sentry/mediators/project_rules/test_creator.py b/tests/sentry/mediators/project_rules/test_creator.py
index f68966d6c9e573..2365c4ddef6d01 100644
--- a/tests/sentry/mediators/project_rules/test_creator.py
+++ b/tests/sentry/mediators/project_rules/test_creator.py
@@ -12,6 +12,7 @@ def setUp(self):
)
self.creator = Creator(
name="New Cool Rule",
+ owner=self.user.actor.id,
project=self.project,
action_match="all",
filter_match="any",
@@ -36,6 +37,7 @@ def test_creates_rule(self):
r = self.creator.call()
rule = Rule.objects.get(id=r.id)
assert rule.label == "New Cool Rule"
+ assert rule.owner == self.user.actor
assert rule.project == self.project
assert rule.environment_id is None
assert rule.data == {
diff --git a/tests/sentry/mediators/project_rules/test_updater.py b/tests/sentry/mediators/project_rules/test_updater.py
index 65f4c19016545e..f22d27aa0d5379 100644
--- a/tests/sentry/mediators/project_rules/test_updater.py
+++ b/tests/sentry/mediators/project_rules/test_updater.py
@@ -17,6 +17,16 @@ def test_update_name(self):
self.updater.call()
assert self.rule.label == "Cool New Rule"
+ def test_update_owner(self):
+ self.updater.owner = self.user.actor.id
+ self.updater.call()
+ assert self.rule.owner == self.user.actor
+
+ team = self.create_team()
+ self.updater.owner = team.actor.id
+ self.updater.call()
+ assert self.rule.owner == team.actor
+
def test_update_environment(self):
self.updater.environment = 3
self.updater.call()
|
4f13ea63fced44177666d7c0970bede9daf48014
|
2018-03-28 00:07:13
|
Evan Purkhiser
|
fix(ui): Detailed error alignment
| false
|
Detailed error alignment
|
fix
|
diff --git a/src/sentry/static/sentry/less/errors.less b/src/sentry/static/sentry/less/errors.less
index ff5003aeafa865..650e5a82ed6270 100644
--- a/src/sentry/static/sentry/less/errors.less
+++ b/src/sentry/static/sentry/less/errors.less
@@ -14,6 +14,10 @@
opacity: 0.3;
}
+.detailed-error-content {
+ margin-top: 8px;
+}
+
.detailed-error-content-footer {
margin-top: 18px;
border-top: 1px solid @trim;
|
39ab7e3d90cc2a0080a9d6145791856c0c594c0e
|
2020-07-21 23:00:16
|
Scott Cooper
|
feat(ui): Move issue subscribe button to action bar (#19327)
| false
|
Move issue subscribe button to action bar (#19327)
|
feat
|
diff --git a/src/sentry/static/sentry/app/components/group/sidebar.jsx b/src/sentry/static/sentry/app/components/group/sidebar.jsx
index 6151b00c7a3537..f338ffe5f9d2ec 100644
--- a/src/sentry/static/sentry/app/components/group/sidebar.jsx
+++ b/src/sentry/static/sentry/app/components/group/sidebar.jsx
@@ -6,7 +6,7 @@ import keyBy from 'lodash/keyBy';
import pickBy from 'lodash/pickBy';
import {addLoadingMessage, clearIndicators} from 'app/actionCreators/indicator';
-import {t, tct} from 'app/locale';
+import {t} from 'app/locale';
import ErrorBoundary from 'app/components/errorBoundary';
import ExternalIssueList from 'app/components/group/externalIssuesList';
import GroupParticipants from 'app/components/group/participants';
@@ -15,19 +15,9 @@ import GroupTagDistributionMeter from 'app/components/group/tagDistributionMeter
import GuideAnchor from 'app/components/assistant/guideAnchor';
import LoadingError from 'app/components/loadingError';
import SentryTypes from 'app/sentryTypes';
-import SubscribeButton from 'app/components/subscribeButton';
import SuggestedOwners from 'app/components/group/suggestedOwners/suggestedOwners';
import withApi from 'app/utils/withApi';
-
-const SUBSCRIPTION_REASONS = {
- commented: t("You're receiving updates because you have commented on this issue."),
- assigned: t("You're receiving updates because you were assigned to this issue."),
- bookmarked: t("You're receiving updates because you have bookmarked this issue."),
- changed_status: t(
- "You're receiving updates because you have changed the status of this issue."
- ),
- mentioned: t("You're receiving updates because you have been mentioned in this issue."),
-};
+import {getSubscriptionReason} from 'app/views/organizationGroupDetails/utils';
class GroupSidebar extends React.Component {
static propTypes = {
@@ -175,40 +165,8 @@ class GroupSidebar extends React.Component {
return null;
}
- canChangeSubscriptionState() {
- return !(this.props.group.subscriptionDetails || {disabled: false}).disabled;
- }
-
getNotificationText() {
- const {group} = this.props;
-
- if (group.isSubscribed) {
- let result = t(
- "You're receiving updates because you are subscribed to this issue."
- );
- if (group.subscriptionDetails) {
- const reason = group.subscriptionDetails.reason;
- if (SUBSCRIPTION_REASONS.hasOwnProperty(reason)) {
- result = SUBSCRIPTION_REASONS[reason];
- }
- } else {
- result = tct(
- "You're receiving updates because you are [link:subscribed to workflow notifications] for this project.",
- {
- link: <a href="/account/settings/notifications/" />,
- }
- );
- }
- return result;
- } else {
- if (group.subscriptionDetails && group.subscriptionDetails.disabled) {
- return tct('You have [link:disabled workflow notifications] for this project.', {
- link: <a href="/account/settings/notifications/" />,
- });
- } else {
- return t("You're not subscribed to this issue.");
- }
- }
+ return getSubscriptionReason(this.props.group);
}
renderParticipantData() {
@@ -289,17 +247,10 @@ class GroupSidebar extends React.Component {
)}
{this.renderParticipantData()}
-
<h6>
<span>{t('Notifications')}</span>
</h6>
<p className="help-block">{this.getNotificationText()}</p>
- {this.canChangeSubscriptionState() && (
- <SubscribeButton
- isSubscribed={group.isSubscribed}
- onClick={() => this.toggleSubscription()}
- />
- )}
</div>
);
}
diff --git a/src/sentry/static/sentry/app/components/subscribeButton.tsx b/src/sentry/static/sentry/app/components/subscribeButton.tsx
index e625e2843bd3f2..79e29dbbbed864 100644
--- a/src/sentry/static/sentry/app/components/subscribeButton.tsx
+++ b/src/sentry/static/sentry/app/components/subscribeButton.tsx
@@ -3,7 +3,7 @@ import React from 'react';
import Button from 'app/components/button';
import {t} from 'app/locale';
-import {IconBell} from 'app/icons/iconBell';
+import {IconBell} from 'app/icons';
type Props = {
onClick: (e: React.MouseEvent) => void;
diff --git a/src/sentry/static/sentry/app/icons/index.tsx b/src/sentry/static/sentry/app/icons/index.tsx
index 29e58e9ba99810..4a7355251c9935 100644
--- a/src/sentry/static/sentry/app/icons/index.tsx
+++ b/src/sentry/static/sentry/app/icons/index.tsx
@@ -96,3 +96,4 @@ export {IconWindow} from './iconWindow';
export {IconTerminal} from './iconTerminal';
export {IconSwitch} from './iconSwitch';
export {IconMobile} from './iconMobile';
+export {IconBell} from './iconBell';
diff --git a/src/sentry/static/sentry/app/types/index.tsx b/src/sentry/static/sentry/app/types/index.tsx
index 697a5e1ae221e7..d619dd7d4bfb73 100644
--- a/src/sentry/static/sentry/app/types/index.tsx
+++ b/src/sentry/static/sentry/app/types/index.tsx
@@ -612,6 +612,7 @@ export type Group = {
type: EventOrGroupType;
userCount: number;
userReportCount: number;
+ subscriptionDetails: {disabled?: boolean; reason?: string} | null;
};
/**
diff --git a/src/sentry/static/sentry/app/views/organizationGroupDetails/actions.jsx b/src/sentry/static/sentry/app/views/organizationGroupDetails/actions.jsx
index 8d1517d1745096..cae200ff14b1e8 100644
--- a/src/sentry/static/sentry/app/views/organizationGroupDetails/actions.jsx
+++ b/src/sentry/static/sentry/app/views/organizationGroupDetails/actions.jsx
@@ -32,6 +32,8 @@ import space from 'app/styles/space';
import withApi from 'app/utils/withApi';
import withOrganization from 'app/utils/withOrganization';
+import SubscribeAction from './subscribeAction';
+
class DeleteActions extends React.Component {
static propTypes = {
organization: SentryTypes.Organization.isRequired,
@@ -232,6 +234,10 @@ const GroupDetailsActions = createReactClass({
this.onUpdate({isBookmarked: !this.props.group.isBookmarked});
},
+ onToggleSubscribe() {
+ this.onUpdate({isSubscribed: !this.props.group.isSubscribed});
+ },
+
onDiscard() {
const {group, project, organization} = this.props;
const id = uniqueId();
@@ -283,30 +289,15 @@ const GroupDetailsActions = createReactClass({
isAutoResolved={isResolved && group.statusDetails.autoResolved}
/>
</GuideAnchor>
-
<GuideAnchor target="ignore_delete_discard" position="bottom" offset={space(3)}>
<IgnoreActions isIgnored={isIgnored} onUpdate={this.onUpdate} />
</GuideAnchor>
-
- <div className="btn-group">
- <div
- className={bookmarkClassName}
- title={t('Bookmark')}
- onClick={this.onToggleBookmark}
- >
- <IconWrapper>
- <IconStar isSolid size="xs" />
- </IconWrapper>
- </div>
- </div>
-
<DeleteActions
organization={organization}
project={project}
onDelete={this.onDelete}
onDiscard={this.onDiscard}
/>
-
{orgFeatures.has('shared-issues') && (
<div className="btn-group">
<ShareIssue
@@ -319,7 +310,6 @@ const GroupDetailsActions = createReactClass({
/>
</div>
)}
-
{orgFeatures.has('discover-basic') && (
<div className="btn-group">
<Link
@@ -331,6 +321,18 @@ const GroupDetailsActions = createReactClass({
</Link>
</div>
)}
+ <div className="btn-group">
+ <div
+ className={bookmarkClassName}
+ title={t('Bookmark')}
+ onClick={this.onToggleBookmark}
+ >
+ <IconWrapper>
+ <IconStar isSolid size="xs" />
+ </IconWrapper>
+ </div>
+ </div>
+ <SubscribeAction group={group} onClick={this.onToggleSubscribe} />
</div>
);
},
diff --git a/src/sentry/static/sentry/app/views/organizationGroupDetails/subscribeAction.tsx b/src/sentry/static/sentry/app/views/organizationGroupDetails/subscribeAction.tsx
new file mode 100644
index 00000000000000..56d334c54c13e2
--- /dev/null
+++ b/src/sentry/static/sentry/app/views/organizationGroupDetails/subscribeAction.tsx
@@ -0,0 +1,52 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+import styled from '@emotion/styled';
+
+import {Group} from 'app/types';
+import SentryTypes from 'app/sentryTypes';
+import {IconBell} from 'app/icons';
+import {t} from 'app/locale';
+import Tooltip from 'app/components/tooltip';
+
+import {getSubscriptionReason} from './utils';
+
+type Props = {
+ group: Group;
+ onClick: (event: React.MouseEvent<HTMLDivElement>) => void;
+};
+
+const SubscribeAction = ({group, onClick}: Props) => {
+ const canChangeSubscriptionState = (): boolean => {
+ return !(group.subscriptionDetails?.disabled ?? false);
+ };
+
+ const subscribedClassName = `group-subscribe btn btn-default btn-sm${
+ group.isSubscribed ? ' active' : ''
+ }`;
+
+ return (
+ canChangeSubscriptionState() && (
+ <div className="btn-group">
+ <Tooltip title={getSubscriptionReason(group, true)}>
+ <div className={subscribedClassName} title={t('Subscribe')} onClick={onClick}>
+ <IconWrapper>
+ <IconBell size="xs" />
+ </IconWrapper>
+ </div>
+ </Tooltip>
+ </div>
+ )
+ );
+};
+
+SubscribeAction.propTypes = {
+ group: SentryTypes.Group.isRequired,
+ onClick: PropTypes.func.isRequired,
+};
+
+export default SubscribeAction;
+
+const IconWrapper = styled('span')`
+ position: relative;
+ top: 1px;
+`;
diff --git a/src/sentry/static/sentry/app/views/organizationGroupDetails/utils.jsx b/src/sentry/static/sentry/app/views/organizationGroupDetails/utils.jsx
index 3e799ba94ed330..851bf94e7285e8 100644
--- a/src/sentry/static/sentry/app/views/organizationGroupDetails/utils.jsx
+++ b/src/sentry/static/sentry/app/views/organizationGroupDetails/utils.jsx
@@ -1,3 +1,6 @@
+import React from 'react';
+
+import {t, tct} from 'app/locale';
import {Client} from 'app/api';
/**
@@ -62,3 +65,58 @@ export function getEventEnvironment(event) {
return tag ? tag.value : null;
}
+
+const SUBSCRIPTION_REASONS = {
+ commented: t(
+ "You're receiving workflow notifications because you have commented on this issue."
+ ),
+ assigned: t(
+ "You're receiving workflow notifications because you were assigned to this issue."
+ ),
+ bookmarked: t(
+ "You're receiving workflow notifications because you have bookmarked this issue."
+ ),
+ changed_status: t(
+ "You're receiving workflow notifications because you have changed the status of this issue."
+ ),
+ mentioned: t(
+ "You're receiving workflow notifications because you have been mentioned in this issue."
+ ),
+};
+
+/**
+ * @param {object} group
+ * @param {boolean} removeLinks add/remove links to subscription reasons text (default: false)
+ * @returns Reason for subscription
+ */
+export function getSubscriptionReason(group, removeLinks = false) {
+ if (group.subscriptionDetails && group.subscriptionDetails.disabled) {
+ return tct('You have [link:disabled workflow notifications] for this project.', {
+ link: removeLinks ? <span /> : <a href="/account/settings/notifications/" />,
+ });
+ }
+
+ if (!group.isSubscribed) {
+ return t("You're not subscribed to this issue.");
+ }
+
+ if (group.subscriptionDetails) {
+ const {reason} = group.subscriptionDetails;
+ if (reason === 'unknown') {
+ return t(
+ "You're receiving workflow notifications because you are subscribed to this issue."
+ );
+ }
+
+ if (SUBSCRIPTION_REASONS.hasOwnProperty(reason)) {
+ return SUBSCRIPTION_REASONS[reason];
+ }
+ }
+
+ return tct(
+ "You're receiving updates because you are [link:subscribed to workflow notifications] for this project.",
+ {
+ link: removeLinks ? <span /> : <a href="/account/settings/notifications/" />,
+ }
+ );
+}
diff --git a/src/sentry/static/sentry/app/views/releasesV2/detail/overview/issues.tsx b/src/sentry/static/sentry/app/views/releasesV2/detail/overview/issues.tsx
index 5c6cfaadb23aa0..47f862af93aefe 100644
--- a/src/sentry/static/sentry/app/views/releasesV2/detail/overview/issues.tsx
+++ b/src/sentry/static/sentry/app/views/releasesV2/detail/overview/issues.tsx
@@ -179,7 +179,6 @@ class Issues extends React.Component<Props, State> {
</Button>
</OpenInButtonBar>
</ControlsWrapper>
-
<TableWrapper data-test-id="release-wrapper">
<GroupList
orgId={orgId}
diff --git a/tests/js/spec/components/group/sidebar.spec.jsx b/tests/js/spec/components/group/sidebar.spec.jsx
index ee4a754b538e76..4f266fd6353830 100644
--- a/tests/js/spec/components/group/sidebar.spec.jsx
+++ b/tests/js/spec/components/group/sidebar.spec.jsx
@@ -121,30 +121,6 @@ describe('GroupSidebar', function() {
});
});
- describe('subscribing', function() {
- let issuesApi;
- beforeEach(function() {
- issuesApi = MockApiClient.addMockResponse({
- url: '/projects/org-slug/project-slug/issues/',
- method: 'PUT',
- body: TestStubs.Group({isSubscribed: false}),
- });
- });
-
- it('can subscribe', function() {
- const btn = wrapper.find('SubscribeButton');
-
- btn.simulate('click');
-
- expect(issuesApi).toHaveBeenCalledWith(
- expect.anything(),
- expect.objectContaining({
- data: {isSubscribed: true},
- })
- );
- });
- });
-
describe('environment toggle', function() {
it('re-requests tags with correct environment', function() {
const stagingEnv = {name: 'staging', displayName: 'Staging', id: '2'};
diff --git a/tests/js/spec/views/organizationGroupDetails/actions.spec.jsx b/tests/js/spec/views/organizationGroupDetails/actions.spec.jsx
index ba0057f2a9081e..1a464ffd36abf0 100644
--- a/tests/js/spec/views/organizationGroupDetails/actions.spec.jsx
+++ b/tests/js/spec/views/organizationGroupDetails/actions.spec.jsx
@@ -1,6 +1,6 @@
import React from 'react';
-import {shallow} from 'sentry-test/enzyme';
+import {shallow, mountWithTheme} from 'sentry-test/enzyme';
import GroupActions from 'app/views/organizationGroupDetails/actions';
import ConfigStore from 'app/stores/configStore';
@@ -35,4 +35,86 @@ describe('GroupActions', function() {
expect(wrapper).toMatchSnapshot();
});
});
+
+ describe('subscribing', function() {
+ let issuesApi;
+ beforeEach(function() {
+ issuesApi = MockApiClient.addMockResponse({
+ url: '/projects/org/project/issues/',
+ method: 'PUT',
+ body: TestStubs.Group({isSubscribed: false}),
+ });
+ });
+
+ it('can subscribe', function() {
+ const wrapper = mountWithTheme(
+ <GroupActions
+ group={TestStubs.Group({
+ id: '1337',
+ pluginActions: [],
+ pluginIssues: [],
+ })}
+ project={TestStubs.ProjectDetails({
+ id: '2448',
+ name: 'project name',
+ slug: 'project',
+ })}
+ organization={TestStubs.Organization({
+ id: '4660',
+ slug: 'org',
+ })}
+ />
+ );
+ const btn = wrapper.find('.group-subscribe');
+ btn.simulate('click');
+
+ expect(issuesApi).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ data: {isSubscribed: true},
+ })
+ );
+ });
+ });
+
+ describe('bookmarking', function() {
+ let issuesApi;
+ beforeEach(function() {
+ issuesApi = MockApiClient.addMockResponse({
+ url: '/projects/org/project/issues/',
+ method: 'PUT',
+ body: TestStubs.Group({isBookmarked: false}),
+ });
+ });
+
+ it('can bookmark', function() {
+ const wrapper = mountWithTheme(
+ <GroupActions
+ group={TestStubs.Group({
+ id: '1337',
+ pluginActions: [],
+ pluginIssues: [],
+ })}
+ project={TestStubs.ProjectDetails({
+ id: '2448',
+ name: 'project name',
+ slug: 'project',
+ })}
+ organization={TestStubs.Organization({
+ id: '4660',
+ slug: 'org',
+ })}
+ />
+ );
+ const btn = wrapper.find('.group-bookmark');
+ btn.simulate('click');
+
+ expect(issuesApi).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ data: {isBookmarked: true},
+ })
+ );
+ });
+ });
});
diff --git a/webpack.config.js b/webpack.config.js
index 26405087805e25..2fa94202d36d8f 100644
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -1,8 +1,8 @@
/*eslint-env node*/
/*eslint import/no-nodejs-modules:0 */
const fs = require('fs');
-
const path = require('path');
+
const {CleanWebpackPlugin} = require('clean-webpack-plugin'); // installed via npm
const webpack = require('webpack');
const ExtractTextPlugin = require('mini-css-extract-plugin');
|
9285c52ef1c029baef1e721f4d74fea441018bc3
|
2023-04-29 01:06:43
|
Evan Purkhiser
|
ref(js): Use usePageFilters in organizationGroupDetails (#43218)
| false
|
Use usePageFilters in organizationGroupDetails (#43218)
|
ref
|
diff --git a/static/app/views/issueDetails/groupEventDetails/index.tsx b/static/app/views/issueDetails/groupEventDetails/index.tsx
index aad1f1e683b85b..7400c2315111f1 100644
--- a/static/app/views/issueDetails/groupEventDetails/index.tsx
+++ b/static/app/views/issueDetails/groupEventDetails/index.tsx
@@ -5,11 +5,11 @@ import LoadingIndicator from 'sentry/components/loadingIndicator';
import {t} from 'sentry/locale';
import OrganizationEnvironmentsStore from 'sentry/stores/organizationEnvironmentsStore';
import {useLegacyStore} from 'sentry/stores/useLegacyStore';
-import {Environment, Group, Organization, PageFilters, Project} from 'sentry/types';
+import {Environment, Group, Organization, Project} from 'sentry/types';
import {Event} from 'sentry/types/event';
import useApi from 'sentry/utils/useApi';
+import usePageFilters from 'sentry/utils/usePageFilters';
import withOrganization from 'sentry/utils/withOrganization';
-import withPageFilters from 'sentry/utils/withPageFilters';
import {ReprocessingStatus} from '../utils';
@@ -25,11 +25,11 @@ export interface GroupEventDetailsProps
onRetry: () => void;
organization: Organization;
project: Project;
- selection: PageFilters;
}
// Blocks rendering of the event until the environment is loaded
export function GroupEventDetailsContainer(props: GroupEventDetailsProps) {
+ const {selection} = usePageFilters();
const api = useApi();
// fetchOrganizationEnvironments is called in groupDetails.tsx
@@ -47,12 +47,11 @@ export function GroupEventDetailsContainer(props: GroupEventDetailsProps) {
return <LoadingIndicator />;
}
- const {selection, ...otherProps} = props;
const environments: Environment[] = state.environments.filter(env =>
selection.environments.includes(env.name)
);
- return <GroupEventDetails {...otherProps} api={api} environments={environments} />;
+ return <GroupEventDetails {...props} api={api} environments={environments} />;
}
-export default withOrganization(withPageFilters(GroupEventDetailsContainer));
+export default withOrganization(GroupEventDetailsContainer);
|
284592ab5b8c387d4a578dcfff322b2ae62cbe19
|
2023-11-15 19:35:39
|
Shruthi
|
chore(starfish): Rename breadcrumb, remove duplicate sidebar item (#59980)
| false
|
Rename breadcrumb, remove duplicate sidebar item (#59980)
|
chore
|
diff --git a/static/app/components/sidebar/index.tsx b/static/app/components/sidebar/index.tsx
index 25c05d88736b09..62aede10830a4d 100644
--- a/static/app/components/sidebar/index.tsx
+++ b/static/app/components/sidebar/index.tsx
@@ -342,13 +342,6 @@ function Sidebar({location, organization}: Props) {
id="performance-browser-interactions"
icon={<SubitemDot collapsed={collapsed} />}
/>
- <SidebarItem
- {...sidebarItemProps}
- label={<GuideAnchor target="starfish">{t('Screens')}</GuideAnchor>}
- to={`/organizations/${organization.slug}/performance/mobile/screens/`}
- id="starfish-mobile-screen-loads"
- icon={<SubitemDot collapsed={collapsed} />}
- />
</SidebarAccordion>
</Feature>
);
diff --git a/static/app/views/starfish/views/screens/screenLoadSpans/index.tsx b/static/app/views/starfish/views/screens/screenLoadSpans/index.tsx
index 38e5e16dfa184e..32f1243a45d7b2 100644
--- a/static/app/views/starfish/views/screens/screenLoadSpans/index.tsx
+++ b/static/app/views/starfish/views/screens/screenLoadSpans/index.tsx
@@ -13,7 +13,6 @@ import {
PageErrorAlert,
PageErrorProvider,
} from 'sentry/utils/performance/contexts/pageError';
-import {decodeScalar} from 'sentry/utils/queryString';
import {useLocation} from 'sentry/utils/useLocation';
import useOrganization from 'sentry/utils/useOrganization';
import useRouter from 'sentry/utils/useRouter';
@@ -64,7 +63,7 @@ function ScreenLoadSpans() {
},
{
to: '',
- label: decodeScalar(location.query.transaction),
+ label: t('Screen Summary'),
},
];
|
c53d501f6340b2f3b87c726eefe0db32df28a4f4
|
2023-09-09 04:47:46
|
Ryan Albrecht
|
ref: Refactor Entries fixture to use typescript (#55952)
| false
|
Refactor Entries fixture to use typescript (#55952)
|
ref
|
diff --git a/fixtures/js-stubs/entries.js b/fixtures/js-stubs/entries.js
deleted file mode 100644
index 571ec0a4501566..00000000000000
--- a/fixtures/js-stubs/entries.js
+++ /dev/null
@@ -1,698 +0,0 @@
-export function Entries() {
- return [
- [
- {
- type: 'exception',
- data: {
- values: [
- {
- stacktrace: {
- frames: [
- {
- function: null,
- colNo: null,
- vars: {},
- symbol: null,
- module: '<unknown module>',
- lineNo: null,
- errors: null,
- package: null,
- absPath:
- 'https://sentry.io/hiventy/kraken-prod/issues/438681831/?referrer=slack#',
- inApp: false,
- instructionAddr: null,
- filename: '/hiventy/kraken-prod/issues/438681831/',
- platform: null,
- context: [],
- symbolAddr: null,
- },
- ],
- framesOmitted: null,
- registers: null,
- hasSystemFrames: false,
- },
- module: null,
- rawStacktrace: null,
- mechanism: null,
- threadId: null,
- value: 'Unexpected token else',
- type: 'SyntaxError',
- },
- ],
- excOmitted: null,
- hasSystemFrames: false,
- },
- },
- {
- type: 'threads',
- data: {
- values: [
- {
- stacktrace: {
- frames: [
- {
- function: 'start',
- package: 'libdyld.dylib',
- image_addr: '0x7fff20256000',
- in_app: true,
- symbol_addr: '0x7fff20257408',
- data: {},
- instruction_addr: '0x7fff20257409',
- },
- {
- function: 'main',
- package: 'iOS-Swift',
- symbol: 'main',
- image_addr: '0x10e68f000',
- in_app: true,
- symbol_addr: '0x10e693440',
- data: {},
- instruction_addr: '0x10e69348a',
- },
- {
- function: 'UIApplicationMain',
- package: 'UIKitCore',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff246722bb',
- data: {},
- instruction_addr: '0x7fff24672320',
- },
- {
- function: '-[UIApplication _run]',
- package: 'UIKitCore',
- symbol: '-[UIApplication _run]',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff2466d07f',
- data: {},
- instruction_addr: '0x7fff2466d40f',
- },
- {
- function: 'GSEventRunModal',
- package: 'GraphicsServices',
- image_addr: '0x7fff2b790000',
- in_app: true,
- symbol_addr: '0x7fff2b793d28',
- data: {},
- instruction_addr: '0x7fff2b793db3',
- },
- {
- function: 'CFRunLoopRunSpecific',
- package: 'CoreFoundation',
- image_addr: '0x7fff20329000',
- in_app: true,
- symbol_addr: '0x7fff203a1967',
- data: {},
- instruction_addr: '0x7fff203a1b9e',
- },
- {
- function: '__CFRunLoopRun',
- package: 'CoreFoundation',
- image_addr: '0x7fff20329000',
- in_app: true,
- symbol_addr: '0x7fff203a2089',
- data: {},
- instruction_addr: '0x7fff203a23f7',
- },
- {
- function: '__CFRunLoopDoSources0',
- package: 'CoreFoundation',
- image_addr: '0x7fff20329000',
- in_app: true,
- symbol_addr: '0x7fff203a7b27',
- data: {},
- instruction_addr: '0x7fff203a7c1f',
- },
- {
- function: '__CFRunLoopDoSource0',
- package: 'CoreFoundation',
- image_addr: '0x7fff20329000',
- in_app: true,
- symbol_addr: '0x7fff203a8689',
- data: {},
- instruction_addr: '0x7fff203a873d',
- },
- {
- function:
- '__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__',
- package: 'CoreFoundation',
- image_addr: '0x7fff20329000',
- in_app: true,
- symbol_addr: '0x7fff203a8834',
- data: {},
- instruction_addr: '0x7fff203a8845',
- },
- {
- function: '__eventFetcherSourceCallback',
- package: 'UIKitCore',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff24712c68',
- data: {},
- instruction_addr: '0x7fff24712cd0',
- },
- {
- function: '__processEventQueue',
- package: 'UIKitCore',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff24718cf3',
- data: {},
- instruction_addr: '0x7fff2471c33a',
- },
- {
- function: '-[UIApplicationAccessibility sendEvent:]',
- package: 'UIKit',
- symbol: '-[UIApplicationAccessibility sendEvent:]',
- image_addr: '0x110b5e000',
- in_app: true,
- symbol_addr: '0x110b8799d',
- data: {},
- instruction_addr: '0x110b879f2',
- },
- {
- function: '-[UIApplication sendEvent:]',
- package: 'UIKitCore',
- symbol: '-[UIApplication sendEvent:]',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff2468ba19',
- data: {},
- instruction_addr: '0x7fff2468bc92',
- },
- {
- function: '-[UIWindow sendEvent:]',
- package: 'UIKitCore',
- symbol: '-[UIWindow sendEvent:]',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff246b0eb9',
- data: {},
- instruction_addr: '0x7fff246b215f',
- },
- {
- function: '-[UIWindow _sendTouchesForEvent:]',
- package: 'UIKitCore',
- symbol: '-[UIWindow _sendTouchesForEvent:]',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff246afddf',
- data: {},
- instruction_addr: '0x7fff246b02e6',
- },
- {
- function: '-[UIControl touchesEnded:withEvent:]',
- package: 'UIKitCore',
- symbol: '-[UIControl touchesEnded:withEvent:]',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff23f9e644',
- data: {},
- instruction_addr: '0x7fff23f9e838',
- },
- {
- function: '-[UIControl _sendActionsForEvents:withEvent:]',
- package: 'UIKitCore',
- symbol: '-[UIControl _sendActionsForEvents:withEvent:]',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff23f9fe03',
- data: {},
- instruction_addr: '0x7fff23f9ff4f',
- },
- {
- function: '-[UIControl sendAction:to:forEvent:]',
- package: 'UIKitCore',
- symbol: '-[UIControl sendAction:to:forEvent:]',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff23f9fb4d',
- data: {},
- instruction_addr: '0x7fff23f9fc2c',
- },
- {
- function:
- '__44-[SentryBreadcrumbTracker swizzleSendAction]_block_invoke_2',
- package: 'Sentry',
- symbol:
- '__44-[SentryBreadcrumbTracker swizzleSendAction]_block_invoke_2',
- image_addr: '0x10e90f000',
- in_app: false,
- symbol_addr: '0x10e951350',
- data: {},
- instruction_addr: '0x10e9518e9',
- },
- {
- function: '-[UIApplication sendAction:to:from:forEvent:]',
- package: 'UIKitCore',
- symbol: '-[UIApplication sendAction:to:from:forEvent:]',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff24673978',
- data: {},
- instruction_addr: '0x7fff246739cb',
- },
- {
- function: 'ViewController.captureNSException',
- package: 'iOS-Swift',
- symbol: '$s9iOS_Swift14ViewControllerC18captureNSExceptionyyypFTo',
- image_addr: '0x10e68f000',
- in_app: true,
- symbol_addr: '0x10e692290',
- raw_function: '@objc ViewController.captureNSException(_:)',
- data: {},
- instruction_addr: '0x10e6922df',
- },
- {
- function: 'ViewController.captureNSException',
- package: 'iOS-Swift',
- symbol: '$s9iOS_Swift14ViewControllerC18captureNSExceptionyyypF',
- image_addr: '0x10e68f000',
- in_app: true,
- symbol_addr: '0x10e691e60',
- raw_function: 'ViewController.captureNSException(_:)',
- data: {},
- instruction_addr: '0x10e691fd8',
- },
- ],
- },
- name: '',
- current: true,
- crashed: true,
- state: 'RUNNABLE',
- raw_stacktrace: {
- frames: [
- {
- function: 'start',
- package: 'libdyld.dylib',
- image_addr: '0x7fff20256000',
- in_app: true,
- symbol_addr: '0x7fff20257408',
- instruction_addr: '0x7fff20257409',
- },
- {
- function: 'main',
- package: 'iOS-Swift',
- image_addr: '0x10e68f000',
- in_app: true,
- symbol_addr: '0x10e693440',
- instruction_addr: '0x10e69348b',
- },
- {
- function: 'UIApplicationMain',
- package: 'UIKitCore',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff246722bb',
- instruction_addr: '0x7fff24672320',
- },
- {
- function: '-[UIApplication _run]',
- package: 'UIKitCore',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff2466d07f',
- instruction_addr: '0x7fff2466d40f',
- },
- {
- function: 'GSEventRunModal',
- package: 'GraphicsServices',
- image_addr: '0x7fff2b790000',
- in_app: true,
- symbol_addr: '0x7fff2b793d28',
- instruction_addr: '0x7fff2b793db3',
- },
- {
- function: 'CFRunLoopRunSpecific',
- package: 'CoreFoundation',
- image_addr: '0x7fff20329000',
- in_app: true,
- symbol_addr: '0x7fff203a1967',
- instruction_addr: '0x7fff203a1b9e',
- },
- {
- function: '__CFRunLoopRun',
- package: 'CoreFoundation',
- image_addr: '0x7fff20329000',
- in_app: true,
- symbol_addr: '0x7fff203a2089',
- instruction_addr: '0x7fff203a23f7',
- },
- {
- function: '__CFRunLoopDoSources0',
- package: 'CoreFoundation',
- image_addr: '0x7fff20329000',
- in_app: true,
- symbol_addr: '0x7fff203a7b27',
- instruction_addr: '0x7fff203a7c1f',
- },
- {
- function: '__CFRunLoopDoSource0',
- package: 'CoreFoundation',
- image_addr: '0x7fff20329000',
- in_app: true,
- symbol_addr: '0x7fff203a8689',
- instruction_addr: '0x7fff203a873d',
- },
- {
- function:
- '__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__',
- package: 'CoreFoundation',
- image_addr: '0x7fff20329000',
- in_app: true,
- symbol_addr: '0x7fff203a8834',
- instruction_addr: '0x7fff203a8845',
- },
- {
- function: '__eventFetcherSourceCallback',
- package: 'UIKitCore',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff24712c68',
- instruction_addr: '0x7fff24712cd0',
- },
- {
- function: '__processEventQueue',
- package: 'UIKitCore',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff24718cf3',
- instruction_addr: '0x7fff2471c33a',
- },
- {
- function: '-[UIApplicationAccessibility sendEvent:]',
- package: 'UIKit',
- image_addr: '0x110b5e000',
- in_app: true,
- symbol_addr: '0x110b8799d',
- instruction_addr: '0x110b879f2',
- },
- {
- function: '-[UIApplication sendEvent:]',
- package: 'UIKitCore',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff2468ba19',
- instruction_addr: '0x7fff2468bc92',
- },
- {
- function: '-[UIWindow sendEvent:]',
- package: 'UIKitCore',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff246b0eb9',
- instruction_addr: '0x7fff246b215f',
- },
- {
- function: '-[UIWindow _sendTouchesForEvent:]',
- package: 'UIKitCore',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff246afddf',
- instruction_addr: '0x7fff246b02e6',
- },
- {
- function: '-[UIControl touchesEnded:withEvent:]',
- package: 'UIKitCore',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff23f9e644',
- instruction_addr: '0x7fff23f9e838',
- },
- {
- function: '-[UIControl _sendActionsForEvents:withEvent:]',
- package: 'UIKitCore',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff23f9fe03',
- instruction_addr: '0x7fff23f9ff4f',
- },
- {
- function: '-[UIControl sendAction:to:forEvent:]',
- package: 'UIKitCore',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff23f9fb4d',
- instruction_addr: '0x7fff23f9fc2c',
- },
- {
- function:
- '__44-[SentryBreadcrumbTracker swizzleSendAction]_block_invoke_2',
- package: 'Sentry',
- image_addr: '0x10e90f000',
- in_app: false,
- symbol_addr: '0x10e951350',
- instruction_addr: '0x10e9518ea',
- },
- {
- function: '-[UIApplication sendAction:to:from:forEvent:]',
- package: 'UIKitCore',
- image_addr: '0x7fff23a83000',
- in_app: true,
- symbol_addr: '0x7fff24673978',
- instruction_addr: '0x7fff246739cb',
- },
- {
- function: '$s9iOS_Swift14ViewControllerC18captureNSExceptionyyypFTo',
- package: 'iOS-Swift',
- image_addr: '0x10e68f000',
- in_app: true,
- symbol_addr: '0x10e692290',
- instruction_addr: '0x10e6922e0',
- },
- {
- function: '$s9iOS_Swift14ViewControllerC18captureNSExceptionyyypF',
- package: 'iOS-Swift',
- image_addr: '0x10e68f000',
- in_app: true,
- symbol_addr: '0x10e691e60',
- instruction_addr: '0x10e691fd8',
- },
- ],
- },
- id: 0,
- },
- {
- current: false,
- crashed: false,
- id: 1,
- name: '',
- state: 'BLOCKED',
- },
- {
- current: false,
- crashed: false,
- id: 2,
- state: 'WAITING',
- name: '',
- },
- {
- current: false,
- crashed: false,
- id: 3,
- state: 'WAITING',
- name: 'com.apple.uikit.eventfetch-thread',
- },
- {
- current: false,
- crashed: false,
- id: 4,
- state: 'WAITING',
- name: '',
- },
- {
- current: false,
- crashed: false,
- id: 5,
- state: 'WAITING',
- name: '',
- },
- {
- current: false,
- crashed: false,
- id: 6,
- state: 'WAITING',
- name: '',
- },
- {
- current: false,
- crashed: false,
- id: 7,
- state: 'WAITING',
- name: 'com.apple.NSURLConnectionLoader',
- },
- ],
- },
- },
- {
- type: 'breadcrumbs',
- data: {
- values: [
- {
- category: 'xhr',
- level: 'info',
- event_id: null,
- timestamp: '2018-01-23T08:12:53.591Z',
- data: {
- url: 'https://reload.getsentry.net/page/',
- status_code: '201',
- method: 'POST',
- },
- message: null,
- type: 'http',
- },
- {
- category: 'xhr',
- level: 'info',
- event_id: null,
- timestamp: '2018-01-23T08:12:53.636Z',
- data: {
- url: '/api/0/organizations/?member=1',
- status_code: '200',
- method: 'GET',
- },
- message: null,
- type: 'http',
- },
- {
- category: 'xhr',
- level: 'info',
- event_id: null,
- timestamp: '2018-01-23T08:12:53.895Z',
- data: {url: '/api/0/internal/health/', status_code: '403', method: 'GET'},
- message: null,
- type: 'http',
- },
- ],
- },
- },
- {
- type: 'request',
- data: {
- fragment: '',
- cookies: [],
- inferredContentType: null,
- env: null,
- headers: [
- ['Referer', '[Filtered]'],
- [
- 'User-Agent',
- 'Mozilla/5.0 (Linux; Android 7.0; ONEPLUS A3003 Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/56.0.2924.87 Mobile Safari/537.36',
- ],
- ],
- url: 'https://sentry.io/hiventy/kraken-prod/issues/438681831/',
- query: 'referrer=slack',
- data: null,
- method: null,
- },
- },
- ],
- [
- {
- type: 'exception',
- data: {
- values: [
- {
- stacktrace: {
- frames: [
- {
- function: null,
- colNo: null,
- vars: {},
- symbol: null,
- module: '<unknown module>',
- lineNo: null,
- errors: null,
- package: null,
- absPath:
- 'https://sentry.io/hiventy/kraken-prod/issues/438681831/?referrer=slack#',
- inApp: false,
- instructionAddr: null,
- filename: '/hiventy/kraken-prod/issues/438681831/',
- platform: null,
- context: [],
- symbolAddr: null,
- },
- ],
- framesOmitted: null,
- registers: null,
- hasSystemFrames: false,
- },
- module: null,
- rawStacktrace: null,
- mechanism: null,
- threadId: null,
- value: 'Unexpected token else',
- type: 'SyntaxError',
- },
- ],
- excOmitted: null,
- hasSystemFrames: false,
- },
- },
- {
- type: 'breadcrumbs',
- data: {
- values: [
- {
- category: 'xhr',
- level: 'info',
- event_id: null,
- timestamp: '2018-01-23T08:12:53.591Z',
- data: {
- url: 'https://reload.getsentry.net/page/',
- status_code: '201',
- method: 'POST',
- },
- message: null,
- type: 'http',
- },
- {
- category: 'xhr',
- level: 'info',
- event_id: null,
- timestamp: '2018-01-23T08:12:53.636Z',
- data: {
- url: '/api/0/organizations/?member=1',
- status_code: '200',
- method: 'GET',
- },
- message: null,
- type: 'http',
- },
- {
- category: 'xhr',
- level: 'info',
- event_id: null,
- timestamp: '2018-01-23T08:12:53.895Z',
- data: {url: '/api/0/internal/health/', status_code: '403', method: 'GET'},
- message: null,
- type: 'http',
- },
- ],
- },
- },
- {
- type: 'request',
- data: {
- fragment: '',
- cookies: [],
- inferredContentType: null,
- env: null,
- headers: [
- ['Referer', '[Filtered]'],
- [
- 'User-Agent',
- 'Mozilla/5.0 (Linux; Android 7.0; ONEPLUS A3003 Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/56.0.2924.87 Mobile Safari/537.36',
- ],
- ],
- url: 'https://sentry.io/hiventy/kraken-prod/issues/438681831/',
- query: 'referrer=slack',
- data: null,
- method: null,
- },
- },
- ],
- ];
-}
diff --git a/fixtures/js-stubs/entries.ts b/fixtures/js-stubs/entries.ts
new file mode 100644
index 00000000000000..0786fca8a649ff
--- /dev/null
+++ b/fixtures/js-stubs/entries.ts
@@ -0,0 +1,701 @@
+import {type Entry as TEntry, EntryType} from 'sentry/types';
+
+import {EventEntry as MockEventEntry} from './eventEntry';
+
+export function Entries123Target(): TEntry[] {
+ return [
+ MockEventEntry({
+ type: EntryType.EXCEPTION,
+ data: {
+ values: [
+ {
+ stacktrace: {
+ frames: [
+ {
+ function: null,
+ colNo: null,
+ vars: {},
+ symbol: null,
+ module: '<unknown module>',
+ lineNo: null,
+ errors: null,
+ package: null,
+ absPath:
+ 'https://sentry.io/hiventy/kraken-prod/issues/438681831/?referrer=slack#',
+ inApp: false,
+ instructionAddr: null,
+ filename: '/hiventy/kraken-prod/issues/438681831/',
+ platform: null,
+ context: [],
+ symbolAddr: null,
+ },
+ ],
+ framesOmitted: null,
+ registers: null,
+ hasSystemFrames: false,
+ },
+ module: null,
+ rawStacktrace: null,
+ mechanism: null,
+ threadId: null,
+ value: 'Unexpected token else',
+ type: 'SyntaxError',
+ },
+ ],
+ excOmitted: null,
+ hasSystemFrames: false,
+ },
+ }),
+ MockEventEntry({
+ type: EntryType.THREADS,
+ data: {
+ values: [
+ {
+ stacktrace: {
+ frames: [
+ {
+ function: 'start',
+ package: 'libdyld.dylib',
+ image_addr: '0x7fff20256000',
+ in_app: true,
+ symbol_addr: '0x7fff20257408',
+ data: {},
+ instruction_addr: '0x7fff20257409',
+ },
+ {
+ function: 'main',
+ package: 'iOS-Swift',
+ symbol: 'main',
+ image_addr: '0x10e68f000',
+ in_app: true,
+ symbol_addr: '0x10e693440',
+ data: {},
+ instruction_addr: '0x10e69348a',
+ },
+ {
+ function: 'UIApplicationMain',
+ package: 'UIKitCore',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff246722bb',
+ data: {},
+ instruction_addr: '0x7fff24672320',
+ },
+ {
+ function: '-[UIApplication _run]',
+ package: 'UIKitCore',
+ symbol: '-[UIApplication _run]',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff2466d07f',
+ data: {},
+ instruction_addr: '0x7fff2466d40f',
+ },
+ {
+ function: 'GSEventRunModal',
+ package: 'GraphicsServices',
+ image_addr: '0x7fff2b790000',
+ in_app: true,
+ symbol_addr: '0x7fff2b793d28',
+ data: {},
+ instruction_addr: '0x7fff2b793db3',
+ },
+ {
+ function: 'CFRunLoopRunSpecific',
+ package: 'CoreFoundation',
+ image_addr: '0x7fff20329000',
+ in_app: true,
+ symbol_addr: '0x7fff203a1967',
+ data: {},
+ instruction_addr: '0x7fff203a1b9e',
+ },
+ {
+ function: '__CFRunLoopRun',
+ package: 'CoreFoundation',
+ image_addr: '0x7fff20329000',
+ in_app: true,
+ symbol_addr: '0x7fff203a2089',
+ data: {},
+ instruction_addr: '0x7fff203a23f7',
+ },
+ {
+ function: '__CFRunLoopDoSources0',
+ package: 'CoreFoundation',
+ image_addr: '0x7fff20329000',
+ in_app: true,
+ symbol_addr: '0x7fff203a7b27',
+ data: {},
+ instruction_addr: '0x7fff203a7c1f',
+ },
+ {
+ function: '__CFRunLoopDoSource0',
+ package: 'CoreFoundation',
+ image_addr: '0x7fff20329000',
+ in_app: true,
+ symbol_addr: '0x7fff203a8689',
+ data: {},
+ instruction_addr: '0x7fff203a873d',
+ },
+ {
+ function: '__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__',
+ package: 'CoreFoundation',
+ image_addr: '0x7fff20329000',
+ in_app: true,
+ symbol_addr: '0x7fff203a8834',
+ data: {},
+ instruction_addr: '0x7fff203a8845',
+ },
+ {
+ function: '__eventFetcherSourceCallback',
+ package: 'UIKitCore',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff24712c68',
+ data: {},
+ instruction_addr: '0x7fff24712cd0',
+ },
+ {
+ function: '__processEventQueue',
+ package: 'UIKitCore',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff24718cf3',
+ data: {},
+ instruction_addr: '0x7fff2471c33a',
+ },
+ {
+ function: '-[UIApplicationAccessibility sendEvent:]',
+ package: 'UIKit',
+ symbol: '-[UIApplicationAccessibility sendEvent:]',
+ image_addr: '0x110b5e000',
+ in_app: true,
+ symbol_addr: '0x110b8799d',
+ data: {},
+ instruction_addr: '0x110b879f2',
+ },
+ {
+ function: '-[UIApplication sendEvent:]',
+ package: 'UIKitCore',
+ symbol: '-[UIApplication sendEvent:]',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff2468ba19',
+ data: {},
+ instruction_addr: '0x7fff2468bc92',
+ },
+ {
+ function: '-[UIWindow sendEvent:]',
+ package: 'UIKitCore',
+ symbol: '-[UIWindow sendEvent:]',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff246b0eb9',
+ data: {},
+ instruction_addr: '0x7fff246b215f',
+ },
+ {
+ function: '-[UIWindow _sendTouchesForEvent:]',
+ package: 'UIKitCore',
+ symbol: '-[UIWindow _sendTouchesForEvent:]',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff246afddf',
+ data: {},
+ instruction_addr: '0x7fff246b02e6',
+ },
+ {
+ function: '-[UIControl touchesEnded:withEvent:]',
+ package: 'UIKitCore',
+ symbol: '-[UIControl touchesEnded:withEvent:]',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff23f9e644',
+ data: {},
+ instruction_addr: '0x7fff23f9e838',
+ },
+ {
+ function: '-[UIControl _sendActionsForEvents:withEvent:]',
+ package: 'UIKitCore',
+ symbol: '-[UIControl _sendActionsForEvents:withEvent:]',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff23f9fe03',
+ data: {},
+ instruction_addr: '0x7fff23f9ff4f',
+ },
+ {
+ function: '-[UIControl sendAction:to:forEvent:]',
+ package: 'UIKitCore',
+ symbol: '-[UIControl sendAction:to:forEvent:]',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff23f9fb4d',
+ data: {},
+ instruction_addr: '0x7fff23f9fc2c',
+ },
+ {
+ function:
+ '__44-[SentryBreadcrumbTracker swizzleSendAction]_block_invoke_2',
+ package: 'Sentry',
+ symbol:
+ '__44-[SentryBreadcrumbTracker swizzleSendAction]_block_invoke_2',
+ image_addr: '0x10e90f000',
+ in_app: false,
+ symbol_addr: '0x10e951350',
+ data: {},
+ instruction_addr: '0x10e9518e9',
+ },
+ {
+ function: '-[UIApplication sendAction:to:from:forEvent:]',
+ package: 'UIKitCore',
+ symbol: '-[UIApplication sendAction:to:from:forEvent:]',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff24673978',
+ data: {},
+ instruction_addr: '0x7fff246739cb',
+ },
+ {
+ function: 'ViewController.captureNSException',
+ package: 'iOS-Swift',
+ symbol: '$s9iOS_Swift14ViewControllerC18captureNSExceptionyyypFTo',
+ image_addr: '0x10e68f000',
+ in_app: true,
+ symbol_addr: '0x10e692290',
+ raw_function: '@objc ViewController.captureNSException(_:)',
+ data: {},
+ instruction_addr: '0x10e6922df',
+ },
+ {
+ function: 'ViewController.captureNSException',
+ package: 'iOS-Swift',
+ symbol: '$s9iOS_Swift14ViewControllerC18captureNSExceptionyyypF',
+ image_addr: '0x10e68f000',
+ in_app: true,
+ symbol_addr: '0x10e691e60',
+ raw_function: 'ViewController.captureNSException(_:)',
+ data: {},
+ instruction_addr: '0x10e691fd8',
+ },
+ ],
+ },
+ name: '',
+ current: true,
+ crashed: true,
+ state: 'RUNNABLE',
+ raw_stacktrace: {
+ frames: [
+ {
+ function: 'start',
+ package: 'libdyld.dylib',
+ image_addr: '0x7fff20256000',
+ in_app: true,
+ symbol_addr: '0x7fff20257408',
+ instruction_addr: '0x7fff20257409',
+ },
+ {
+ function: 'main',
+ package: 'iOS-Swift',
+ image_addr: '0x10e68f000',
+ in_app: true,
+ symbol_addr: '0x10e693440',
+ instruction_addr: '0x10e69348b',
+ },
+ {
+ function: 'UIApplicationMain',
+ package: 'UIKitCore',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff246722bb',
+ instruction_addr: '0x7fff24672320',
+ },
+ {
+ function: '-[UIApplication _run]',
+ package: 'UIKitCore',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff2466d07f',
+ instruction_addr: '0x7fff2466d40f',
+ },
+ {
+ function: 'GSEventRunModal',
+ package: 'GraphicsServices',
+ image_addr: '0x7fff2b790000',
+ in_app: true,
+ symbol_addr: '0x7fff2b793d28',
+ instruction_addr: '0x7fff2b793db3',
+ },
+ {
+ function: 'CFRunLoopRunSpecific',
+ package: 'CoreFoundation',
+ image_addr: '0x7fff20329000',
+ in_app: true,
+ symbol_addr: '0x7fff203a1967',
+ instruction_addr: '0x7fff203a1b9e',
+ },
+ {
+ function: '__CFRunLoopRun',
+ package: 'CoreFoundation',
+ image_addr: '0x7fff20329000',
+ in_app: true,
+ symbol_addr: '0x7fff203a2089',
+ instruction_addr: '0x7fff203a23f7',
+ },
+ {
+ function: '__CFRunLoopDoSources0',
+ package: 'CoreFoundation',
+ image_addr: '0x7fff20329000',
+ in_app: true,
+ symbol_addr: '0x7fff203a7b27',
+ instruction_addr: '0x7fff203a7c1f',
+ },
+ {
+ function: '__CFRunLoopDoSource0',
+ package: 'CoreFoundation',
+ image_addr: '0x7fff20329000',
+ in_app: true,
+ symbol_addr: '0x7fff203a8689',
+ instruction_addr: '0x7fff203a873d',
+ },
+ {
+ function: '__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__',
+ package: 'CoreFoundation',
+ image_addr: '0x7fff20329000',
+ in_app: true,
+ symbol_addr: '0x7fff203a8834',
+ instruction_addr: '0x7fff203a8845',
+ },
+ {
+ function: '__eventFetcherSourceCallback',
+ package: 'UIKitCore',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff24712c68',
+ instruction_addr: '0x7fff24712cd0',
+ },
+ {
+ function: '__processEventQueue',
+ package: 'UIKitCore',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff24718cf3',
+ instruction_addr: '0x7fff2471c33a',
+ },
+ {
+ function: '-[UIApplicationAccessibility sendEvent:]',
+ package: 'UIKit',
+ image_addr: '0x110b5e000',
+ in_app: true,
+ symbol_addr: '0x110b8799d',
+ instruction_addr: '0x110b879f2',
+ },
+ {
+ function: '-[UIApplication sendEvent:]',
+ package: 'UIKitCore',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff2468ba19',
+ instruction_addr: '0x7fff2468bc92',
+ },
+ {
+ function: '-[UIWindow sendEvent:]',
+ package: 'UIKitCore',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff246b0eb9',
+ instruction_addr: '0x7fff246b215f',
+ },
+ {
+ function: '-[UIWindow _sendTouchesForEvent:]',
+ package: 'UIKitCore',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff246afddf',
+ instruction_addr: '0x7fff246b02e6',
+ },
+ {
+ function: '-[UIControl touchesEnded:withEvent:]',
+ package: 'UIKitCore',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff23f9e644',
+ instruction_addr: '0x7fff23f9e838',
+ },
+ {
+ function: '-[UIControl _sendActionsForEvents:withEvent:]',
+ package: 'UIKitCore',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff23f9fe03',
+ instruction_addr: '0x7fff23f9ff4f',
+ },
+ {
+ function: '-[UIControl sendAction:to:forEvent:]',
+ package: 'UIKitCore',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff23f9fb4d',
+ instruction_addr: '0x7fff23f9fc2c',
+ },
+ {
+ function:
+ '__44-[SentryBreadcrumbTracker swizzleSendAction]_block_invoke_2',
+ package: 'Sentry',
+ image_addr: '0x10e90f000',
+ in_app: false,
+ symbol_addr: '0x10e951350',
+ instruction_addr: '0x10e9518ea',
+ },
+ {
+ function: '-[UIApplication sendAction:to:from:forEvent:]',
+ package: 'UIKitCore',
+ image_addr: '0x7fff23a83000',
+ in_app: true,
+ symbol_addr: '0x7fff24673978',
+ instruction_addr: '0x7fff246739cb',
+ },
+ {
+ function: '$s9iOS_Swift14ViewControllerC18captureNSExceptionyyypFTo',
+ package: 'iOS-Swift',
+ image_addr: '0x10e68f000',
+ in_app: true,
+ symbol_addr: '0x10e692290',
+ instruction_addr: '0x10e6922e0',
+ },
+ {
+ function: '$s9iOS_Swift14ViewControllerC18captureNSExceptionyyypF',
+ package: 'iOS-Swift',
+ image_addr: '0x10e68f000',
+ in_app: true,
+ symbol_addr: '0x10e691e60',
+ instruction_addr: '0x10e691fd8',
+ },
+ ],
+ },
+ id: 0,
+ },
+ {
+ current: false,
+ crashed: false,
+ id: 1,
+ name: '',
+ state: 'BLOCKED',
+ },
+ {
+ current: false,
+ crashed: false,
+ id: 2,
+ state: 'WAITING',
+ name: '',
+ },
+ {
+ current: false,
+ crashed: false,
+ id: 3,
+ state: 'WAITING',
+ name: 'com.apple.uikit.eventfetch-thread',
+ },
+ {
+ current: false,
+ crashed: false,
+ id: 4,
+ state: 'WAITING',
+ name: '',
+ },
+ {
+ current: false,
+ crashed: false,
+ id: 5,
+ state: 'WAITING',
+ name: '',
+ },
+ {
+ current: false,
+ crashed: false,
+ id: 6,
+ state: 'WAITING',
+ name: '',
+ },
+ {
+ current: false,
+ crashed: false,
+ id: 7,
+ state: 'WAITING',
+ name: 'com.apple.NSURLConnectionLoader',
+ },
+ ],
+ },
+ }),
+ MockEventEntry({
+ type: EntryType.BREADCRUMBS,
+ data: {
+ values: [
+ {
+ category: 'xhr',
+ level: 'info',
+ event_id: null,
+ timestamp: '2018-01-23T08:12:53.591Z',
+ data: {
+ url: 'https://reload.getsentry.net/page/',
+ status_code: '201',
+ method: 'POST',
+ },
+ message: null,
+ type: 'http',
+ },
+ {
+ category: 'xhr',
+ level: 'info',
+ event_id: null,
+ timestamp: '2018-01-23T08:12:53.636Z',
+ data: {
+ url: '/api/0/organizations/?member=1',
+ status_code: '200',
+ method: 'GET',
+ },
+ message: null,
+ type: 'http',
+ },
+ {
+ category: 'xhr',
+ level: 'info',
+ event_id: null,
+ timestamp: '2018-01-23T08:12:53.895Z',
+ data: {url: '/api/0/internal/health/', status_code: '403', method: 'GET'},
+ message: null,
+ type: 'http',
+ },
+ ],
+ },
+ }),
+ MockEventEntry({
+ type: EntryType.REQUEST,
+ data: {
+ fragment: '',
+ cookies: [],
+ inferredContentType: null,
+ env: null,
+ headers: [
+ ['Referer', '[Filtered]'],
+ [
+ 'User-Agent',
+ 'Mozilla/5.0 (Linux; Android 7.0; ONEPLUS A3003 Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/56.0.2924.87 Mobile Safari/537.36',
+ ],
+ ],
+ url: 'https://sentry.io/hiventy/kraken-prod/issues/438681831/',
+ query: 'referrer=slack',
+ data: null,
+ method: null,
+ },
+ }),
+ ];
+}
+
+export function Entries123Base(): TEntry[] {
+ return [
+ MockEventEntry({
+ type: EntryType.EXCEPTION,
+ data: {
+ values: [
+ {
+ stacktrace: {
+ frames: [
+ {
+ function: null,
+ colNo: null,
+ vars: {},
+ symbol: null,
+ module: '<unknown module>',
+ lineNo: null,
+ errors: null,
+ package: null,
+ absPath:
+ 'https://sentry.io/hiventy/kraken-prod/issues/438681831/?referrer=slack#',
+ inApp: false,
+ instructionAddr: null,
+ filename: '/hiventy/kraken-prod/issues/438681831/',
+ platform: null,
+ context: [],
+ symbolAddr: null,
+ },
+ ],
+ framesOmitted: null,
+ registers: null,
+ hasSystemFrames: false,
+ },
+ module: null,
+ rawStacktrace: null,
+ mechanism: null,
+ threadId: null,
+ value: 'Unexpected token else',
+ type: 'SyntaxError',
+ },
+ ],
+ excOmitted: null,
+ hasSystemFrames: false,
+ },
+ }),
+ MockEventEntry({
+ type: EntryType.BREADCRUMBS,
+ data: {
+ values: [
+ {
+ category: 'xhr',
+ level: 'info',
+ event_id: null,
+ timestamp: '2018-01-23T08:12:53.591Z',
+ data: {
+ url: 'https://reload.getsentry.net/page/',
+ status_code: '201',
+ method: 'POST',
+ },
+ message: null,
+ type: 'http',
+ },
+ {
+ category: 'xhr',
+ level: 'info',
+ event_id: null,
+ timestamp: '2018-01-23T08:12:53.636Z',
+ data: {
+ url: '/api/0/organizations/?member=1',
+ status_code: '200',
+ method: 'GET',
+ },
+ message: null,
+ type: 'http',
+ },
+ {
+ category: 'xhr',
+ level: 'info',
+ event_id: null,
+ timestamp: '2018-01-23T08:12:53.895Z',
+ data: {url: '/api/0/internal/health/', status_code: '403', method: 'GET'},
+ message: null,
+ type: 'http',
+ },
+ ],
+ },
+ }),
+ MockEventEntry({
+ type: EntryType.REQUEST,
+ data: {
+ fragment: '',
+ cookies: [],
+ inferredContentType: null,
+ env: null,
+ headers: [
+ ['Referer', '[Filtered]'],
+ [
+ 'User-Agent',
+ 'Mozilla/5.0 (Linux; Android 7.0; ONEPLUS A3003 Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/56.0.2924.87 Mobile Safari/537.36',
+ ],
+ ],
+ url: 'https://sentry.io/hiventy/kraken-prod/issues/438681831/',
+ query: 'referrer=slack',
+ data: null,
+ method: null,
+ },
+ }),
+ ];
+}
diff --git a/fixtures/js-stubs/types.tsx b/fixtures/js-stubs/types.tsx
index 766117151caf07..64d6afc07ad0d6 100644
--- a/fixtures/js-stubs/types.tsx
+++ b/fixtures/js-stubs/types.tsx
@@ -54,6 +54,8 @@ type TestStubFixtures = {
DiscoverSavedQuery: OverridableStub;
DocIntegration: OverridableStub;
Entries: SimpleStub;
+ Entries123Base: OverridableStub;
+ Entries123Target: OverridableStub;
Environments: SimpleStub;
Event: OverridableStub;
EventAttachment: OverridableStub;
diff --git a/static/app/components/issueDiff/index.spec.tsx b/static/app/components/issueDiff/index.spec.tsx
index de27111ccecce9..97c71bc7263644 100644
--- a/static/app/components/issueDiff/index.spec.tsx
+++ b/static/app/components/issueDiff/index.spec.tsx
@@ -5,7 +5,8 @@ import {IssueDiff} from 'sentry/components/issueDiff';
jest.mock('sentry/api');
describe('IssueDiff', function () {
- const entries = TestStubs.Entries();
+ const entries123Target = TestStubs.Entries123Target();
+ const entries123Base = TestStubs.Entries123Base();
const api = new MockApiClient();
const project = TestStubs.Project();
@@ -25,7 +26,7 @@ describe('IssueDiff', function () {
MockApiClient.addMockResponse({
url: `/projects/org-slug/${project.slug}/events/123target/`,
body: {
- entries: entries[0],
+ entries: entries123Target,
},
});
@@ -33,7 +34,7 @@ describe('IssueDiff', function () {
url: `/projects/org-slug/${project.slug}/events/123base/`,
body: {
platform: 'javascript',
- entries: entries[1],
+ entries: entries123Base,
},
});
});
diff --git a/tests/js/sentry-test/loadFixtures.ts b/tests/js/sentry-test/loadFixtures.ts
index 89406257d50978..fae1d1ef8620b1 100644
--- a/tests/js/sentry-test/loadFixtures.ts
+++ b/tests/js/sentry-test/loadFixtures.ts
@@ -78,33 +78,35 @@ const extensions = ['.js', '.ts', '.tsx', '.json'];
const SPECIAL_MAPPING = {
AllAuthenticators: 'authenticators',
OrgRoleList: 'roleList',
- MetricsField: 'metrics',
- EventsStats: 'events',
+ BitbucketIntegrationConfig: 'integrationListDirectory',
DetailedEvents: 'events',
+ DiscoverSavedQuery: 'discover',
+ Entries123Base: 'entries',
+ Entries123Target: 'entries',
Events: 'events',
- OutcomesWithReason: 'outcomes',
- SentryAppComponentAsync: 'sentryAppComponent',
+ EventsStats: 'events',
EventStacktraceMessage: 'eventStacktraceException',
- MetricsTotalCountByReleaseIn24h: 'metrics',
- MetricsSessionUserCountByStatusByRelease: 'metrics',
- MOCK_RESP_VERBOSE: 'ruleConditions',
- SessionStatusCountByProjectInPeriod: 'sessions',
- SessionUserCountByStatusByRelease: 'sessions',
- SessionUserCountByStatus: 'sessions',
- SessionStatusCountByReleaseInPeriod: 'sessions',
- SessionsField: 'sessions',
- ProviderList: 'integrationListDirectory',
- BitbucketIntegrationConfig: 'integrationListDirectory',
GitHubIntegration: 'githubIntegration',
- GitHubIntegrationProvider: 'githubIntegrationProvider',
GitHubIntegrationConfig: 'integrationListDirectory',
+ GitHubIntegrationProvider: 'githubIntegrationProvider',
+ MetricsField: 'metrics',
+ MetricsSessionUserCountByStatusByRelease: 'metrics',
+ MetricsTotalCountByReleaseIn24h: 'metrics',
+ MOCK_RESP_VERBOSE: 'ruleConditions',
OrgOwnedApps: 'integrationListDirectory',
+ OutcomesWithReason: 'outcomes',
+ PluginListConfig: 'integrationListDirectory',
+ ProviderList: 'integrationListDirectory',
PublishedApps: 'integrationListDirectory',
+ SentryAppComponentAsync: 'sentryAppComponent',
SentryAppInstalls: 'integrationListDirectory',
- PluginListConfig: 'integrationListDirectory',
- DiscoverSavedQuery: 'discover',
- VercelProvider: 'vercelIntegration',
+ SessionsField: 'sessions',
+ SessionStatusCountByProjectInPeriod: 'sessions',
+ SessionStatusCountByReleaseInPeriod: 'sessions',
+ SessionUserCountByStatus: 'sessions',
+ SessionUserCountByStatusByRelease: 'sessions',
TagValues: 'tagvalues',
+ VercelProvider: 'vercelIntegration',
};
function tryRequire(dir: string, name: string): any {
|
577a0df554db16533fbb64d7cc584006e3006bdf
|
2024-01-25 22:41:26
|
Isabella Enriquez
|
ref(issues): Make auto-transition task batch size smaller (#63807)
| false
|
Make auto-transition task batch size smaller (#63807)
|
ref
|
diff --git a/src/sentry/tasks/auto_ongoing_issues.py b/src/sentry/tasks/auto_ongoing_issues.py
index 29d19e211b1e62..3e5e00408ae765 100644
--- a/src/sentry/tasks/auto_ongoing_issues.py
+++ b/src/sentry/tasks/auto_ongoing_issues.py
@@ -22,7 +22,7 @@
TRANSITION_AFTER_DAYS = 7
ITERATOR_CHUNK = 100
-CHILD_TASK_COUNT = 250
+CHILD_TASK_COUNT = 10
def log_error_if_queue_has_items(func):
|
92e31b8da7b68953f35622e74844b02551686b8d
|
2024-12-14 06:45:15
|
Cathy Teng
|
chore(utils): allow duplicate values in registry by making reverse lookup optional (#82114)
| false
|
allow duplicate values in registry by making reverse lookup optional (#82114)
|
chore
|
diff --git a/src/sentry/utils/registry.py b/src/sentry/utils/registry.py
index 0ff110e268e054..3eff6865e82051 100644
--- a/src/sentry/utils/registry.py
+++ b/src/sentry/utils/registry.py
@@ -15,9 +15,15 @@ class NoRegistrationExistsError(ValueError):
class Registry(Generic[T]):
- def __init__(self):
+ """
+ A simple generic registry that allows for registering and retrieving items by key. Reverse lookup by value is enabled by default.
+ If you have duplicate values, you may want to disable reverse lookup.
+ """
+
+ def __init__(self, enable_reverse_lookup=True):
self.registrations: dict[str, T] = {}
self.reverse_lookup: dict[T, str] = {}
+ self.enable_reverse_lookup = enable_reverse_lookup
def register(self, key: str):
def inner(item: T) -> T:
@@ -26,13 +32,14 @@ def inner(item: T) -> T:
f"A registration already exists for {key}: {self.registrations[key]}"
)
- if item in self.reverse_lookup:
- raise AlreadyRegisteredError(
- f"A registration already exists for {item}: {self.reverse_lookup[item]}"
- )
+ if self.enable_reverse_lookup:
+ if item in self.reverse_lookup:
+ raise AlreadyRegisteredError(
+ f"A registration already exists for {item}: {self.reverse_lookup[item]}"
+ )
+ self.reverse_lookup[item] = key
self.registrations[key] = item
- self.reverse_lookup[item] = key
return item
@@ -44,6 +51,8 @@ def get(self, key: str) -> T:
return self.registrations[key]
def get_key(self, item: T) -> str:
+ if not self.enable_reverse_lookup:
+ raise NotImplementedError("Reverse lookup is not enabled")
if item not in self.reverse_lookup:
raise NoRegistrationExistsError(f"No registration exists for {item}")
return self.reverse_lookup[item]
diff --git a/tests/sentry/utils/test_registry.py b/tests/sentry/utils/test_registry.py
index 2f3415c288fd04..cbb886a7884ca8 100644
--- a/tests/sentry/utils/test_registry.py
+++ b/tests/sentry/utils/test_registry.py
@@ -33,3 +33,23 @@ def unregistered_func():
test_registry.register("something else")(unregistered_func)
assert test_registry.get("something else") == unregistered_func
+
+ def test_allow_duplicate_values(self):
+ test_registry = Registry[str](enable_reverse_lookup=False)
+
+ @test_registry.register("something")
+ @test_registry.register("something 2")
+ def registered_func():
+ pass
+
+ assert test_registry.get("something") == registered_func
+ assert test_registry.get("something 2") == registered_func
+
+ with pytest.raises(NoRegistrationExistsError):
+ test_registry.get("something else")
+
+ with pytest.raises(NotImplementedError):
+ test_registry.get_key(registered_func)
+
+ test_registry.register("something else")(registered_func)
+ assert test_registry.get("something else") == registered_func
|
a502309b17446ad85a65d9b8f9b8cd9156293ebd
|
2024-01-13 01:06:08
|
Malachi Willey
|
feat(code-mappings): Add new function for applying code mappings to stack frames (try 2) (#63128)
| false
|
Add new function for applying code mappings to stack frames (try 2) (#63128)
|
feat
|
diff --git a/src/sentry/integrations/utils/code_mapping.py b/src/sentry/integrations/utils/code_mapping.py
index 09b712ef274380..c5e37ee6d72e29 100644
--- a/src/sentry/integrations/utils/code_mapping.py
+++ b/src/sentry/integrations/utils/code_mapping.py
@@ -8,6 +8,7 @@
from sentry.models.project import Project
from sentry.models.repository import Repository
from sentry.services.hybrid_cloud.integration.model import RpcOrganizationIntegration
+from sentry.utils.event_frames import EventFrame, try_munge_frame_path
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
@@ -100,6 +101,38 @@ def filter_source_code_files(files: List[str]) -> List[str]:
return _supported_files
+def convert_stacktrace_frame_path_to_source_path(
+ frame: EventFrame,
+ code_mapping: RepositoryProjectPathConfig,
+ platform: str | None,
+ sdk_name: str | None,
+) -> str | None:
+ """
+ Applies the given code mapping to the given stacktrace frame and returns the source path.
+
+ If the code mapping does not apply to the frame, returns None.
+ """
+
+ # In most cases, code mappings get applied to frame.filename, but some platforms such as Java
+ # contain folder info in other parts of the frame (e.g. frame.module="com.example.app.MainActivity"
+ # gets transformed to "com/example/app/MainActivity.java"), so in those cases we use the
+ # transformed path instead.
+ stacktrace_path = (
+ try_munge_frame_path(frame=frame, platform=platform, sdk_name=sdk_name) or frame.filename
+ )
+
+ if stacktrace_path and stacktrace_path.startswith(code_mapping.stack_root):
+ return stacktrace_path.replace(code_mapping.stack_root, code_mapping.source_root, 1)
+
+ # Some platforms only provide the file's name without folder paths, so we
+ # need to use the absolute path instead. If the code mapping has a non-empty
+ # stack_root value and it matches the absolute path, we do the mapping on it.
+ if frame.abs_path and frame.abs_path.startswith(code_mapping.stack_root):
+ return frame.abs_path.replace(code_mapping.stack_root, code_mapping.source_root, 1)
+
+ return None
+
+
# XXX: Look at sentry.interfaces.stacktrace and maybe use that
class FrameFilename:
def __init__(self, frame_file_path: str) -> None:
@@ -433,6 +466,7 @@ def get_sorted_code_mapping_configs(project: Project) -> List[RepositoryProjectP
"""
Returns the code mapping config list for a project sorted based on precedence.
User generated code mappings are evaluated before Sentry generated code mappings.
+ Code mappings with absolute path stack roots are evaluated before relative path stack roots.
Code mappings with more defined stack trace roots are evaluated before less defined stack trace
roots.
@@ -455,10 +489,15 @@ def get_sorted_code_mapping_configs(project: Project) -> List[RepositoryProjectP
for index, sorted_config in enumerate(sorted_configs):
# This check will ensure that all user defined code mappings will come before Sentry generated ones
if (
- sorted_config.automatically_generated and not config.automatically_generated
- ) or ( # Insert more defined stack roots before less defined ones
- (sorted_config.automatically_generated == config.automatically_generated)
- and config.stack_root.startswith(sorted_config.stack_root)
+ (sorted_config.automatically_generated and not config.automatically_generated)
+ or ( # Insert absolute paths before relative paths
+ not sorted_config.stack_root.startswith("/")
+ and config.stack_root.startswith("/")
+ )
+ or ( # Insert more defined stack roots before less defined ones
+ (sorted_config.automatically_generated == config.automatically_generated)
+ and config.stack_root.startswith(sorted_config.stack_root)
+ )
):
sorted_configs.insert(index, config)
inserted = True
diff --git a/src/sentry/utils/event_frames.py b/src/sentry/utils/event_frames.py
index 0a02bd16e87299..c6a3e8b6b36d99 100644
--- a/src/sentry/utils/event_frames.py
+++ b/src/sentry/utils/event_frames.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import inspect
from copy import deepcopy
from dataclasses import dataclass, field
from typing import (
@@ -18,10 +19,25 @@
from sentry.utils.safe import PathSearchable, get_path
+@dataclass(frozen=True)
+class EventFrame:
+ lineno: Optional[int] = None
+ in_app: Optional[bool] = None
+ abs_path: Optional[str] = None
+ filename: Optional[str] = None
+ function: Optional[str] = None
+ package: Optional[str] = None
+ module: Optional[str] = None
+
+ @classmethod
+ def from_dict(cls, data: Mapping[str, Any]) -> EventFrame:
+ return cls(**{k: v for k, v in data.items() if k in inspect.signature(cls).parameters})
+
+
# mypy hack to work around callable assuing the first arg of callable is 'self'
# https://github.com/python/mypy/issues/5485
class FrameMunger(Protocol):
- def __call__(self, key: str, frame: MutableMapping[str, Any]) -> bool:
+ def __call__(self, frame: EventFrame) -> str | None:
pass
@@ -32,51 +48,48 @@ class SdkFrameMunger:
supported_sdks: Set[str] = field(default_factory=set)
-def java_frame_munger(key: str, frame: MutableMapping[str, Any]) -> bool:
- if frame.get("filename") is None or frame.get("module") is None:
- return False
- if "/" not in str(frame.get("filename")) and frame.get("module"):
+def java_frame_munger(frame: EventFrame) -> str | None:
+ if not frame.filename or not frame.module:
+ return None
+ if "/" not in str(frame.filename) and frame.module:
# Replace the last module segment with the filename, as the
# terminal element in a module path is the class
- module = frame["module"].split(".")
- module[-1] = frame["filename"]
- frame[key] = "/".join(module)
- return True
- return False
+ module = frame.module.split(".")
+ module[-1] = frame.filename
+ return "/".join(module)
+ return None
-def cocoa_frame_munger(key: str, frame: MutableMapping[str, Any]) -> bool:
- if not frame.get("package") or not frame.get("abs_path"):
- return False
+def cocoa_frame_munger(frame: EventFrame) -> str | None:
+ if not frame.package or not frame.abs_path:
+ return None
- rel_path = package_relative_path(frame.get("abs_path"), frame.get("package"))
+ rel_path = package_relative_path(frame.abs_path, frame.package)
if rel_path:
- frame[key] = rel_path
- return True
- return False
+ return rel_path
+ return None
-def flutter_frame_munger(key: str, frame: MutableMapping[str, Any]) -> bool:
- if not frame.get("abs_path"):
- return False
+def flutter_frame_munger(frame: EventFrame) -> str | None:
+ if not frame.abs_path:
+ return None
- abs_path = str(frame.get("abs_path"))
+ abs_path = str(frame.abs_path)
if abs_path.startswith("dart:"):
- return False
+ return None
elif abs_path.startswith("package:"):
- if not frame.get("package"):
- return False
+ if not frame.package:
+ return None
- pkg = frame.get("package")
+ pkg = frame.package
if abs_path.find(f"package:{pkg}") == -1:
- return False
+ return None
else:
src_path = abs_path.replace(f"package:{pkg}", "", 1).strip("/")
if src_path:
- frame[key] = src_path
- return True
- return False
+ return src_path
+ return None
def package_relative_path(abs_path: str | None, package: str | None) -> str | None:
@@ -106,6 +119,23 @@ def get_sdk_name(event_data: PathSearchable) -> Optional[str]:
return get_path(event_data, "sdk", "name", filter=True) or None
+def try_munge_frame_path(
+ frame: EventFrame,
+ platform: str | None = None,
+ sdk_name: str | None = None,
+) -> str | None:
+ """
+ Applies platform-specific frame munging for filename pathing.
+
+ If munging was successful, return the munged filename, otherwise return None.
+ """
+ munger = platform and PLATFORM_FRAME_MUNGER.get(platform)
+ if not munger or (munger.requires_sdk and sdk_name not in munger.supported_sdks):
+ return None
+
+ return munger.frame_munger(frame)
+
+
def munged_filename_and_frames(
platform: str,
data_frames: Sequence[Mapping[str, Any]],
@@ -127,7 +157,10 @@ def munged_filename_and_frames(
)
frames_updated = False
for frame in copy_frames:
- frames_updated |= munger.frame_munger(key, frame)
+ munged_filename = munger.frame_munger(EventFrame.from_dict(frame))
+ if munged_filename:
+ frame[key] = munged_filename
+ frames_updated = True
return (key, copy_frames) if frames_updated else None
diff --git a/tests/sentry/integrations/utils/test_code_mapping.py b/tests/sentry/integrations/utils/test_code_mapping.py
index af9e58e679c37c..c4ea25175fd475 100644
--- a/tests/sentry/integrations/utils/test_code_mapping.py
+++ b/tests/sentry/integrations/utils/test_code_mapping.py
@@ -9,6 +9,7 @@
Repo,
RepoTree,
UnsupportedFrameFilename,
+ convert_stacktrace_frame_path_to_source_path,
filter_source_code_files,
get_extension,
get_sorted_code_mapping_configs,
@@ -19,6 +20,7 @@
from sentry.silo.base import SiloMode
from sentry.testutils.cases import TestCase
from sentry.testutils.silo import assume_test_silo_mode
+from sentry.utils.event_frames import EventFrame
sentry_files = [
"bin/__init__.py",
@@ -328,6 +330,77 @@ def test_normalized_stack_and_source_roots_starts_with_app_dot_dot_slash(self):
assert source_path == ""
+class TestConvertStacktraceFramePathToSourcePath(TestCase):
+ def setUp(self):
+ super()
+ with assume_test_silo_mode(SiloMode.CONTROL):
+ self.integration = self.create_provider_integration(provider="example", name="Example")
+ self.integration.add_organization(self.organization, self.user)
+ self.oi = OrganizationIntegration.objects.get(integration_id=self.integration.id)
+
+ self.repo = self.create_repo(
+ project=self.project,
+ name="getsentry/sentry",
+ )
+
+ self.code_mapping_empty = self.create_code_mapping(
+ organization_integration=self.oi,
+ project=self.project,
+ repo=self.repo,
+ stack_root="",
+ source_root="src/",
+ )
+ self.code_mapping_abs_path = self.create_code_mapping(
+ organization_integration=self.oi,
+ project=self.project,
+ repo=self.repo,
+ stack_root="/Users/Foo/src/sentry/",
+ source_root="src/sentry/",
+ )
+ self.code_mapping_file = self.create_code_mapping(
+ organization_integration=self.oi,
+ project=self.project,
+ repo=self.repo,
+ stack_root="sentry/",
+ source_root="src/sentry/",
+ )
+
+ def test_convert_stacktrace_frame_path_to_source_path_empty(self):
+ assert (
+ convert_stacktrace_frame_path_to_source_path(
+ frame=EventFrame(filename="sentry/file.py"),
+ code_mapping=self.code_mapping_empty,
+ platform="python",
+ sdk_name="sentry.python",
+ )
+ == "src/sentry/file.py"
+ )
+
+ def test_convert_stacktrace_frame_path_to_source_path_abs_path(self):
+ assert (
+ convert_stacktrace_frame_path_to_source_path(
+ frame=EventFrame(
+ filename="file.py", abs_path="/Users/Foo/src/sentry/folder/file.py"
+ ),
+ code_mapping=self.code_mapping_abs_path,
+ platform="python",
+ sdk_name="sentry.python",
+ )
+ == "src/sentry/folder/file.py"
+ )
+
+ def test_convert_stacktrace_frame_path_to_source_path_java(self):
+ assert (
+ convert_stacktrace_frame_path_to_source_path(
+ frame=EventFrame(filename="File.java", module="sentry.module.File"),
+ code_mapping=self.code_mapping_file,
+ platform="java",
+ sdk_name="sentry.java",
+ )
+ == "src/sentry/module/File.java"
+ )
+
+
class TestGetSortedCodeMappingConfigs(TestCase):
def setUp(self):
super()
@@ -390,9 +463,19 @@ def test_get_sorted_code_mapping_configs(self):
source_root="",
automatically_generated=True,
)
+ # Created by user, well defined stack root that references abs_path
+ code_mapping6 = self.create_code_mapping(
+ organization_integration=self.oi,
+ project=self.project,
+ repo=self.repo,
+ stack_root="/Users/User/code/src/getsentry/src/sentry/",
+ source_root="",
+ automatically_generated=False,
+ )
# Expected configs: stack_root, automatically_generated
expected_config_order = [
+ code_mapping6, # "/Users/User/code/src/getsentry/src/sentry/", False
code_mapping3, # "usr/src/getsentry/", False
code_mapping4, # "usr/src/", False
code_mapping1, # "", False
diff --git a/tests/sentry/utils/test_event_frames.py b/tests/sentry/utils/test_event_frames.py
index 6326c15d0b5f19..cec3fb12343972 100644
--- a/tests/sentry/utils/test_event_frames.py
+++ b/tests/sentry/utils/test_event_frames.py
@@ -2,6 +2,7 @@
from sentry.testutils.cases import TestCase
from sentry.utils.event_frames import (
+ EventFrame,
cocoa_frame_munger,
find_stack_frames,
flutter_frame_munger,
@@ -279,34 +280,27 @@ def test_simple(self):
"symbol_addr": "0x102ce2b70",
}
- did_munge = cocoa_frame_munger("munged_filename", exception_frame)
- assert did_munge
- assert (
- exception_frame["munged_filename"]
- == "SampleProject/Classes/App Delegate/AppDelegate.swift"
- )
+ munged_filename = cocoa_frame_munger(EventFrame.from_dict(exception_frame))
+ assert munged_filename == "SampleProject/Classes/App Delegate/AppDelegate.swift"
def test_missing_required_no_munging(self):
assert cocoa_frame_munger(
- "munged_filename",
- {
- "package": "SampleProject",
- "abs_path": "SampleProject/AppDelegate.swift",
- },
+ EventFrame(
+ package="SampleProject",
+ abs_path="SampleProject/AppDelegate.swift",
+ )
)
- assert not cocoa_frame_munger("munged_filename", {})
+ assert not cocoa_frame_munger(EventFrame())
assert not cocoa_frame_munger(
- "munged_filename",
- {
- "package": "SampleProject",
- },
+ EventFrame(
+ package="SampleProject",
+ )
)
assert not cocoa_frame_munger(
- "munged_filename",
- {
- "abs_path": "SampleProject/AppDelegate.swift",
- },
+ EventFrame(
+ abs_path="SampleProject/AppDelegate.swift",
+ )
)
def test_package_relative_repeats(self):
@@ -316,10 +310,9 @@ def test_package_relative_repeats(self):
"abs_path": "/Users/gszeto/code/SampleProject/more/dirs/SwiftySampleProject/SampleProject/Classes/App Delegate/AppDelegate.swift",
}
- did_munge = cocoa_frame_munger("munged_filename", exception_frame)
- assert did_munge
+ munged_filename = cocoa_frame_munger(EventFrame.from_dict(exception_frame))
assert (
- exception_frame["munged_filename"]
+ munged_filename
== "SampleProject/more/dirs/SwiftySampleProject/SampleProject/Classes/App Delegate/AppDelegate.swift"
)
@@ -416,37 +409,31 @@ def test_flutter_munger_supported(self):
def test_dart_prefix_not_munged(self):
assert not flutter_frame_munger(
- "munged_filename",
- {
- "abs_path": "dart:ui/a/b/test.dart",
- },
+ EventFrame(abs_path="dart:ui/a/b/test.dart"),
)
def test_abs_path_not_present_not_munged(self):
assert not flutter_frame_munger(
- "munged_filename",
- {
- "function": "tryCatchModule",
- "package": "sentry_flutter_example",
- "filename": "test.dart",
- },
+ EventFrame(
+ function="tryCatchModule",
+ package="sentry_flutter_example",
+ filename="test.dart",
+ )
)
def test_different_package_not_munged(self):
assert not flutter_frame_munger(
- "munged_filename",
- {
- "package": "sentry_flutter_example",
- "abs_path": "package:different_package/a/b/test.dart",
- },
+ EventFrame(
+ package="sentry_flutter_example",
+ abs_path="package:different_package/a/b/test.dart",
+ )
)
def test_no_package_not_munged(self):
assert not flutter_frame_munger(
- "munged_filename",
- {
- "abs_path": "package:different_package/a/b/test.dart",
- },
+ EventFrame(
+ abs_path="package:different_package/a/b/test.dart",
+ )
)
|
fe9f7317cd35d06684d109d94c09e6ba1be6079d
|
2022-09-21 00:31:38
|
Malachi Willey
|
test(ui): Convert SmartSearchBar tests to RTL (#39020)
| false
|
Convert SmartSearchBar tests to RTL (#39020)
|
test
|
diff --git a/static/app/components/searchSyntax/renderer.tsx b/static/app/components/searchSyntax/renderer.tsx
index f5265def843dfa..e168d3e51c6b3c 100644
--- a/static/app/components/searchSyntax/renderer.tsx
+++ b/static/app/components/searchSyntax/renderer.tsx
@@ -134,7 +134,12 @@ const FilterToken = ({
forceVisible
skipWrapper
>
- <Filter ref={filterElementRef} active={isActive} invalid={showInvalid}>
+ <Filter
+ ref={filterElementRef}
+ active={isActive}
+ invalid={showInvalid}
+ data-test-id={showInvalid ? 'filter-token-invalid' : 'filter-token'}
+ >
{filter.negated && <Negation>!</Negation>}
<KeyToken token={filter.key} negated={filter.negated} />
{filter.operator && <Operator>{filter.operator}</Operator>}
diff --git a/static/app/components/smartSearchBar/index.spec.jsx b/static/app/components/smartSearchBar/index.spec.jsx
index 7d19012c3a977c..ce7a2f040dec94 100644
--- a/static/app/components/smartSearchBar/index.spec.jsx
+++ b/static/app/components/smartSearchBar/index.spec.jsx
@@ -1,5 +1,5 @@
-import {mountWithTheme} from 'sentry-test/enzyme';
import {
+ act,
fireEvent,
render,
screen,
@@ -7,31 +7,17 @@ import {
waitFor,
} from 'sentry-test/reactTestingLibrary';
-import {Client} from 'sentry/api';
import {SmartSearchBar} from 'sentry/components/smartSearchBar';
-import {ShortcutType} from 'sentry/components/smartSearchBar/types';
-import {shortcuts} from 'sentry/components/smartSearchBar/utils';
import TagStore from 'sentry/stores/tagStore';
import {FieldKey} from 'sentry/utils/fields';
describe('SmartSearchBar', function () {
- let defaultProps, location, options, organization, supportedTags;
- let environmentTagValuesMock;
- const tagValuesMock = jest.fn(() => Promise.resolve([]));
-
- const mockCursorPosition = (component, pos) => {
- delete component.cursorPosition;
- Object.defineProperty(component, 'cursorPosition', {
- get: jest.fn().mockReturnValue(pos),
- configurable: true,
- });
- };
+ let defaultProps;
beforeEach(function () {
TagStore.reset();
TagStore.loadTagsSuccess(TestStubs.Tags());
- tagValuesMock.mockClear();
- supportedTags = TagStore.getState();
+ const supportedTags = TagStore.getState();
supportedTags.firstRelease = {
key: 'firstRelease',
name: 'firstRelease',
@@ -41,32 +27,20 @@ describe('SmartSearchBar', function () {
name: 'is',
};
- organization = TestStubs.Organization({id: '123'});
+ const organization = TestStubs.Organization({id: '123'});
- location = {
+ const location = {
pathname: '/organizations/org-slug/recent-searches/',
query: {
projectId: '0',
},
};
- options = TestStubs.routerContext([
- {
- organization,
- location,
- router: {location},
- },
- ]);
-
MockApiClient.clearMockResponses();
MockApiClient.addMockResponse({
url: '/organizations/org-slug/recent-searches/',
body: [],
});
- environmentTagValuesMock = MockApiClient.addMockResponse({
- url: '/projects/123/456/tags/environment/values/',
- body: [],
- });
defaultProps = {
query: '',
@@ -137,7 +111,9 @@ describe('SmartSearchBar', function () {
const textbox = screen.getByRole('textbox');
userEvent.type(textbox, 'bro');
- expect(await screen.findByTestId('search-autocomplete-item')).toBeInTheDocument();
+ expect(
+ await screen.findByRole('option', {name: 'bro wser - field'})
+ ).toBeInTheDocument();
// down once to 'browser' dropdown item
userEvent.keyboard('{ArrowDown}{Tab}');
@@ -160,7 +136,9 @@ describe('SmartSearchBar', function () {
const textbox = screen.getByRole('textbox');
userEvent.type(textbox, 'bro');
- expect(await screen.findByTestId('search-autocomplete-item')).toBeInTheDocument();
+ expect(
+ await screen.findByRole('option', {name: 'bro wser - field'})
+ ).toBeInTheDocument();
// down once to 'browser' dropdown item
userEvent.keyboard('{ArrowDown}{Enter}');
@@ -175,6 +153,19 @@ describe('SmartSearchBar', function () {
expect(onSearchMock).not.toHaveBeenCalled();
});
+ it('searches and completes tags with negation operator', async function () {
+ render(<SmartSearchBar {...defaultProps} />);
+
+ const textbox = screen.getByRole('textbox');
+ userEvent.type(textbox, '!bro');
+
+ const field = await screen.findByRole('option', {name: 'bro wser - field'});
+
+ userEvent.click(field);
+
+ expect(textbox).toHaveValue('!browser:');
+ });
+
describe('componentWillReceiveProps()', function () {
it('should add a space when setting query', function () {
render(<SmartSearchBar {...defaultProps} query="one" />);
@@ -319,299 +310,154 @@ describe('SmartSearchBar', function () {
expect(screen.getByRole('textbox')).toHaveValue('');
});
- describe('updateAutoCompleteItems()', function () {
- beforeEach(function () {
- jest.useFakeTimers();
- });
- it('sets state when empty', function () {
- const props = {
- query: '',
- organization,
- location,
- supportedTags,
- };
- const searchBar = mountWithTheme(<SmartSearchBar {...props} />, options).instance();
- searchBar.updateAutoCompleteItems();
- expect(searchBar.state.searchTerm).toEqual('');
- expect(searchBar.state.searchGroups).toEqual([]);
- expect(searchBar.state.activeSearchItem).toEqual(-1);
- });
+ it('does not fetch tag values with environment tag and excludeEnvironment', function () {
+ jest.useFakeTimers('modern');
- it('sets state when incomplete tag', async function () {
- const props = {
- query: 'fu',
- organization,
- location,
- supportedTags,
- };
- jest.useRealTimers();
- const wrapper = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = wrapper.instance();
- wrapper.find('textarea').simulate('focus');
- searchBar.updateAutoCompleteItems();
- await tick();
- wrapper.update();
- expect(searchBar.state.searchTerm).toEqual('fu');
- expect(searchBar.state.searchGroups).toEqual([
- expect.objectContaining({children: []}),
- ]);
- expect(searchBar.state.activeSearchItem).toEqual(-1);
- });
+ const getTagValuesMock = jest.fn().mockResolvedValue([]);
- it('sets state when incomplete tag has negation operator', async function () {
- const props = {
- query: '!fu',
- organization,
- location,
- supportedTags,
- };
- jest.useRealTimers();
- const wrapper = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = wrapper.instance();
- wrapper.find('textarea').simulate('focus');
- searchBar.updateAutoCompleteItems();
- await tick();
- wrapper.update();
- expect(searchBar.state.searchTerm).toEqual('fu');
- expect(searchBar.state.searchGroups).toEqual([
- expect.objectContaining({children: []}),
- ]);
- expect(searchBar.state.activeSearchItem).toEqual(-1);
- });
+ render(
+ <SmartSearchBar
+ {...defaultProps}
+ onGetTagValues={getTagValuesMock}
+ excludeEnvironment
+ />
+ );
- it('sets state when incomplete tag as second textarea', async function () {
- const props = {
- query: 'is:unresolved fu',
- organization,
- location,
- supportedTags,
- };
- jest.useRealTimers();
- const wrapper = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = wrapper.instance();
- // Cursor is at end of line
- mockCursorPosition(searchBar, 15);
- searchBar.updateAutoCompleteItems();
- await tick();
- wrapper.update();
- expect(searchBar.state.searchTerm).toEqual('fu');
- // 2 items because of headers ("Tags")
- expect(searchBar.state.searchGroups).toHaveLength(1);
- expect(searchBar.state.activeSearchItem).toEqual(-1);
- });
+ const textbox = screen.getByRole('textbox');
+ userEvent.type(textbox, 'environment:');
- it('does not request values when tag is environments', function () {
- const props = {
- query: 'environment:production',
- excludeEnvironment: true,
- location,
- organization,
- supportedTags,
- };
- const searchBar = mountWithTheme(<SmartSearchBar {...props} />, options).instance();
- searchBar.updateAutoCompleteItems();
- jest.advanceTimersByTime(301);
- expect(environmentTagValuesMock).not.toHaveBeenCalled();
+ act(() => {
+ jest.runOnlyPendingTimers();
});
- it('does not request values when tag is `timesSeen`', function () {
- // This should never get called
- const mock = MockApiClient.addMockResponse({
- url: '/projects/123/456/tags/timesSeen/values/',
- body: [],
- });
- const props = {
- query: 'timesSeen:',
- organization,
- supportedTags,
- };
- const searchBar = mountWithTheme(
- <SmartSearchBar {...props} api={new Client()} />,
- options
- ).instance();
- searchBar.updateAutoCompleteItems();
- jest.advanceTimersByTime(301);
- expect(mock).not.toHaveBeenCalled();
- });
+ expect(getTagValuesMock).not.toHaveBeenCalled();
+ });
- it('requests values when tag is `firstRelease`', function () {
- const mock = MockApiClient.addMockResponse({
- url: '/organizations/org-slug/releases/',
- body: [],
- });
- const props = {
- orgId: 'org-slug',
- projectId: '0',
- query: 'firstRelease:',
- location,
- organization,
- supportedTags,
- };
-
- const searchBar = mountWithTheme(
- <SmartSearchBar {...props} api={new Client()} />,
- options
- ).instance();
- mockCursorPosition(searchBar, 13);
- searchBar.updateAutoCompleteItems();
-
- jest.advanceTimersByTime(301);
- expect(mock).toHaveBeenCalledWith(
- '/organizations/org-slug/releases/',
- expect.objectContaining({
- method: 'GET',
- query: {
- project: '0',
- per_page: 5, // Limit results to 5 for autocomplete
- },
- })
- );
- });
+ it('does not fetch tag values with timesSeen tag', function () {
+ jest.useFakeTimers('modern');
- it('shows operator autocompletion', async function () {
- const props = {
- query: 'is:unresolved',
- organization,
- location,
- supportedTags,
- };
- jest.useRealTimers();
- const wrapper = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = wrapper.instance();
- // Cursor is on ':'
- mockCursorPosition(searchBar, 3);
- searchBar.updateAutoCompleteItems();
- await tick();
- wrapper.update();
- // two search groups because of operator suggestions
- expect(searchBar.state.searchGroups).toHaveLength(2);
- expect(searchBar.state.activeSearchItem).toEqual(-1);
- });
+ const getTagValuesMock = jest.fn().mockResolvedValue([]);
- it('responds to cursor changes', async function () {
- const props = {
- query: 'is:unresolved',
- organization,
- location,
- supportedTags,
- };
- jest.useRealTimers();
- const wrapper = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = wrapper.instance();
- // Cursor is on ':'
- mockCursorPosition(searchBar, 3);
- searchBar.updateAutoCompleteItems();
- await tick();
- wrapper.update();
- // two search groups tags and values
- expect(searchBar.state.searchGroups).toHaveLength(2);
- expect(searchBar.state.activeSearchItem).toEqual(-1);
- mockCursorPosition(searchBar, 1);
- searchBar.updateAutoCompleteItems();
- await tick();
- wrapper.update();
- // one search group because showing tags
- expect(searchBar.state.searchGroups).toHaveLength(1);
- expect(searchBar.state.activeSearchItem).toEqual(-1);
- });
+ render(
+ <SmartSearchBar
+ {...defaultProps}
+ onGetTagValues={getTagValuesMock}
+ excludeEnvironment
+ />
+ );
- it('shows errors on incorrect tokens', function () {
- const props = {
- query: 'tag: is: has: ',
- organization,
- location,
- supportedTags,
- };
- jest.useRealTimers();
- const wrapper = mountWithTheme(<SmartSearchBar {...props} />, options);
- wrapper.find('Filter').forEach(filter => {
- expect(filter.prop('invalid')).toBe(true);
- });
+ const textbox = screen.getByRole('textbox');
+ userEvent.type(textbox, 'timesSeen:');
+
+ act(() => {
+ jest.runOnlyPendingTimers();
});
- it('handles autocomplete race conditions when cursor position changed', async function () {
- const props = {
- query: 'is:',
- organization,
- location,
- supportedTags,
- };
-
- jest.useFakeTimers();
- const wrapper = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = wrapper.instance();
- // Cursor is on ':'
- searchBar.generateValueAutocompleteGroup = jest.fn(
- () =>
- new Promise(resolve => {
- setTimeout(() => {
- resolve({
- searchItems: [],
- recentSearchItems: [],
- tagName: 'test',
- type: 'value',
- });
- }, [300]);
- })
- );
- mockCursorPosition(searchBar, 3);
- searchBar.updateAutoCompleteItems();
- jest.advanceTimersByTime(200);
+ expect(getTagValuesMock).not.toHaveBeenCalled();
+ });
- // Move cursor off of the place the update was called before it's done at 300ms
- mockCursorPosition(searchBar, 0);
+ it('fetches and displays tag values with other tags', function () {
+ jest.useFakeTimers();
- jest.advanceTimersByTime(101);
+ const getTagValuesMock = jest.fn().mockResolvedValue([]);
- // Get the pending promises to resolve
- await Promise.resolve();
- wrapper.update();
+ render(
+ <SmartSearchBar
+ {...defaultProps}
+ onGetTagValues={getTagValuesMock}
+ excludeEnvironment
+ />
+ );
- expect(searchBar.state.searchGroups).toHaveLength(0);
+ const textbox = screen.getByRole('textbox');
+ userEvent.type(textbox, 'browser:');
+
+ act(() => {
+ jest.runOnlyPendingTimers();
});
- it('handles race conditions when query changes from default state', async function () {
- const props = {
- query: '',
- organization,
- location,
- supportedTags,
- };
-
- jest.useFakeTimers();
- const wrapper = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = wrapper.instance();
- // Cursor is on ':'
- searchBar.getRecentSearches = jest.fn(
- () =>
- new Promise(resolve => {
- setTimeout(() => {
- resolve([]);
- }, [300]);
- })
- );
- mockCursorPosition(searchBar, 0);
- searchBar.updateAutoCompleteItems();
- jest.advanceTimersByTime(200);
+ expect(getTagValuesMock).toHaveBeenCalledTimes(1);
+ });
- // Change query before it's done at 300ms
- searchBar.updateQuery('is:');
+ it('shows correct options on cursor changes for keys and values', async function () {
+ jest.useFakeTimers();
- jest.advanceTimersByTime(101);
+ const getTagValuesMock = jest.fn().mockResolvedValue([]);
- // Get the pending promises to resolve
- await Promise.resolve();
- wrapper.update();
+ render(
+ <SmartSearchBar
+ {...defaultProps}
+ query="is:unresolved"
+ onGetTagValues={getTagValuesMock}
+ onGetRecentSearches={jest.fn().mockReturnValue([])}
+ />
+ );
- expect(searchBar.state.searchGroups).toHaveLength(0);
+ const textbox = screen.getByRole('textbox');
+
+ // Set cursor to beginning of "is" tag
+ textbox.setSelectionRange(0, 0);
+ userEvent.click(textbox);
+ act(() => {
+ jest.runAllTimers();
});
+ // Should show "Keys" section
+ expect(await screen.findByText('Keys')).toBeInTheDocument();
+
+ // Set cursor to middle of "is" tag
+ userEvent.keyboard('{ArrowRight}');
+ act(() => {
+ jest.runAllTimers();
+ });
+ // Should show "Keys" and NOT "Operator Helpers" or "Values"
+ expect(await screen.findByText('Keys')).toBeInTheDocument();
+ expect(screen.queryByText('Operator Helpers')).not.toBeInTheDocument();
+ expect(screen.queryByText('Values')).not.toBeInTheDocument();
+
+ // Set cursor to end of "is" tag
+ userEvent.keyboard('{ArrowRight}');
+ act(() => {
+ jest.runAllTimers();
+ });
+ // Should show "Tags" and "Operator Helpers" but NOT "Values"
+ expect(await screen.findByText('Keys')).toBeInTheDocument();
+ expect(screen.getByText('Operator Helpers')).toBeInTheDocument();
+ expect(screen.queryByText('Values')).not.toBeInTheDocument();
+
+ // Set cursor after the ":"
+ userEvent.keyboard('{ArrowRight}');
+ act(() => {
+ jest.runAllTimers();
+ });
+ // Should show "Values" and "Operator Helpers" but NOT "Keys"
+ expect(await screen.findByText('Values')).toBeInTheDocument();
+ expect(await screen.findByText('Operator Helpers')).toBeInTheDocument();
+ expect(screen.queryByText('Keys')).not.toBeInTheDocument();
+
+ // Set cursor inside value
+ userEvent.keyboard('{ArrowRight}');
+ act(() => {
+ jest.runAllTimers();
+ });
+ // Should show "Values" and NOT "Operator Helpers" or "Keys"
+ expect(await screen.findByText('Values')).toBeInTheDocument();
+ expect(screen.queryByText('Operator Helpers')).not.toBeInTheDocument();
+ expect(screen.queryByText('Keys')).not.toBeInTheDocument();
+ });
+
+ it('shows syntax error for incorrect tokens', function () {
+ render(<SmartSearchBar {...defaultProps} query="tag: is: has:" />);
- it('correctly groups nested keys', async function () {
- const props = {
- query: 'nest',
- organization,
- location,
- supportedTags: {
+ // Should have three invalid tokens (tag:, is:, and has:)
+ expect(screen.getAllByTestId('filter-token-invalid')).toHaveLength(3);
+ });
+
+ it('renders nested keys correctly', async function () {
+ const {container} = render(
+ <SmartSearchBar
+ {...defaultProps}
+ query=""
+ supportedTags={{
nested: {
key: 'nested',
name: 'nested',
@@ -620,200 +466,28 @@ describe('SmartSearchBar', function () {
key: 'nested.child',
name: 'nested.child',
},
- },
- };
- jest.useRealTimers();
- const wrapper = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = wrapper.instance();
- // Cursor is at end of line
- mockCursorPosition(searchBar, 4);
- searchBar.updateAutoCompleteItems();
- await tick();
- wrapper.update();
-
- expect(searchBar.state.searchGroups).toHaveLength(1);
- expect(searchBar.state.searchGroups[0].children).toHaveLength(1);
- expect(searchBar.state.searchGroups[0].children[0].title).toBe('nested');
- expect(searchBar.state.searchGroups[0].children[0].children).toHaveLength(1);
- expect(searchBar.state.searchGroups[0].children[0].children[0].title).toBe(
- 'nested.child'
- );
- });
-
- it('correctly groups nested keys without a parent', async function () {
- const props = {
- query: 'nest',
- organization,
- location,
- supportedTags: {
- 'nested.child1': {
- key: 'nested.child1',
- name: 'nested.child1',
- },
- 'nested.child2': {
- key: 'nested.child2',
- name: 'nested.child2',
+ 'nestednoparent.child': {
+ key: 'nestednoparent.child',
+ name: 'nestednoparent.child',
},
- },
- };
- jest.useRealTimers();
- const wrapper = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = wrapper.instance();
- // Cursor is at end of line
- mockCursorPosition(searchBar, 4);
- searchBar.updateAutoCompleteItems();
- await tick();
- wrapper.update();
-
- expect(searchBar.state.searchGroups).toHaveLength(1);
- expect(searchBar.state.searchGroups[0].children).toHaveLength(1);
- expect(searchBar.state.searchGroups[0].children[0].title).toBe('nested');
- expect(searchBar.state.searchGroups[0].children[0].children).toHaveLength(2);
- expect(searchBar.state.searchGroups[0].children[0].children[0].title).toBe(
- 'nested.child1'
- );
- expect(searchBar.state.searchGroups[0].children[0].children[1].title).toBe(
- 'nested.child2'
- );
- });
- });
-
- describe('cursorSearchTerm', function () {
- it('selects the correct free text word', async function () {
- jest.useRealTimers();
-
- const props = {
- query: '',
- organization,
- location,
- supportedTags,
- };
- const smartSearchBar = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = smartSearchBar.instance();
- const textarea = smartSearchBar.find('textarea');
-
- textarea.simulate('focus');
- mockCursorPosition(searchBar, 6);
- textarea.simulate('change', {target: {value: 'typ testest err'}});
- await tick();
-
- // Expect the correct search term to be selected
- const cursorSearchTerm = searchBar.cursorSearchTerm;
- expect(cursorSearchTerm.searchTerm).toEqual('testest');
- expect(cursorSearchTerm.start).toBe(4);
- expect(cursorSearchTerm.end).toBe(11);
- });
-
- it('selects the correct free text word (last word)', async function () {
- jest.useRealTimers();
-
- const props = {
- query: '',
- organization,
- location,
- supportedTags,
- };
- const smartSearchBar = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = smartSearchBar.instance();
- const textarea = smartSearchBar.find('textarea');
-
- textarea.simulate('focus');
- mockCursorPosition(searchBar, 15);
- textarea.simulate('change', {target: {value: 'typ testest err'}});
- await tick();
-
- // Expect the correct search term to be selected
- const cursorSearchTerm = searchBar.cursorSearchTerm;
- expect(cursorSearchTerm.searchTerm).toEqual('err');
- expect(cursorSearchTerm.start).toBe(15);
- expect(cursorSearchTerm.end).toBe(18);
- });
+ }}
+ />
+ );
- it('selects the correct free text word (first word)', async function () {
- jest.useRealTimers();
-
- const props = {
- query: '',
- organization,
- location,
- supportedTags,
- };
- const smartSearchBar = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = smartSearchBar.instance();
- const textarea = smartSearchBar.find('textarea');
-
- textarea.simulate('focus');
- mockCursorPosition(searchBar, 1);
- textarea.simulate('change', {target: {value: 'typ testest err'}});
- await tick();
-
- // Expect the correct search term to be selected
- const cursorSearchTerm = searchBar.cursorSearchTerm;
- expect(cursorSearchTerm.searchTerm).toEqual('typ');
- expect(cursorSearchTerm.start).toBe(0);
- expect(cursorSearchTerm.end).toBe(3);
- });
+ const textbox = screen.getByRole('textbox');
+ userEvent.type(textbox, 'nest');
- it('search term location correctly selects key of filter token', async function () {
- jest.useRealTimers();
-
- const props = {
- query: '',
- organization,
- location,
- supportedTags,
- };
- const smartSearchBar = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = smartSearchBar.instance();
- const textarea = smartSearchBar.find('textarea');
-
- textarea.simulate('focus');
- mockCursorPosition(searchBar, 6);
- textarea.simulate('change', {target: {value: 'typ device:123'}});
- await tick();
-
- // Expect the correct search term to be selected
- const cursorSearchTerm = searchBar.cursorSearchTerm;
- expect(cursorSearchTerm.searchTerm).toEqual('device');
- expect(cursorSearchTerm.start).toBe(4);
- expect(cursorSearchTerm.end).toBe(10);
- });
+ await screen.findByText('Keys');
- it('search term location correctly selects value of filter token', async function () {
- jest.useRealTimers();
-
- const props = {
- query: '',
- organization,
- location,
- supportedTags,
- };
- const smartSearchBar = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = smartSearchBar.instance();
- const textarea = smartSearchBar.find('textarea');
-
- textarea.simulate('focus');
- mockCursorPosition(searchBar, 11);
- textarea.simulate('change', {target: {value: 'typ device:123'}});
- await tick();
-
- // Expect the correct search term to be selected
- const cursorSearchTerm = searchBar.cursorSearchTerm;
- expect(cursorSearchTerm.searchTerm).toEqual('123');
- expect(cursorSearchTerm.start).toBe(11);
- expect(cursorSearchTerm.end).toBe(14);
- });
+ expect(container).toSnapshot();
});
- describe('getTagKeys()', function () {
- it('filters both keys and descriptions', async function () {
- jest.useRealTimers();
-
- const props = {
- query: 'event',
- organization,
- location,
- supportedTags: {
+ it('filters keys on name and description', async function () {
+ render(
+ <SmartSearchBar
+ {...defaultProps}
+ query=""
+ supportedTags={{
[FieldKey.DEVICE_CHARGING]: {
key: FieldKey.DEVICE_CHARGING,
},
@@ -823,447 +497,342 @@ describe('SmartSearchBar', function () {
[FieldKey.DEVICE_ARCH]: {
key: FieldKey.DEVICE_ARCH,
},
- },
- };
- const smartSearchBar = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = smartSearchBar.instance();
+ }}
+ />
+ );
- mockCursorPosition(searchBar, 3);
- searchBar.updateAutoCompleteItems();
+ const textbox = screen.getByRole('textbox');
+ userEvent.type(textbox, 'event');
- await tick();
+ await screen.findByText('Keys');
- expect(searchBar.state.flatSearchItems).toHaveLength(2);
- expect(searchBar.state.flatSearchItems[0].title).toBe(FieldKey.EVENT_TYPE);
- expect(searchBar.state.flatSearchItems[1].title).toBe(FieldKey.DEVICE_CHARGING);
- });
+ // Should show event.type (has event in key) and device.charging (has event in description)
+ expect(screen.getByRole('option', {name: /event . type/})).toBeInTheDocument();
+ expect(screen.getByRole('option', {name: /charging/})).toBeInTheDocument();
- it('filters only keys', async function () {
- jest.useRealTimers();
+ // But not device.arch (not in key or description)
+ expect(screen.queryByRole('option', {name: /arch/})).not.toBeInTheDocument();
+ });
- const props = {
- query: 'device',
- organization,
- location,
- supportedTags: {
- [FieldKey.DEVICE_CHARGING]: {
- key: FieldKey.DEVICE_CHARGING,
- },
- [FieldKey.EVENT_TYPE]: {
- key: FieldKey.EVENT_TYPE,
- },
- [FieldKey.DEVICE_ARCH]: {
- key: FieldKey.DEVICE_ARCH,
- },
- },
- };
- const smartSearchBar = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = smartSearchBar.instance();
+ it('handles autocomplete race conditions when cursor position changed', async function () {
+ jest.useFakeTimers();
+ const mockOnGetTagValues = jest.fn().mockImplementation(
+ () =>
+ new Promise(resolve => {
+ setTimeout(() => {
+ resolve(['value']);
+ }, [300]);
+ })
+ );
+
+ render(
+ <SmartSearchBar {...defaultProps} onGetTagValues={mockOnGetTagValues} query="" />
+ );
- mockCursorPosition(searchBar, 2);
- searchBar.updateAutoCompleteItems();
+ const textbox = screen.getByRole('textbox');
- await tick();
+ // Type key and start searching values
+ userEvent.type(textbox, 'is:');
- expect(searchBar.state.flatSearchItems).toHaveLength(2);
- expect(searchBar.state.flatSearchItems[0].title).toBe(FieldKey.DEVICE_ARCH);
- expect(searchBar.state.flatSearchItems[1].title).toBe(FieldKey.DEVICE_CHARGING);
+ act(() => {
+ jest.advanceTimersByTime(200);
});
- it('filters only descriptions', async function () {
- jest.useRealTimers();
+ // Before values have finished searching, clear the textbox
+ userEvent.clear(textbox);
- const props = {
- query: 'time',
- organization,
- location,
- supportedTags: {
- [FieldKey.DEVICE_CHARGING]: {
- key: FieldKey.DEVICE_CHARGING,
- },
- [FieldKey.EVENT_TYPE]: {
- key: FieldKey.EVENT_TYPE,
- },
- [FieldKey.DEVICE_ARCH]: {
- key: FieldKey.DEVICE_ARCH,
- },
- },
- };
- const smartSearchBar = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = smartSearchBar.instance();
+ act(() => {
+ jest.runAllTimers();
+ });
- mockCursorPosition(searchBar, 4);
- searchBar.updateAutoCompleteItems();
+ // Should show keys, not values in dropdown
+ expect(await screen.findByText('Keys')).toBeInTheDocument();
+ expect(screen.queryByText('Values')).not.toBeInTheDocument();
+ });
- await tick();
+ it('autocompletes tag values', async function () {
+ jest.useFakeTimers();
+ const mockOnChange = jest.fn();
- expect(searchBar.state.flatSearchItems).toHaveLength(1);
- expect(searchBar.state.flatSearchItems[0].title).toBe(FieldKey.DEVICE_CHARGING);
- });
- });
+ const getTagValuesMock = jest.fn().mockResolvedValue(['Chrome', 'Firefox']);
- describe('onAutoComplete()', function () {
- it('completes terms from the list', function () {
- const props = {
- query: 'event.type:error ',
- organization,
- location,
- supportedTags,
- };
- const searchBar = mountWithTheme(<SmartSearchBar {...props} />, options).instance();
- mockCursorPosition(searchBar, 'event.type:error '.length);
- searchBar.onAutoComplete('myTag:', {type: 'tag'});
- expect(searchBar.state.query).toEqual('event.type:error myTag:');
- });
+ render(
+ <SmartSearchBar
+ {...defaultProps}
+ onGetTagValues={getTagValuesMock}
+ query=""
+ onChange={mockOnChange}
+ />
+ );
- it('completes values if cursor is not at the end', function () {
- const props = {
- query: 'id: event.type:error ',
- organization,
- location,
- supportedTags,
- };
- const searchBar = mountWithTheme(<SmartSearchBar {...props} />, options).instance();
- mockCursorPosition(searchBar, 3);
- searchBar.onAutoComplete('12345', {type: 'tag-value'});
- expect(searchBar.state.query).toEqual('id:12345 event.type:error ');
- });
+ const textbox = screen.getByRole('textbox');
+ userEvent.type(textbox, 'browser:');
- it('completes values if cursor is at the end', function () {
- const props = {
- query: 'event.type:error id:',
- organization,
- location,
- supportedTags,
- };
- const searchBar = mountWithTheme(<SmartSearchBar {...props} />, options).instance();
- mockCursorPosition(searchBar, 20);
- searchBar.onAutoComplete('12345', {type: 'tag-value'});
- expect(searchBar.state.query).toEqual('event.type:error id:12345 ');
+ act(() => {
+ jest.runOnlyPendingTimers();
});
- it('triggers onChange', function () {
- const onChange = jest.fn();
- const props = {
- query: 'event.type:error id:',
- organization,
- location,
- supportedTags,
- };
- const searchBar = mountWithTheme(
- <SmartSearchBar {...props} onChange={onChange} />,
- options
- ).instance();
- mockCursorPosition(searchBar, 20);
- searchBar.onAutoComplete('12345', {type: 'tag-value'});
- expect(onChange).toHaveBeenCalledWith(
- 'event.type:error id:12345 ',
+ const option = await screen.findByRole('option', {name: /Firefox/});
+
+ userEvent.click(option);
+
+ await waitFor(() => {
+ expect(mockOnChange).toHaveBeenLastCalledWith(
+ 'browser:Firefox ',
expect.anything()
);
});
+ });
- it('keeps the negation operator present', async function () {
- jest.useRealTimers();
- const props = {
- query: '',
- organization,
- location,
- supportedTags,
- };
- const smartSearchBar = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = smartSearchBar.instance();
- const textarea = smartSearchBar.find('textarea');
- // start typing part of the tag prefixed by the negation operator!
- textarea.simulate('focus');
- textarea.simulate('change', {target: {value: 'event.type:error !ti'}});
- mockCursorPosition(searchBar, 20);
- await tick();
- // Expect the correct search term to be selected
- const cursorSearchTerm = searchBar.cursorSearchTerm;
- expect(cursorSearchTerm.searchTerm).toEqual('ti');
- expect(cursorSearchTerm.start).toBe(18);
- expect(cursorSearchTerm.end).toBe(20);
- // use autocompletion to do the rest
- searchBar.onAutoComplete('title:', {});
- expect(searchBar.state.query).toEqual('event.type:error !title:');
+ it('autocompletes tag values when there are other tags', async function () {
+ jest.useFakeTimers();
+ const mockOnChange = jest.fn();
+
+ const getTagValuesMock = jest.fn().mockResolvedValue(['Chrome', 'Firefox']);
+
+ render(
+ <SmartSearchBar
+ {...defaultProps}
+ onGetTagValues={getTagValuesMock}
+ excludeEnvironment
+ query="is:unresolved error.handled:true"
+ onChange={mockOnChange}
+ />
+ );
+
+ // Type "browser:" in between existing key/values
+ const textbox = screen.getByRole('textbox');
+ fireEvent.change(textbox, {
+ target: {value: 'is:unresolved browser: error.handled:true'},
});
- it('handles special case for user tag', function () {
- const props = {
- query: '',
- organization,
- location,
- supportedTags,
- };
- const smartSearchBar = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = smartSearchBar.instance();
- const textarea = smartSearchBar.find('textarea');
-
- textarea.simulate('change', {target: {value: 'user:'}});
- mockCursorPosition(searchBar, 5);
- searchBar.onAutoComplete('id:1', {});
- expect(searchBar.state.query).toEqual('user:"id:1" ');
+ // Make sure cursor is at end of "browser:""
+ textbox.setSelectionRange(
+ 'is:unresolved browser:'.length,
+ 'is:unresolved browser:'.length
+ );
+ userEvent.click(textbox);
+
+ act(() => {
+ jest.runOnlyPendingTimers();
});
- });
- it('quotes in predefined values with spaces when autocompleting', async function () {
- jest.useRealTimers();
- const onSearch = jest.fn();
- supportedTags.predefined = {
- key: 'predefined',
- name: 'predefined',
- predefined: true,
- values: ['predefined tag with spaces'],
- };
- const props = {
- orgId: 'org-slug',
- projectId: '0',
- query: '',
- location,
- organization,
- supportedTags,
- onSearch,
- };
- const searchBar = mountWithTheme(
- <SmartSearchBar {...props} api={new Client()} />,
+ const option = await screen.findByRole('option', {name: /Firefox/});
- options
- );
- searchBar.find('textarea').simulate('focus');
- searchBar
- .find('textarea')
- .simulate('change', {target: {value: 'predefined:predefined'}});
- await tick();
-
- const preventDefault = jest.fn();
- searchBar.find('textarea').simulate('keyDown', {key: 'ArrowDown'});
- searchBar.find('textarea').simulate('keyDown', {key: 'Enter', preventDefault});
- await tick();
-
- expect(searchBar.find('textarea').props().value).toEqual(
- 'predefined:"predefined tag with spaces" '
- );
- });
+ userEvent.click(option);
- it('escapes quotes in predefined values properly when autocompleting', async function () {
- jest.useRealTimers();
- const onSearch = jest.fn();
- supportedTags.predefined = {
- key: 'predefined',
- name: 'predefined',
- predefined: true,
- values: ['"predefined" "tag" "with" "quotes"'],
- };
- const props = {
- orgId: 'org-slug',
- projectId: '0',
- query: '',
- location,
- organization,
- supportedTags,
- onSearch,
- };
- const searchBar = mountWithTheme(
- <SmartSearchBar {...props} api={new Client()} />,
+ await waitFor(() => {
+ expect(mockOnChange).toHaveBeenLastCalledWith(
+ 'is:unresolved browser:Firefox error.handled:true',
+ expect.anything()
+ );
+ });
+ });
- options
- );
- searchBar.find('textarea').simulate('focus');
- searchBar
- .find('textarea')
- .simulate('change', {target: {value: 'predefined:predefined'}});
- await tick();
-
- const preventDefault = jest.fn();
- searchBar.find('textarea').simulate('keyDown', {key: 'ArrowDown'});
- searchBar.find('textarea').simulate('keyDown', {key: 'Enter', preventDefault});
- await tick();
-
- expect(searchBar.find('textarea').props().value).toEqual(
- 'predefined:"\\"predefined\\" \\"tag\\" \\"with\\" \\"quotes\\"" '
+ it('autocompletes tag values (user tag)', async function () {
+ jest.useFakeTimers();
+ const mockOnChange = jest.fn();
+ const getTagValuesMock = jest.fn().mockResolvedValue(['id:1']);
+
+ render(
+ <SmartSearchBar
+ {...defaultProps}
+ onGetTagValues={getTagValuesMock}
+ query=""
+ onChange={mockOnChange}
+ />
);
- });
- describe('quick actions', () => {
- it('delete first token', async () => {
- const props = {
- query: 'is:unresolved sdk.name:sentry-cocoa has:key',
- organization,
- location,
- supportedTags,
- };
- const searchBar = mountWithTheme(<SmartSearchBar {...props} />, options).instance();
- searchBar.updateAutoCompleteItems();
+ const textbox = screen.getByRole('textbox');
+ userEvent.type(textbox, 'user:');
- mockCursorPosition(searchBar, 1);
+ act(() => {
+ jest.runOnlyPendingTimers();
+ });
- await tick();
+ const option = await screen.findByRole('option', {name: /id:1/});
- const deleteAction = shortcuts.find(a => a.shortcutType === ShortcutType.Delete);
+ userEvent.click(option);
- expect(deleteAction).toBeDefined();
- if (deleteAction) {
- searchBar.runShortcut(deleteAction);
+ await waitFor(() => {
+ expect(mockOnChange).toHaveBeenLastCalledWith('user:"id:1" ', expect.anything());
+ });
+ });
- await tick();
+ it('autocompletes tag values (predefined values with spaces)', async function () {
+ jest.useFakeTimers();
+ const mockOnChange = jest.fn();
+
+ render(
+ <SmartSearchBar
+ {...defaultProps}
+ query=""
+ onChange={mockOnChange}
+ supportedTags={{
+ predefined: {
+ key: 'predefined',
+ name: 'predefined',
+ predefined: true,
+ values: ['predefined tag with spaces'],
+ },
+ }}
+ />
+ );
- expect(searchBar.state.query).toEqual('sdk.name:sentry-cocoa has:key');
- }
+ const textbox = screen.getByRole('textbox');
+ userEvent.type(textbox, 'predefined:');
+
+ act(() => {
+ jest.runOnlyPendingTimers();
});
- it('delete middle token', async () => {
- const props = {
- query: 'is:unresolved sdk.name:sentry-cocoa has:key',
- organization,
- location,
- supportedTags,
- };
- const searchBar = mountWithTheme(<SmartSearchBar {...props} />, options).instance();
- searchBar.updateAutoCompleteItems();
+ const option = await screen.findByRole('option', {
+ name: /predefined tag with spaces/,
+ });
- mockCursorPosition(searchBar, 18);
+ userEvent.click(option);
- await tick();
+ await waitFor(() => {
+ expect(mockOnChange).toHaveBeenLastCalledWith(
+ 'predefined:"predefined tag with spaces" ',
+ expect.anything()
+ );
+ });
+ });
- const deleteAction = shortcuts.find(a => a.shortcutType === ShortcutType.Delete);
+ it('autocompletes tag values (predefined values with quotes)', async function () {
+ jest.useFakeTimers();
+ const mockOnChange = jest.fn();
+
+ render(
+ <SmartSearchBar
+ {...defaultProps}
+ query=""
+ onChange={mockOnChange}
+ supportedTags={{
+ predefined: {
+ key: 'predefined',
+ name: 'predefined',
+ predefined: true,
+ values: ['"predefined" "tag" "with" "quotes"'],
+ },
+ }}
+ />
+ );
- expect(deleteAction).toBeDefined();
- if (deleteAction) {
- searchBar.runShortcut(deleteAction);
+ const textbox = screen.getByRole('textbox');
+ userEvent.type(textbox, 'predefined:');
- await tick();
+ act(() => {
+ jest.runOnlyPendingTimers();
+ });
- expect(searchBar.state.query).toEqual('is:unresolved has:key');
- }
+ const option = await screen.findByRole('option', {
+ name: /quotes/,
});
- it('exclude token', async () => {
- const props = {
- query: 'is:unresolved sdk.name:sentry-cocoa has:key',
- organization,
- location,
- supportedTags,
- };
- const searchBar = mountWithTheme(<SmartSearchBar {...props} />, options).instance();
- searchBar.updateAutoCompleteItems();
+ userEvent.click(option);
- mockCursorPosition(searchBar, 18);
+ await waitFor(() => {
+ expect(mockOnChange).toHaveBeenLastCalledWith(
+ 'predefined:"\\"predefined\\" \\"tag\\" \\"with\\" \\"quotes\\"" ',
+ expect.anything()
+ );
+ });
+ });
- await tick();
+ describe('quick actions', function () {
+ it('can delete tokens', function () {
+ render(
+ <SmartSearchBar
+ {...defaultProps}
+ query="is:unresolved sdk.name:sentry-cocoa has:key"
+ />
+ );
- const excludeAction = shortcuts.find(shortcut => shortcut.text === 'Exclude');
+ const textbox = screen.getByRole('textbox');
+ userEvent.click(textbox);
- expect(excludeAction).toBeDefined();
- if (excludeAction) {
- searchBar.runShortcut(excludeAction);
+ // Put cursor inside is:resolved
+ textbox.setSelectionRange(1, 1);
- await tick();
+ userEvent.click(screen.getByRole('button', {name: /Delete/}));
- expect(searchBar.state.query).toEqual(
- 'is:unresolved !sdk.name:sentry-cocoa has:key '
- );
- }
+ expect(textbox).toHaveValue('sdk.name:sentry-cocoa has:key');
});
- it('include token', async () => {
- const props = {
- query: 'is:unresolved !sdk.name:sentry-cocoa has:key',
- organization,
- location,
- supportedTags,
- };
- const searchBar = mountWithTheme(<SmartSearchBar {...props} />, options).instance();
- searchBar.updateAutoCompleteItems();
+ it('can delete a middle token', function () {
+ render(
+ <SmartSearchBar
+ {...defaultProps}
+ query="is:unresolved sdk.name:sentry-cocoa has:key"
+ />
+ );
- mockCursorPosition(searchBar, 18);
+ const textbox = screen.getByRole('textbox');
+ // Put cursor inside sdk.name
+ textbox.setSelectionRange('is:unresolved s'.length, 'is:unresolved s'.length);
+ userEvent.click(textbox);
- await tick();
+ userEvent.click(screen.getByRole('button', {name: /Delete/}));
- const includeAction = shortcuts.find(shortcut => shortcut.text === 'Include');
+ expect(textbox).toHaveValue('is:unresolved has:key');
+ });
- expect(includeAction).toBeDefined();
- if (includeAction) {
- searchBar.runShortcut(includeAction);
+ it('can exclude a token', function () {
+ render(
+ <SmartSearchBar
+ {...defaultProps}
+ query="is:unresolved sdk.name:sentry-cocoa has:key"
+ />
+ );
- await tick();
+ const textbox = screen.getByRole('textbox');
+ // Put cursor inside sdk.name
+ textbox.setSelectionRange('is:unresolved sd'.length, 'is:unresolved sd'.length);
+ userEvent.click(textbox);
- expect(searchBar.state.query).toEqual(
- 'is:unresolved sdk.name:sentry-cocoa has:key '
- );
- }
- });
+ userEvent.click(screen.getByRole('button', {name: /Exclude/}));
- it('replaces the correct word', async function () {
- const props = {
- query: '',
- organization,
- location,
- supportedTags,
- };
- const smartSearchBar = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBar = smartSearchBar.instance();
- const textarea = smartSearchBar.find('textarea');
-
- textarea.simulate('focus');
- mockCursorPosition(searchBar, 4);
- textarea.simulate('change', {target: {value: 'typ ti err'}});
-
- await tick();
-
- // Expect the correct search term to be selected
- const cursorSearchTerm = searchBar.cursorSearchTerm;
- expect(cursorSearchTerm.searchTerm).toEqual('ti');
- expect(cursorSearchTerm.start).toBe(4);
- expect(cursorSearchTerm.end).toBe(6);
- // use autocompletion to do the rest
- searchBar.onAutoComplete('title:', {});
- expect(searchBar.state.query).toEqual('typ title: err');
+ expect(textbox).toHaveValue('is:unresolved !sdk.name:sentry-cocoa has:key ');
});
- });
-
- describe('Invalid field state', () => {
- it('Shows invalid field state when invalid field is used', async () => {
- const props = {
- query: 'invalid:',
- organization,
- location,
- supportedTags,
- };
- const searchBar = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBarInst = searchBar.instance();
- mockCursorPosition(searchBarInst, 8);
+ it('can include a token', async function () {
+ render(
+ <SmartSearchBar
+ {...defaultProps}
+ query="is:unresolved !sdk.name:sentry-cocoa has:key"
+ />
+ );
- searchBar.find('textarea').simulate('focus');
+ const textbox = screen.getByRole('textbox');
+ // Put cursor inside sdk.name
+ textbox.setSelectionRange('is:unresolved !s'.length, 'is:unresolved !s'.length);
+ userEvent.click(textbox);
- searchBarInst.updateAutoCompleteItems();
+ expect(textbox).toHaveValue('is:unresolved !sdk.name:sentry-cocoa has:key ');
- await tick();
+ await screen.findByRole('button', {name: /Include/});
+ userEvent.click(screen.getByRole('button', {name: /Include/}));
- expect(searchBarInst.state.searchGroups).toHaveLength(1);
- expect(searchBarInst.state.searchGroups[0].title).toEqual('Keys');
- expect(searchBarInst.state.searchGroups[0].type).toEqual('invalid-tag');
- expect(searchBar.text()).toContain("The field invalid isn't supported here");
+ expect(textbox).toHaveValue('is:unresolved sdk.name:sentry-cocoa has:key ');
});
+ });
- it('Does not show invalid field state when valid field is used', async () => {
- const props = {
- query: 'is:',
- organization,
- location,
- supportedTags,
- };
- const searchBar = mountWithTheme(<SmartSearchBar {...props} />, options);
- const searchBarInst = searchBar.instance();
-
- mockCursorPosition(searchBarInst, 3);
+ it('displays invalid field message', async function () {
+ render(<SmartSearchBar {...defaultProps} query="" />);
- searchBarInst.updateAutoCompleteItems();
+ const textbox = screen.getByRole('textbox');
- await tick();
+ userEvent.type(textbox, 'invalid:');
- expect(searchBar.text()).not.toContain("isn't supported here");
+ act(() => {
+ jest.runOnlyPendingTimers();
});
+
+ expect(
+ await screen.findByRole('option', {name: /the field invalid isn't supported here/i})
+ ).toBeInTheDocument();
});
describe('date fields', () => {
@@ -1272,15 +841,8 @@ describe('SmartSearchBar', function () {
await import('sentry/components/calendar/datePicker');
});
- const props = {
- query: '',
- organization,
- location,
- supportedTags,
- };
-
it('displays date picker dropdown when appropriate', () => {
- render(<SmartSearchBar {...props} />);
+ render(<SmartSearchBar {...defaultProps} query="" />);
const textbox = screen.getByRole('textbox');
userEvent.click(textbox);
@@ -1315,7 +877,7 @@ describe('SmartSearchBar', function () {
});
it('can select a suggested relative time value', () => {
- render(<SmartSearchBar {...props} />);
+ render(<SmartSearchBar {...defaultProps} query="" />);
userEvent.type(screen.getByRole('textbox'), 'lastSeen:');
@@ -1325,7 +887,7 @@ describe('SmartSearchBar', function () {
});
it('can select a specific date/time', async () => {
- render(<SmartSearchBar {...props} />);
+ render(<SmartSearchBar {...defaultProps} query="" />);
userEvent.type(screen.getByRole('textbox'), 'lastSeen:');
@@ -1365,7 +927,7 @@ describe('SmartSearchBar', function () {
});
it('can change an existing datetime', async () => {
- render(<SmartSearchBar {...props} />);
+ render(<SmartSearchBar {...defaultProps} query="" />);
const textbox = screen.getByRole('textbox');
fireEvent.change(textbox, {
@@ -1392,7 +954,7 @@ describe('SmartSearchBar', function () {
});
it('populates the date picker correctly for date without time', async () => {
- render(<SmartSearchBar {...props} query="lastSeen:2022-01-01" />);
+ render(<SmartSearchBar {...defaultProps} query="lastSeen:2022-01-01" />);
const textbox = screen.getByRole('textbox');
// Move cursor to the timestamp
@@ -1412,7 +974,7 @@ describe('SmartSearchBar', function () {
});
it('populates the date picker correctly for date with time and no timezone', async () => {
- render(<SmartSearchBar {...props} query="lastSeen:2022-01-01T09:45:12" />);
+ render(<SmartSearchBar {...defaultProps} query="lastSeen:2022-01-01T09:45:12" />);
const textbox = screen.getByRole('textbox');
// Move cursor to the timestamp
@@ -1428,7 +990,9 @@ describe('SmartSearchBar', function () {
});
it('populates the date picker correctly for date with time and timezone', async () => {
- render(<SmartSearchBar {...props} query="lastSeen:2022-01-01T09:45:12-05:00" />);
+ render(
+ <SmartSearchBar {...defaultProps} query="lastSeen:2022-01-01T09:45:12-05:00" />
+ );
const textbox = screen.getByRole('textbox');
// Move cursor to the timestamp
@@ -1446,18 +1010,16 @@ describe('SmartSearchBar', function () {
describe('custom performance metric filters', () => {
it('raises Invalid file size when parsed filter unit is not a valid size unit', () => {
- const props = {
- organization,
- location,
- supportedTags,
- customPerformanceMetrics: {
- 'measurements.custom.kibibyte': {
- fieldType: 'size',
- },
- },
- };
-
- render(<SmartSearchBar {...props} />);
+ render(
+ <SmartSearchBar
+ {...defaultProps}
+ customPerformanceMetrics={{
+ 'measurements.custom.kibibyte': {
+ fieldType: 'size',
+ },
+ }}
+ />
+ );
const textbox = screen.getByRole('textbox');
userEvent.click(textbox);
@@ -1472,18 +1034,16 @@ describe('SmartSearchBar', function () {
});
it('raises Invalid duration when parsed filter unit is not a valid duration unit', () => {
- const props = {
- organization,
- location,
- supportedTags,
- customPerformanceMetrics: {
- 'measurements.custom.minute': {
- fieldType: 'duration',
- },
- },
- };
-
- render(<SmartSearchBar {...props} />);
+ render(
+ <SmartSearchBar
+ {...defaultProps}
+ customPerformanceMetrics={{
+ 'measurements.custom.minute': {
+ fieldType: 'duration',
+ },
+ }}
+ />
+ );
const textbox = screen.getByRole('textbox');
userEvent.click(textbox);
diff --git a/static/app/components/smartSearchBar/index.tsx b/static/app/components/smartSearchBar/index.tsx
index 8984283fd57e16..ac623a3eb20627 100644
--- a/static/app/components/smartSearchBar/index.tsx
+++ b/static/app/components/smartSearchBar/index.tsx
@@ -1487,6 +1487,7 @@ class SmartSearchBar extends Component<Props, State> {
this.setState({
searchTerm: tagName,
});
+
this.updateAutoCompleteStateMultiHeader(autocompleteGroups);
}
return;
diff --git a/static/app/components/smartSearchBar/searchDropdown.tsx b/static/app/components/smartSearchBar/searchDropdown.tsx
index c5078daadd0175..24d2c75459b79b 100644
--- a/static/app/components/smartSearchBar/searchDropdown.tsx
+++ b/static/app/components/smartSearchBar/searchDropdown.tsx
@@ -316,6 +316,7 @@ const DropdownItem = ({
return (
<Fragment>
<SearchListItem
+ role="option"
className={`${isChild ? 'group-child' : ''} ${item.active ? 'active' : ''}`}
data-test-id="search-autocomplete-item"
onClick={
|
99852b55cf08acffb2e9e8f9c583b1d36aec4811
|
2022-07-12 02:23:45
|
Maggie Bauer
|
feat(auditlog): Add version 2 to audit log endpoint (#36457)
| false
|
Add version 2 to audit log endpoint (#36457)
|
feat
|
diff --git a/src/sentry/api/endpoints/organization_auditlogs.py b/src/sentry/api/endpoints/organization_auditlogs.py
index 9991cfcce6f454..8f909a5ede064f 100644
--- a/src/sentry/api/endpoints/organization_auditlogs.py
+++ b/src/sentry/api/endpoints/organization_auditlogs.py
@@ -46,10 +46,14 @@ def get(self, request: Request, organization) -> Response:
else:
queryset = queryset.filter(event=query["event"])
- return self.paginate(
+ response = self.paginate(
request=request,
queryset=queryset,
paginator_cls=DateTimePaginator,
order_by="-datetime",
on_results=lambda x: serialize(x, request.user),
)
+ # TODO: Cleanup after frontend is fully moved to version 2
+ if "version" in request.GET and request.GET.get("version") == "2":
+ response.data = {"rows": response.data, "options": audit_log.get_api_names()}
+ return response
diff --git a/tests/sentry/api/endpoints/test_organization_auditlogs.py b/tests/sentry/api/endpoints/test_organization_auditlogs.py
index 9f6ddfd17a7fa7..0d9ea0532746a4 100644
--- a/tests/sentry/api/endpoints/test_organization_auditlogs.py
+++ b/tests/sentry/api/endpoints/test_organization_auditlogs.py
@@ -154,3 +154,25 @@ def test_user_out_of_bounds(self):
)
]
}
+
+ def test_version_two_response(self):
+ # Test that version two request will send "rows" with audit log entries
+ # and "options" with the audit log api names list.
+ now = timezone.now()
+
+ entry = AuditLogEntry.objects.create(
+ organization=self.organization,
+ event=audit_log.get_event_id("ORG_EDIT"),
+ actor=self.user,
+ datetime=now,
+ )
+ audit_log_api_names = set(audit_log.get_api_names())
+
+ response = self.get_success_response(self.organization.slug, qs_params={"version": "2"})
+ assert len(response.data) == 2
+ assert response.data["rows"][0]["id"] == str(entry.id)
+ assert set(response.data["options"]) == audit_log_api_names
+
+ response_2 = self.get_success_response(self.organization.slug, qs_params={"version": "3"})
+ assert len(response_2.data) == 1
+ assert response_2.data[0]["id"] == str(entry.id)
|
c000903ef6a941522e677f893ebdf438ec322645
|
2022-10-17 20:01:10
|
Nar Saynorath
|
fix(discover-homepage): Change button labels (#40038)
| false
|
Change button labels (#40038)
|
fix
|
diff --git a/static/app/views/eventsV2/homepage.spec.tsx b/static/app/views/eventsV2/homepage.spec.tsx
index bc6d4969d3d866..8b373a71e3d242 100644
--- a/static/app/views/eventsV2/homepage.spec.tsx
+++ b/static/app/views/eventsV2/homepage.spec.tsx
@@ -157,7 +157,7 @@ describe('Discover > Homepage', () => {
expect(screen.queryByText(/Last edited:/)).not.toBeInTheDocument();
});
- it('shows the Reset Discover Home button on initial load', async () => {
+ it('shows the Remove Default button on initial load', async () => {
MockApiClient.addMockResponse({
url: '/organizations/org-slug/discover/homepage/',
method: 'GET',
@@ -195,11 +195,11 @@ describe('Discover > Homepage', () => {
{context: initialData.routerContext, organization: initialData.organization}
);
- expect(await screen.findByText('Reset Discover Home')).toBeInTheDocument();
- expect(screen.queryByText('Use as Discover Home')).not.toBeInTheDocument();
+ expect(await screen.findByText('Remove Default')).toBeInTheDocument();
+ expect(screen.queryByText('Set As Default')).not.toBeInTheDocument();
});
- it('Disables the Use as Discover Home button when no saved homepage', () => {
+ it('Disables the Set As Default button when no saved homepage', () => {
initialData = initializeOrg({
...initializeOrg(),
organization,
@@ -230,7 +230,7 @@ describe('Discover > Homepage', () => {
);
expect(mockHomepage).toHaveBeenCalled();
- expect(screen.getByRole('button', {name: /use as discover home/i})).toBeDisabled();
+ expect(screen.getByRole('button', {name: /set as default/i})).toBeDisabled();
});
it('follows absolute date selection', async () => {
diff --git a/static/app/views/eventsV2/queryList.spec.jsx b/static/app/views/eventsV2/queryList.spec.jsx
index 15d8e262d1ed80..3956af89c51770 100644
--- a/static/app/views/eventsV2/queryList.spec.jsx
+++ b/static/app/views/eventsV2/queryList.spec.jsx
@@ -263,7 +263,7 @@ describe('EventsV2 > QueryList', function () {
const menuItems = card.find('MenuItemWrap');
expect(menuItems.length).toEqual(3);
- expect(menuItems.at(0).text()).toEqual('Use as Discover Home');
+ expect(menuItems.at(0).text()).toEqual('Set As Default');
expect(menuItems.at(1).text()).toEqual('Duplicate Query');
expect(menuItems.at(2).text()).toEqual('Delete Query');
});
@@ -291,7 +291,7 @@ describe('EventsV2 > QueryList', function () {
expect(miniGraph.props().yAxis).toEqual(['count()', 'failure_count()']);
});
- it('Use as Discover Home updates the homepage query', function () {
+ it('Set As Default updates the homepage query', function () {
render(
<QueryList
organization={organization}
@@ -303,7 +303,7 @@ describe('EventsV2 > QueryList', function () {
);
userEvent.click(screen.getByTestId('menu-trigger'));
- userEvent.click(screen.getByText('Use as Discover Home'));
+ userEvent.click(screen.getByText('Set As Default'));
expect(updateHomepageMock).toHaveBeenCalledWith(
'/organizations/org-slug/discover/homepage/',
expect.objectContaining({
diff --git a/static/app/views/eventsV2/queryList.tsx b/static/app/views/eventsV2/queryList.tsx
index 92d782163e63b5..0eda8036b4455a 100644
--- a/static/app/views/eventsV2/queryList.tsx
+++ b/static/app/views/eventsV2/queryList.tsx
@@ -180,7 +180,7 @@ class QueryList extends Component<Props> {
? [
{
key: 'set-as-default',
- label: t('Use as Discover Home'),
+ label: t('Set As Default'),
onAction: () => {
handleUpdateHomepageQuery(api, organization, eventView.toNewQuery());
},
@@ -266,7 +266,7 @@ class QueryList extends Component<Props> {
? [
{
key: 'set-as-default',
- label: t('Use as Discover Home'),
+ label: t('Set As Default'),
onAction: () => {
handleUpdateHomepageQuery(api, organization, eventView.toNewQuery());
},
diff --git a/static/app/views/eventsV2/results.spec.jsx b/static/app/views/eventsV2/results.spec.jsx
index 3fee812f96ca61..83c048c2f06766 100644
--- a/static/app/views/eventsV2/results.spec.jsx
+++ b/static/app/views/eventsV2/results.spec.jsx
@@ -1730,7 +1730,7 @@ describe('Results', function () {
);
});
- it('updates the homepage query with up to date eventView when Use as Discover Home is clicked', async () => {
+ it('updates the homepage query with up to date eventView when Set As Default is clicked', async () => {
const mockHomepageUpdate = MockApiClient.addMockResponse({
url: '/organizations/org-slug/discover/homepage/',
method: 'PUT',
@@ -1764,9 +1764,9 @@ describe('Results', function () {
);
await waitFor(() =>
- expect(screen.getByRole('button', {name: /use as discover home/i})).toBeEnabled()
+ expect(screen.getByRole('button', {name: /set as default/i})).toBeEnabled()
);
- userEvent.click(screen.getByText('Use as Discover Home'));
+ userEvent.click(screen.getByText('Set As Default'));
expect(mockHomepageUpdate).toHaveBeenCalledWith(
'/organizations/org-slug/discover/homepage/',
@@ -1828,10 +1828,10 @@ describe('Results', function () {
);
await waitFor(() =>
- expect(screen.getByRole('button', {name: /use as discover home/i})).toBeEnabled()
+ expect(screen.getByRole('button', {name: /set as default/i})).toBeEnabled()
);
- userEvent.click(screen.getByText('Use as Discover Home'));
- expect(await screen.findByText('Reset Discover Home')).toBeInTheDocument();
+ userEvent.click(screen.getByText('Set As Default'));
+ expect(await screen.findByText('Remove Default')).toBeInTheDocument();
userEvent.click(screen.getByText('Total Period'));
userEvent.click(screen.getByText('Previous Period'));
@@ -1849,7 +1849,7 @@ describe('Results', function () {
/>
);
screen.getByText('Previous Period');
- expect(await screen.findByText('Use as Discover Home')).toBeInTheDocument();
+ expect(await screen.findByText('Set As Default')).toBeInTheDocument();
});
it('Changes the Use as Discover button to a reset button for prebuilt query', async () => {
@@ -1894,8 +1894,8 @@ describe('Results', function () {
);
await screen.findAllByText(TRANSACTION_VIEWS[0].name);
- userEvent.click(screen.getByText('Use as Discover Home'));
- expect(await screen.findByText('Reset Discover Home')).toBeInTheDocument();
+ userEvent.click(screen.getByText('Set As Default'));
+ expect(await screen.findByText('Remove Default')).toBeInTheDocument();
userEvent.click(screen.getByText('Total Period'));
userEvent.click(screen.getByText('Previous Period'));
@@ -1913,6 +1913,6 @@ describe('Results', function () {
/>
);
screen.getByText('Previous Period');
- expect(await screen.findByText('Use as Discover Home')).toBeInTheDocument();
+ expect(await screen.findByText('Set As Default')).toBeInTheDocument();
});
});
diff --git a/static/app/views/eventsV2/savedQuery/index.tsx b/static/app/views/eventsV2/savedQuery/index.tsx
index 04af15a4f0c6e4..09b3bd0c411fa8 100644
--- a/static/app/views/eventsV2/savedQuery/index.tsx
+++ b/static/app/views/eventsV2/savedQuery/index.tsx
@@ -19,7 +19,7 @@ import FeatureBadge from 'sentry/components/featureBadge';
import {Hovercard} from 'sentry/components/hovercard';
import InputControl from 'sentry/components/input';
import {Overlay, PositionWrapper} from 'sentry/components/overlay';
-import {IconDelete, IconStar} from 'sentry/icons';
+import {IconBookmark, IconDelete, IconStar} from 'sentry/icons';
import {t} from 'sentry/locale';
import space from 'sentry/styles/space';
import {Organization, Project, SavedQuery} from 'sentry/types';
@@ -431,9 +431,10 @@ class SavedQueryButtonGroup extends PureComponent<Props, State> {
});
}
}}
+ icon={<IconBookmark isSolid />}
disabled={buttonDisabled}
>
- {t('Reset Discover Home')}
+ {t('Remove Default')}
<FeatureBadge type="alpha" />
</Button>
);
@@ -453,9 +454,10 @@ class SavedQueryButtonGroup extends PureComponent<Props, State> {
setHomepageQuery(updatedHomepageQuery);
}
}}
+ icon={<IconBookmark />}
disabled={buttonDisabled}
>
- {t('Use as Discover Home')}
+ {t('Set As Default')}
<FeatureBadge type="alpha" />
</Button>
);
diff --git a/static/app/views/eventsV2/savedQuery/utils.tsx b/static/app/views/eventsV2/savedQuery/utils.tsx
index 10f27a68ecf209..9bd98bd9a931ce 100644
--- a/static/app/views/eventsV2/savedQuery/utils.tsx
+++ b/static/app/views/eventsV2/savedQuery/utils.tsx
@@ -224,11 +224,11 @@ export function handleUpdateHomepageQuery(
return promise
.then(savedQuery => {
- addSuccessMessage(t('Saved as Discover home'));
+ addSuccessMessage(t('Saved as Discover default'));
return savedQuery;
})
.catch(() => {
- addErrorMessage(t('Unable to set query as Discover home'));
+ addErrorMessage(t('Unable to set query as Discover default'));
});
}
@@ -237,10 +237,10 @@ export function handleResetHomepageQuery(api: Client, organization: Organization
return promise
.then(() => {
- addSuccessMessage(t('Successfully reset Discover home'));
+ addSuccessMessage(t('Successfully removed Discover default'));
})
.catch(() => {
- addErrorMessage(t('Unable to reset Discover home'));
+ addErrorMessage(t('Unable to remove Discover default'));
});
}
|
cb060047fc3824edaa4aac9b10af9951127caf8a
|
2024-07-31 12:38:03
|
Jan Michael Auer
|
feat(discover): Expose trace.client_sample_rate (#75041)
| false
|
Expose trace.client_sample_rate (#75041)
|
feat
|
diff --git a/src/sentry/snuba/events.py b/src/sentry/snuba/events.py
index 1b74e2e590a464..3b201dc4dcf1d8 100644
--- a/src/sentry/snuba/events.py
+++ b/src/sentry/snuba/events.py
@@ -720,6 +720,14 @@ class Columns(Enum):
discover_name="contexts[trace.parent_span_id]",
alias="trace.parent_span",
)
+ TRACE_CLIENT_SAMPLE_RATE = Column(
+ group_name="events.contexts[trace.client_sample_rate]",
+ event_name="contexts[trace.client_sample_rate]",
+ transaction_name="contexts[trace.client_sample_rate]",
+ discover_name="contexts[trace.client_sample_rate]",
+ issue_platform_name="contexts[trace.client_sample_rate]",
+ alias="trace.client_sample_rate",
+ )
# Reprocessing context
REPROCESSING_ORIGINAL_GROUP_ID = Column(
@@ -729,14 +737,6 @@ class Columns(Enum):
discover_name="contexts[reprocessing.original_issue_id]",
alias="reprocessing.original_issue_id",
)
- TRACE_SAMPLE_RATE = Column(
- group_name="events.contexts[trace.client_sample_rate]",
- event_name="contexts[trace.client_sample_rate]",
- transaction_name="contexts[trace.client_sample_rate]",
- discover_name="contexts[trace.client_sample_rate]",
- issue_platform_name="contexts[trace.client_sample_rate]",
- alias="trace.client_sample_rate",
- )
APP_START_TYPE = Column(
group_name=None,
diff --git a/static/app/utils/fields/index.ts b/static/app/utils/fields/index.ts
index 5cd687696b0ffd..b03d606d46e6fc 100644
--- a/static/app/utils/fields/index.ts
+++ b/static/app/utils/fields/index.ts
@@ -111,6 +111,7 @@ export enum FieldKey {
TRACE = 'trace',
TRACE_PARENT_SPAN = 'trace.parent_span',
TRACE_SPAN = 'trace.span',
+ TRACE_CLIENT_SAMPLE_RATE = 'trace.client_sample_rate',
TRANSACTION = 'transaction',
TRANSACTION_DURATION = 'transaction.duration',
TRANSACTION_OP = 'transaction.op',
@@ -1106,6 +1107,11 @@ const EVENT_FIELD_DEFINITIONS: Record<AllEventFieldKeys, FieldDefinition> = {
kind: FieldKind.FIELD,
valueType: FieldValueType.STRING,
},
+ [FieldKey.TRACE_CLIENT_SAMPLE_RATE]: {
+ desc: t('Sample rate of the trace in the SDK between 0 and 1'),
+ kind: FieldKind.FIELD,
+ valueType: FieldValueType.STRING,
+ },
[FieldKey.TRANSACTION]: {
desc: t('Error or transaction name identifier'),
kind: FieldKind.FIELD,
@@ -1348,6 +1354,7 @@ export const DISCOVER_FIELDS = [
FieldKey.TRACE,
FieldKey.TRACE_SPAN,
FieldKey.TRACE_PARENT_SPAN,
+ FieldKey.TRACE_CLIENT_SAMPLE_RATE,
FieldKey.PROFILE_ID,
|
e4818e8b465308ac6f80e4b1d285f947a9f7de4b
|
2024-03-14 22:40:05
|
Cathy Teng
|
chore(github): cleanup unused code (#66971)
| false
|
cleanup unused code (#66971)
|
chore
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index 0ba2b4ef36b307..d972fb270ce9da 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -761,7 +761,6 @@ def SOCIAL_AUTH_DEFAULT_USERNAME() -> str:
"sentry.tasks.files",
"sentry.tasks.groupowner",
"sentry.tasks.integrations",
- "sentry.tasks.invite_missing_org_members",
"sentry.tasks.low_priority_symbolication",
"sentry.tasks.merge",
"sentry.tasks.options",
@@ -1104,15 +1103,6 @@ def SOCIAL_AUTH_DEFAULT_USERNAME() -> str:
),
"options": {"expires": 60 * 60 * 3},
},
- # "schedule-monthly-invite-missing-org-members": {
- # "task": "sentry.tasks.invite_missing_org_members.schedule_organizations",
- # "schedule": crontab(
- # minute=0,
- # hour=7,
- # day_of_month="1", # 00:00 PDT, 03:00 EDT, 7:00 UTC
- # ),
- # "options": {"expires": 60 * 25},
- # },
"schedule-hybrid-cloud-foreign-key-jobs": {
"task": "sentry.tasks.deletion.hybrid_cloud.schedule_hybrid_cloud_foreign_key_jobs",
# Run every 15 minutes
@@ -1436,7 +1426,6 @@ def custom_parameter_sort(parameter: dict) -> tuple[str, int]:
"organizations:grouping-stacktrace-ui": "Enable experimental new version of stacktrace component where additional data related to grouping is shown on each frame",
"organizations:grouping-title-ui": "Enable tweaks to group title in relation to hierarchical grouping.",
"organizations:grouping-tree-ui": "Enable experimental new version of Merged Issues where sub-hashes are shown",
- "organizations:integrations-gh-invite": "Enables inviting new members based on GitHub commit activity",
"organizations:issue-details-tag-improvements": "Enable tag improvements in the issue details page",
"organizations:mobile-cpu-memory-in-transactions": "Display CPU and memory metrics in transactions with profiles",
"organizations:performance-metrics-backed-transaction-summary": "Enable metrics-backed transaction summary view",
@@ -1588,6 +1577,8 @@ def custom_parameter_sort(parameter: dict) -> tuple[str, int]:
"organizations:integrations-chat-unfurl": True,
# Enable the API to importing CODEOWNERS for a project
"organizations:integrations-codeowners": True,
+ # Enable custom alert priorities for Pagerduty and Opsgenie
+ "organizations:integrations-custom-alert-priorities": False,
# Enable integration functionality to work deployment integrations like Vercel
"organizations:integrations-deployment": True,
# Enable integration functionality to work with enterprise alert rules
@@ -1597,8 +1588,6 @@ def custom_parameter_sort(parameter: dict) -> tuple[str, int]:
"organizations:integrations-enterprise-incident-management": True,
# Enable interface functionality to receive event hooks.
"organizations:integrations-event-hooks": True,
- # Enables inviting new members based on GitHub commit activity.
- "organizations:integrations-gh-invite": False,
# Enable integration functionality to work with alert rules (specifically incident
# management integrations)
"organizations:integrations-incident-management": True,
@@ -1892,8 +1881,6 @@ def custom_parameter_sort(parameter: dict) -> tuple[str, int]:
"organizations:sourcemaps-upload-release-as-artifact-bundle": False,
# Enable Slack messages using Block Kit
"organizations:slack-block-kit": False,
- # Improvements to Slack messages using Block Kit
- "organizations:slack-block-kit-improvements": False,
# Send Slack notifications to threads for Metric Alerts
"organizations:slack-thread": False,
# Send Slack notifications to threads for Issue Alerts
diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py
index 7bdb21fa0cccaa..c7fc2cd889b01a 100644
--- a/src/sentry/features/__init__.py
+++ b/src/sentry/features/__init__.py
@@ -113,11 +113,9 @@
default_manager.add("organizations:grouping-tree-ui", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:higher-ownership-limit", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
default_manager.add("organizations:increased-issue-owners-rate-limit", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
+default_manager.add("organizations:integrations-custom-alert-priorities", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:integrations-deployment", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
default_manager.add("organizations:integrations-feature-flag-integration", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
-default_manager.add("organizations:integrations-gh-invite", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
-default_manager.add("organizations:integrations-open-pr-comment", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
-default_manager.add("organizations:integrations-open-pr-comment-js", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:integrations-open-pr-comment-beta-langs", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:investigation-bias", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:invite-members-rate-limits", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
@@ -261,7 +259,6 @@
default_manager.add("organizations:slack-block-kit", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
default_manager.add("organizations:slack-thread", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:slack-thread-issue-alert", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
-default_manager.add("organizations:slack-block-kit-improvements", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
default_manager.add("organizations:slack-overage-notifications", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:sourcemaps-bundle-flat-file-indexing", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:sourcemaps-upload-release-as-artifact-bundle", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
diff --git a/src/sentry/tasks/invite_missing_org_members.py b/src/sentry/tasks/invite_missing_org_members.py
deleted file mode 100644
index 09f234b0600408..00000000000000
--- a/src/sentry/tasks/invite_missing_org_members.py
+++ /dev/null
@@ -1,117 +0,0 @@
-import logging
-
-from sentry import features
-from sentry.api.endpoints.organization_missing_org_members import (
- _format_external_id,
- _get_missing_organization_members,
- _get_shared_email_domain,
-)
-from sentry.constants import ObjectStatus
-from sentry.models.options import OrganizationOption
-from sentry.models.organization import Organization
-from sentry.notifications.notifications.missing_members_nudge import MissingMembersNudgeNotification
-from sentry.services.hybrid_cloud.integration import integration_service
-from sentry.silo.base import SiloMode
-from sentry.tasks.base import instrumented_task
-
-logger = logging.getLogger(__name__)
-
-
-@instrumented_task(
- name="sentry.tasks.invite_missing_org_members.schedule_organizations",
- max_retries=3,
- silo_mode=SiloMode.REGION,
-)
-def schedule_organizations():
- logger.info("invite_missing_org_members.schedule_organizations")
-
- # NOTE: currently only for github
- github_org_integrations = integration_service.get_organization_integrations(
- providers=["github"], status=ObjectStatus.ACTIVE
- )
- orgs_with_github_integrations = {
- org_integration.organization_id for org_integration in github_org_integrations
- }
-
- for org_id in orgs_with_github_integrations:
- send_nudge_email.delay(org_id)
-
-
-@instrumented_task(
- name="sentry.tasks.invite_missing_members.send_nudge_email",
- silo_mode=SiloMode.REGION,
- queue="nudge.invite_missing_org_members",
-)
-def send_nudge_email(org_id):
- logger.info("invite_missing_org_members.send_nudge_email")
-
- try:
- organization = Organization.objects.get_from_cache(id=org_id)
- except Organization.DoesNotExist:
- logger.info(
- "invite_missing_org_members.send_nudge_email.missing_org",
- extra={"organization_id": org_id},
- )
- return
-
- if not features.has("organizations:integrations-gh-invite", organization):
- logger.info(
- "invite_missing_org_members.send_nudge_email.missing_flag",
- extra={"organization_id": org_id},
- )
- return
-
- if not OrganizationOption.objects.get_value(
- organization=organization, key="sentry:github_nudge_invite", default=True
- ):
- return
-
- integrations = integration_service.get_integrations(
- organization_id=org_id, providers=["github"], status=ObjectStatus.ACTIVE
- )
-
- if not integrations:
- logger.info(
- "invite_missing_org_members.send_nudge_email.missing_integrations",
- extra={"organization_id": org_id},
- )
- return
-
- shared_domain = _get_shared_email_domain(organization)
-
- commit_author_query = _get_missing_organization_members(
- organization,
- provider="github",
- integration_ids=[i.id for i in integrations],
- shared_domain=shared_domain,
- )
-
- if not len(commit_author_query): # don't email if no missing commit authors
- logger.info(
- "invite_missing_org_members.send_nudge_email.no_commit_authors",
- extra={"organization_id": org_id},
- )
- return
-
- commit_authors = []
- for commit_author in commit_author_query[:3]:
- formatted_external_id = _format_external_id(commit_author.external_id)
-
- commit_authors.append(
- {
- "email": commit_author.email,
- "external_id": formatted_external_id,
- "commit_count": commit_author.commit__count,
- }
- )
-
- notification = MissingMembersNudgeNotification(
- organization=organization, commit_authors=commit_authors, provider="github"
- )
-
- logger.info(
- "invite_missing_org_members.send_nudge_email.send_notification",
- extra={"organization_id": org_id},
- )
-
- notification.send()
diff --git a/tests/sentry/integrations/slack/test_message_builder.py b/tests/sentry/integrations/slack/test_message_builder.py
index ede4effb823631..06ff3dfbb91172 100644
--- a/tests/sentry/integrations/slack/test_message_builder.py
+++ b/tests/sentry/integrations/slack/test_message_builder.py
@@ -893,7 +893,6 @@ def test_build_group_generic_issue_block(self):
assert ":red_circle:" in section["text"]["text"]
@with_feature("organizations:slack-block-kit")
- @with_feature("organizations:slack-block-kit-improvements")
def test_build_group_generic_issue_block_no_escaping(self):
"""Test that a generic issue type's Slack alert contains the expected values"""
event = self.store_event(
diff --git a/tests/sentry/tasks/test_invite_missing_org_members.py b/tests/sentry/tasks/test_invite_missing_org_members.py
deleted file mode 100644
index 19ff0dd8dec316..00000000000000
--- a/tests/sentry/tasks/test_invite_missing_org_members.py
+++ /dev/null
@@ -1,178 +0,0 @@
-from unittest.mock import patch
-
-from sentry.constants import ObjectStatus
-from sentry.models.options.organization_option import OrganizationOption
-from sentry.tasks.invite_missing_org_members import schedule_organizations, send_nudge_email
-from sentry.testutils.cases import TestCase
-from sentry.testutils.helpers import with_feature
-from sentry.testutils.silo import region_silo_test
-
-
-@region_silo_test
-@patch(
- "sentry.notifications.notifications.missing_members_nudge.MissingMembersNudgeNotification.send",
-)
-@patch(
- "sentry.tasks.invite_missing_org_members.send_nudge_email",
-)
-class InviteMissingMembersTestCase(TestCase):
- def setUp(self):
- super().setUp()
- self.user = self.create_user(email="[email protected]")
- self.organization = self.create_organization(owner=self.user)
- self.create_member(
- email="[email protected]",
- organization=self.organization,
- )
- member = self.create_member(user=self.create_user(), organization=self.organization)
- member.user_email = "[email protected]"
- member.save()
-
- self.member_commit_author = self.create_commit_author(
- project=self.project, email="[email protected]"
- )
- self.nonmember_commit_author1 = self.create_commit_author(
- project=self.project, email="[email protected]"
- )
- self.nonmember_commit_author1.external_id = "github:c"
- self.nonmember_commit_author1.save()
-
- self.nonmember_commit_author2 = self.create_commit_author(
- project=self.project, email="[email protected]"
- )
- self.nonmember_commit_author2.external_id = "github:d"
- self.nonmember_commit_author2.save()
-
- nonmember_commit_author_invalid_char = self.create_commit_author(
- project=self.project, email="[email protected]"
- )
- nonmember_commit_author_invalid_char.external_id = "github:hi+1"
- nonmember_commit_author_invalid_char.save()
-
- nonmember_commit_author_invalid_domain = self.create_commit_author(
- project=self.project, email="[email protected]"
- )
- nonmember_commit_author_invalid_domain.external_id = "github:gmail"
- nonmember_commit_author_invalid_domain.save()
-
- self.repo = self.create_repo(project=self.project, provider="integrations:github")
- self.create_commit(repo=self.repo, author=self.member_commit_author)
- self.create_commit(repo=self.repo, author=self.nonmember_commit_author1)
- self.create_commit(repo=self.repo, author=self.nonmember_commit_author1)
- self.create_commit(repo=self.repo, author=self.nonmember_commit_author2)
- self.create_commit(repo=self.repo, author=nonmember_commit_author_invalid_char)
- self.create_commit(repo=self.repo, author=nonmember_commit_author_invalid_domain)
-
- not_shared_domain_author = self.create_commit_author(
- project=self.project, email="[email protected]"
- )
- not_shared_domain_author.external_id = "github:not"
- not_shared_domain_author.save()
- self.create_commit(repo=self.repo, author=not_shared_domain_author)
-
- self.login_as(self.user)
-
- @with_feature("organizations:integrations-gh-invite")
- def test_schedules_and_sends(self, mock_send_email, mock_send_notification):
- integration = self.create_integration(
- organization=self.organization, provider="github", name="Github", external_id="github:1"
- )
- self.repo.integration_id = integration.id
- self.repo.save()
-
- with self.tasks():
- schedule_organizations()
-
- mock_send_email.delay.assert_called_with(self.organization.id)
-
- send_nudge_email(org_id=self.organization.id)
-
- assert mock_send_notification.called
-
- @with_feature("organizations:integrations-gh-invite")
- @patch(
- "sentry.notifications.notifications.missing_members_nudge.MissingMembersNudgeNotification.__init__",
- return_value=None,
- )
- def test_excludes_filtered_emails(
- self, mock_init_notification, mock_send_email, mock_send_notification
- ):
- integration = self.create_integration(
- organization=self.organization, provider="github", name="Github", external_id="github:1"
- )
- self.repo.integration_id = integration.id
- self.repo.save()
-
- send_nudge_email(org_id=self.organization.id)
-
- commit_authors = [
- {"email": "[email protected]", "external_id": "c", "commit_count": 2},
- {"email": "[email protected]", "external_id": "d", "commit_count": 1},
- ]
-
- mock_init_notification.assert_called_once_with(
- organization=self.organization, commit_authors=commit_authors, provider="github"
- )
-
- def test_no_github_repos(self, mock_send_email, mock_send_notification):
- self.repo.delete()
-
- with self.tasks():
- schedule_organizations()
-
- assert not mock_send_email.delay.called
-
- def test_no_active_github_repos(self, mock_send_email, mock_send_notification):
- self.repo.status = ObjectStatus.DISABLED
- self.repo.save()
-
- with self.tasks():
- schedule_organizations()
-
- assert not mock_send_email.delay.called
-
- def test_missing_org(self, mock_send_email, mock_send_notification):
- send_nudge_email(org_id=0)
-
- assert not mock_send_notification.called
-
- def test_missing_feature_flag(self, mock_send_email, mock_send_notification):
- send_nudge_email(org_id=self.organization.id)
-
- assert not mock_send_notification.called
-
- @with_feature("organizations:integrations-gh-invite")
- def test_missing_integration(self, mock_send_email, mock_send_notification):
- send_nudge_email(org_id=self.organization.id)
-
- assert not mock_send_notification.called
-
- @with_feature("organizations:integrations-gh-invite")
- def test_missing_option(self, mock_send_email, mock_send_notification):
- OrganizationOption.objects.set_value(
- organization=self.organization, key="sentry:github_nudge_invite", value=False
- )
-
- integration = self.create_integration(
- organization=self.organization, provider="github", name="Github", external_id="github:1"
- )
- self.repo.integration_id = integration.id
- self.repo.save()
-
- send_nudge_email(org_id=self.organization.id)
-
- assert not mock_send_notification.called
-
- @with_feature("organizations:integrations-gh-invite")
- def test_missing_nonmember_commit_authors(self, mock_send_email, mock_send_notification):
- org = self.create_organization()
- project = self.create_project(organization=org)
- self.create_repo(project=project, provider="github")
-
- self.create_integration(
- organization=org, provider="github", name="Github", external_id="github:1"
- )
-
- send_nudge_email(org_id=org.id)
-
- assert not mock_send_notification.called
|
8f7d6966583d0538a5d5f08fd22c46c2f7ef27c3
|
2021-04-28 04:31:58
|
Danny Lee
|
feat(getParams): Support page-* prefix for local datetime (#25662)
| false
|
Support page-* prefix for local datetime (#25662)
|
feat
|
diff --git a/static/app/components/organizations/globalSelectionHeader/getParams.tsx b/static/app/components/organizations/globalSelectionHeader/getParams.tsx
index 350a9dac4c1a83..a81e8ee0f73490 100644
--- a/static/app/components/organizations/globalSelectionHeader/getParams.tsx
+++ b/static/app/components/organizations/globalSelectionHeader/getParams.tsx
@@ -132,8 +132,10 @@ type ParsedParams = {
};
type InputParams = {
+ pageStatsPeriod?: ParamValue;
pageStart?: Date | ParamValue;
pageEnd?: Date | ParamValue;
+ pageUtc?: boolean | ParamValue;
start?: Date | ParamValue;
end?: Date | ParamValue;
period?: ParamValue;
@@ -158,8 +160,10 @@ export function getParams(
}: GetParamsOptions = {}
): ParsedParams {
const {
+ pageStatsPeriod,
pageStart,
pageEnd,
+ pageUtc,
start,
end,
period,
@@ -169,7 +173,10 @@ export function getParams(
} = params;
// `statsPeriod` takes precedence for now
- let coercedPeriod = getStatsPeriodValue(statsPeriod) || getStatsPeriodValue(period);
+ let coercedPeriod =
+ getStatsPeriodValue(pageStatsPeriod) ||
+ getStatsPeriodValue(statsPeriod) ||
+ getStatsPeriodValue(period);
const dateTimeStart = allowAbsoluteDatetime
? allowAbsolutePageDatetime
@@ -195,7 +202,7 @@ export function getParams(
end: coercedPeriod ? null : dateTimeEnd,
// coerce utc into a string (it can be both: a string representation from router,
// or a boolean from time range picker)
- utc: getUtcValue(utc),
+ utc: getUtcValue(pageUtc ?? utc),
...otherParams,
})
// Filter null values
diff --git a/tests/js/spec/components/organizations/getParams.spec.jsx b/tests/js/spec/components/organizations/getParams.spec.jsx
index b63f1f4756e159..047ee7d03df6f0 100644
--- a/tests/js/spec/components/organizations/getParams.spec.jsx
+++ b/tests/js/spec/components/organizations/getParams.spec.jsx
@@ -129,18 +129,42 @@ describe('getParams', function () {
).toEqual({statsPeriod: '14d'});
});
- it('should use pageStart and pageEnd to override start and end', function () {
+ it('should use pageStart/pageEnd/pageUtc to override start/end/utc', function () {
expect(
getParams(
{
pageStart: '2021-10-23T04:28:49+0000',
pageEnd: '2021-10-26T02:56:17+0000',
+ pageUtc: 'true',
start: '2019-10-23T04:28:49+0000',
end: '2019-10-26T02:56:17+0000',
+ utc: 'false',
},
{allowAbsolutePageDatetime: true}
)
- ).toEqual({start: '2021-10-23T04:28:49.000', end: '2021-10-26T02:56:17.000'});
+ ).toEqual({
+ start: '2021-10-23T04:28:49.000',
+ end: '2021-10-26T02:56:17.000',
+ utc: 'true',
+ });
+ });
+
+ it('should use pageStatsPeriod to override statsPeriod', function () {
+ expect(
+ getParams({
+ pageStart: '2021-10-23T04:28:49+0000',
+ pageEnd: '2021-10-26T02:56:17+0000',
+ pageUtc: 'true',
+ pageStatsPeriod: '90d',
+ start: '2019-10-23T04:28:49+0000',
+ end: '2019-10-26T02:56:17+0000',
+ utc: 'false',
+ statsPeriod: '14d',
+ })
+ ).toEqual({
+ utc: 'true',
+ statsPeriod: '90d',
+ });
});
it('does not return default statsPeriod if `allowEmptyPeriod` option is passed', function () {
|
d9c2131b37ce0609fbe8b5bdee773fd98416a5c9
|
2023-05-01 21:14:54
|
Kev
|
feat(perf): Adjust txn summary to use MEP (#48068)
| false
|
Adjust txn summary to use MEP (#48068)
|
feat
|
diff --git a/static/app/utils/performance/contexts/metricsEnhancedPerformanceDataContext.tsx b/static/app/utils/performance/contexts/metricsEnhancedPerformanceDataContext.tsx
index e1871c5710fd3d..c2bf6cb011364f 100644
--- a/static/app/utils/performance/contexts/metricsEnhancedPerformanceDataContext.tsx
+++ b/static/app/utils/performance/contexts/metricsEnhancedPerformanceDataContext.tsx
@@ -8,7 +8,7 @@ import {PerformanceWidgetSetting} from 'sentry/views/performance/landing/widgets
import {AutoSampleState, useMEPSettingContext} from './metricsEnhancedSetting';
import {createDefinedContext} from './utils';
-interface MetricsEnhancedPerformanceDataContext {
+export interface MetricsEnhancedPerformanceDataContext {
setIsMetricsData: (value?: boolean) => void;
isMetricsData?: boolean;
}
@@ -53,6 +53,18 @@ export function MEPDataProvider({
export const useMEPDataContext = _useMEPDataContext;
+export function getIsMetricsDataFromResults(
+ results: any,
+ field = ''
+): boolean | undefined {
+ const isMetricsData =
+ results?.meta?.isMetricsData ??
+ results?.seriesAdditionalInfo?.[field]?.isMetricsData ??
+ results?.histograms?.meta?.isMetricsData ??
+ results?.tableData?.meta?.isMetricsData;
+ return isMetricsData;
+}
+
export function MEPTag() {
const {isMetricsData} = useMEPDataContext();
const organization = useOrganization();
diff --git a/static/app/utils/performance/contexts/metricsEnhancedSetting.tsx b/static/app/utils/performance/contexts/metricsEnhancedSetting.tsx
index eb00101a0b6b90..b1fff445c5a821 100644
--- a/static/app/utils/performance/contexts/metricsEnhancedSetting.tsx
+++ b/static/app/utils/performance/contexts/metricsEnhancedSetting.tsx
@@ -4,6 +4,7 @@ import {Location} from 'history';
import {Organization} from 'sentry/types';
import localStorage from 'sentry/utils/localStorage';
+import {MEPDataProvider} from 'sentry/utils/performance/contexts/metricsEnhancedPerformanceDataContext';
import {decodeScalar} from 'sentry/utils/queryString';
import useOrganization from 'sentry/utils/useOrganization';
@@ -76,11 +77,10 @@ export function canUseMetricsData(organization: Organization) {
const isDevFlagOn = canUseMetricsDevUI(organization); // Forces metrics data on as well.
const isInternalViewOn = organization.features.includes(
'performance-transaction-name-only-search'
- ); // TODO: Swap this flag out.
-
- const samplingRolloutFlag = organization.features.includes('dynamic-sampling');
+ );
+ const samplingFeatureFlag = organization.features.includes('dynamic-sampling'); // Exists on AM2 plans only.
const isRollingOut =
- samplingRolloutFlag && organization.features.includes('mep-rollout-flag');
+ samplingFeatureFlag && organization.features.includes('mep-rollout-flag');
return isDevFlagOn || isInternalViewOn || isRollingOut;
}
@@ -166,7 +166,7 @@ export function MEPSettingProvider({
setAutoSampleState,
}}
>
- {children}
+ <MEPDataProvider>{children}</MEPDataProvider>
</_MEPSettingProvider>
);
}
diff --git a/static/app/views/performance/landing/widgets/components/queryHandler.tsx b/static/app/views/performance/landing/widgets/components/queryHandler.tsx
index b5af89ffab0132..f25fb4eb031729 100644
--- a/static/app/views/performance/landing/widgets/components/queryHandler.tsx
+++ b/static/app/views/performance/landing/widgets/components/queryHandler.tsx
@@ -1,7 +1,10 @@
import {Fragment, useEffect} from 'react';
import {getUtcToLocalDateObject} from 'sentry/utils/dates';
-import {useMEPDataContext} from 'sentry/utils/performance/contexts/metricsEnhancedPerformanceDataContext';
+import {
+ getIsMetricsDataFromResults,
+ useMEPDataContext,
+} from 'sentry/utils/performance/contexts/metricsEnhancedPerformanceDataContext';
import {QueryDefinitionWithKey, QueryHandlerProps, WidgetDataConstraint} from '../types';
import {PerformanceWidgetSetting} from '../widgetDefinitions';
@@ -95,10 +98,10 @@ function QueryResultSaver<T extends WidgetDataConstraint>(
const transformed = query.transform(props.queryProps, results, props.query);
useEffect(() => {
- const isMetricsData =
- results?.seriesAdditionalInfo?.[props.queryProps.fields[0]]?.isMetricsData ??
- results?.histograms?.meta?.isMetricsData ??
- results?.tableData?.meta?.isMetricsData;
+ const isMetricsData = getIsMetricsDataFromResults(
+ results,
+ props.queryProps.fields[0]
+ );
mepContext.setIsMetricsData(isMetricsData);
props.setWidgetDataForKey(query.queryKey, transformed);
}, [transformed?.hasData, transformed?.isLoading, transformed?.isErrored]);
diff --git a/static/app/views/performance/landing/widgets/utils.tsx b/static/app/views/performance/landing/widgets/utils.tsx
index abec198da1d5b7..6d2c193f47ee77 100644
--- a/static/app/views/performance/landing/widgets/utils.tsx
+++ b/static/app/views/performance/landing/widgets/utils.tsx
@@ -29,15 +29,21 @@ function setWidgetStorageObject(localObject: Record<string, string>) {
const mepQueryParamBase = {};
-export function getMEPQueryParams(mepContext: MetricsEnhancedSettingContext) {
+export function getMEPQueryParams(
+ mepContext: MetricsEnhancedSettingContext,
+ forceAuto?: boolean
+) {
let queryParams = {};
const base = mepQueryParamBase;
- if (mepContext.shouldQueryProvideMEPAutoParams) {
+ if (mepContext.shouldQueryProvideMEPAutoParams || forceAuto) {
queryParams = {
...queryParams,
...base,
dataset: 'metricsEnhanced',
};
+ if (forceAuto) {
+ return queryParams;
+ }
}
if (mepContext.shouldQueryProvideMEPTransactionParams) {
queryParams = {...queryParams, ...base, dataset: 'discover'};
diff --git a/static/app/views/performance/transactionSummary/transactionOverview/charts.tsx b/static/app/views/performance/transactionSummary/transactionOverview/charts.tsx
index fe45623ad2df39..feb4461a84f3e9 100644
--- a/static/app/views/performance/transactionSummary/transactionOverview/charts.tsx
+++ b/static/app/views/performance/transactionSummary/transactionOverview/charts.tsx
@@ -151,11 +151,7 @@ function TransactionSummaryCharts({
};
const mepSetting = useMEPSettingContext();
- const queryExtras = getTransactionMEPParamsIfApplicable(
- mepSetting,
- organization,
- location
- );
+ const queryExtras = getTransactionMEPParamsIfApplicable(mepSetting, organization);
return (
<Panel>
diff --git a/static/app/views/performance/transactionSummary/transactionOverview/content.tsx b/static/app/views/performance/transactionSummary/transactionOverview/content.tsx
index b28e0a82cbe097..44689f9e06e4c6 100644
--- a/static/app/views/performance/transactionSummary/transactionOverview/content.tsx
+++ b/static/app/views/performance/transactionSummary/transactionOverview/content.tsx
@@ -31,6 +31,10 @@ import {
SPAN_OP_RELATIVE_BREAKDOWN_FIELD,
} from 'sentry/utils/discover/fields';
import {QueryError} from 'sentry/utils/discover/genericDiscoverQuery';
+import {
+ MetricsEnhancedPerformanceDataContext,
+ useMEPDataContext,
+} from 'sentry/utils/performance/contexts/metricsEnhancedPerformanceDataContext';
import {decodeScalar} from 'sentry/utils/queryString';
import projectSupportsReplay from 'sentry/utils/replays/projectSupportsReplay';
import {useRoutes} from 'sentry/utils/useRoutes';
@@ -100,6 +104,7 @@ function SummaryContent({
unfilteredTotalValues,
}: Props) {
const routes = useRoutes();
+ const mepDataContext = useMEPDataContext();
function handleSearch(query: string) {
const queryParams = normalizeDateTimeParams({
...(location.query || {}),
@@ -180,9 +185,13 @@ function SummaryContent({
return sortedEventView;
}
- function generateActionBarItems(_org: Organization, _location: Location) {
+ function generateActionBarItems(
+ _org: Organization,
+ _location: Location,
+ _mepDataContext: MetricsEnhancedPerformanceDataContext
+ ) {
let items: ActionBarItem[] | undefined = undefined;
- if (!canUseTransactionMetricsData(_org, _location)) {
+ if (!canUseTransactionMetricsData(_org, _mepDataContext)) {
items = [
{
key: 'alert',
@@ -193,7 +202,11 @@ function SummaryContent({
'Based on your search criteria and sample rate, the events available may be limited.'
)}
>
- <StyledIconWarning size="sm" color="warningText" />
+ <StyledIconWarning
+ data-test-id="search-metrics-fallback-warning"
+ size="sm"
+ color="warningText"
+ />
</Tooltip>
),
menuItem: {
@@ -340,7 +353,11 @@ function SummaryContent({
fields={eventView.fields}
onSearch={handleSearch}
maxQueryLength={MAX_QUERY_LENGTH}
- actionBarItems={generateActionBarItems(organization, location)}
+ actionBarItems={generateActionBarItems(
+ organization,
+ location,
+ mepDataContext
+ )}
/>
</FilterActions>
<TransactionSummaryCharts
diff --git a/static/app/views/performance/transactionSummary/transactionOverview/index.spec.tsx b/static/app/views/performance/transactionSummary/transactionOverview/index.spec.tsx
index c37a3291081f4a..2d5962af2cd963 100644
--- a/static/app/views/performance/transactionSummary/transactionOverview/index.spec.tsx
+++ b/static/app/views/performance/transactionSummary/transactionOverview/index.spec.tsx
@@ -6,6 +6,7 @@ import {render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrar
import ProjectsStore from 'sentry/stores/projectsStore';
import TeamStore from 'sentry/stores/teamStore';
import {Project} from 'sentry/types';
+import {DiscoverDatasets} from 'sentry/utils/discover/types';
import {
MEPSetting,
MEPState,
@@ -70,6 +71,7 @@ function TestComponent({
}
describe('Performance > TransactionSummary', function () {
+ let eventStatsMock: jest.Mock;
beforeEach(function () {
// @ts-ignore no-console
// eslint-disable-next-line no-console
@@ -88,7 +90,7 @@ describe('Performance > TransactionSummary', function () {
url: '/organizations/org-slug/tags/user.email/values/',
body: [],
});
- MockApiClient.addMockResponse({
+ eventStatsMock = MockApiClient.addMockResponse({
url: '/organizations/org-slug/events-stats/',
body: {data: [[123, []]]},
});
@@ -100,6 +102,7 @@ describe('Performance > TransactionSummary', function () {
url: '/organizations/org-slug/issues/?limit=5&project=2&query=is%3Aunresolved%20transaction%3A%2Fperformance&sort=new&statsPeriod=14d',
body: [],
});
+
MockApiClient.addMockResponse({
url: '/organizations/org-slug/users/',
body: [],
@@ -125,32 +128,33 @@ describe('Performance > TransactionSummary', function () {
url: '/organizations/org-slug/events-facets-performance/',
body: {},
});
-
- // Mock totals for the sidebar and other summary data
+ // Events Mock totals for the sidebar and other summary data
MockApiClient.addMockResponse({
- url: '/organizations/org-slug/eventsv2/',
+ url: '/organizations/org-slug/events/',
body: {
meta: {
- count: 'number',
- apdex: 'number',
- count_miserable_user: 'number',
- user_misery: 'number',
- count_unique_user: 'number',
- p95: 'number',
- failure_rate: 'number',
- tpm: 'number',
- project_threshold_config: 'string',
+ fields: {
+ 'count()': 'number',
+ 'apdex()': 'number',
+ 'count_miserable_user()': 'number',
+ 'user_misery()': 'number',
+ 'count_unique_user()': 'number',
+ 'p95()': 'number',
+ 'failure_rate()': 'number',
+ 'tpm()': 'number',
+ project_threshold_config: 'string',
+ },
},
data: [
{
- count: 2,
- apdex: 0.6,
- count_miserable_user: 122,
- user_misery: 0.114,
- count_unique_user: 1,
- p95: 750.123,
- failure_rate: 1,
- tpm: 1,
+ 'count()': 2,
+ 'apdex()': 0.6,
+ 'count_miserable_user()': 122,
+ 'user_misery()': 0.114,
+ 'count_unique_user()': 1,
+ 'p95()': 750.123,
+ 'failure_rate()': 1,
+ 'tpm()': 1,
project_threshold_config: ['duration', 300],
},
],
@@ -161,60 +165,7 @@ describe('Performance > TransactionSummary', function () {
},
],
});
- // Eventsv2 Transaction list response
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/eventsv2/',
- headers: {
- Link:
- '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=2:0:0>; rel="next"; results="true"; cursor="2:0:0",' +
- '<http://localhost/api/0/organizations/org-slug/eventsv2/?cursor=1:0:0>; rel="previous"; results="false"; cursor="1:0:0"',
- },
- body: {
- meta: {
- id: 'string',
- 'user.display': 'string',
- 'transaction.duration': 'duration',
- 'project.id': 'integer',
- timestamp: 'date',
- },
- data: [
- {
- id: 'deadbeef',
- 'user.display': '[email protected]',
- 'transaction.duration': 400,
- 'project.id': 2,
- timestamp: '2020-05-21T15:31:18+00:00',
- },
- ],
- },
- match: [
- (_url, options) => {
- return options.query?.field?.includes('user.display');
- },
- ],
- });
- // Eventsv2 Mock totals for status breakdown
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/eventsv2/',
- body: {
- meta: {
- 'transaction.status': 'string',
- count: 'number',
- },
- data: [
- {
- count: 2,
- 'transaction.status': 'ok',
- },
- ],
- },
- match: [
- (_url, options) => {
- return options.query?.field?.includes('transaction.status');
- },
- ],
- });
- // Events Mock totals for the sidebar and other summary data
+ // [Metrics Enhanced] Events Mock totals for the sidebar and other summary data
MockApiClient.addMockResponse({
url: '/organizations/org-slug/events/',
body: {
@@ -230,24 +181,27 @@ describe('Performance > TransactionSummary', function () {
'tpm()': 'number',
project_threshold_config: 'string',
},
+ isMetricsData: true,
},
data: [
{
- 'count()': 2,
- 'apdex()': 0.6,
- 'count_miserable_user()': 122,
- 'user_misery()': 0.114,
- 'count_unique_user()': 1,
- 'p95()': 750.123,
+ 'count()': 200,
+ 'apdex()': 0.5,
+ 'count_miserable_user()': 120,
+ 'user_misery()': 0.1,
+ 'count_unique_user()': 100,
+ 'p95()': 731.3132,
'failure_rate()': 1,
- 'tpm()': 1,
+ 'tpm()': 100,
project_threshold_config: ['duration', 300],
},
],
},
match: [
(_url, options) => {
- return options.query?.field?.includes('p95()');
+ const isMetricsEnhanced =
+ options.query?.dataset === DiscoverDatasets.METRICS_ENHANCED;
+ return options.query?.field?.includes('p95()') && isMetricsEnhanced;
},
],
});
@@ -473,7 +427,7 @@ describe('Performance > TransactionSummary', function () {
jest.restoreAllMocks();
});
- describe('with discover', function () {
+ describe('with events', function () {
it('renders basic UI elements', async function () {
const {organization, router, routerContext} = initializeData();
@@ -508,11 +462,6 @@ describe('Performance > TransactionSummary', function () {
screen.getByRole('button', {name: 'Filter Slow Transactions (p95)'})
).toBeInTheDocument();
- // Ensure ops breakdown filter exists
- expect(
- screen.getByRole('button', {name: 'Filter by operation'})
- ).toBeInTheDocument();
-
// Ensure create alert from discover is hidden without metric alert
expect(
screen.queryByRole('button', {name: 'Create Alert'})
@@ -562,7 +511,7 @@ describe('Performance > TransactionSummary', function () {
});
it('renders sidebar widgets', async function () {
- const {organization, router, routerContext} = initializeData();
+ const {organization, router, routerContext} = initializeData({});
render(<TestComponent router={router} location={router.location} />, {
context: routerContext,
@@ -808,7 +757,9 @@ describe('Performance > TransactionSummary', function () {
body: [],
});
- const {organization, router, routerContext} = initializeData({});
+ const {organization, router, routerContext} = initializeData({
+ features: ['performance-suspect-spans-view'],
+ });
render(<TestComponent router={router} location={router.location} />, {
context: routerContext,
@@ -860,13 +811,8 @@ describe('Performance > TransactionSummary', function () {
'foo, bar, 100% of all events. View events with this tag value.'
)
);
- await userEvent.click(
- await screen.findByLabelText(
- 'user, id:100, 100% of all events. View events with this tag value.'
- )
- );
- expect(router.push).toHaveBeenCalledTimes(3);
+ expect(router.push).toHaveBeenCalledTimes(2);
expect(router.push).toHaveBeenNthCalledWith(1, {
query: {
@@ -885,83 +831,47 @@ describe('Performance > TransactionSummary', function () {
transactionCursor: '1:0:0',
},
});
-
- expect(router.push).toHaveBeenNthCalledWith(3, {
- query: {
- project: '2',
- query: 'user:"id:100"',
- transaction: '/performance',
- transactionCursor: '1:0:0',
- },
- });
});
- });
- describe('with events', function () {
- it('renders basic UI elements', async function () {
- const {organization, router, routerContext} = initializeData();
+ it('does not use MEP dataset for stats query without features', async function () {
+ const {organization, router, routerContext} = initializeData({
+ query: {query: 'transaction.op:pageload'}, // transaction.op is covered by the metrics dataset
+ features: [''], // No 'dynamic-sampling' feature to indicate it can use metrics dataset or metrics enhanced.
+ });
render(<TestComponent router={router} location={router.location} />, {
context: routerContext,
organization,
});
- // It shows the header
await screen.findByText('Transaction Summary');
- expect(screen.getByRole('heading', {name: '/performance'})).toBeInTheDocument();
- // It shows a chart
- expect(
- screen.getByRole('button', {name: 'Display Duration Breakdown'})
- ).toBeInTheDocument();
-
- // It shows a searchbar
- expect(screen.getByLabelText('Search events')).toBeInTheDocument();
-
- // It shows a table
- expect(screen.getByTestId('transactions-table')).toBeInTheDocument();
-
- // Ensure open in discover button exists.
- expect(screen.getByTestId('transaction-events-open')).toBeInTheDocument();
-
- // Ensure open issues button exists.
- expect(screen.getByRole('button', {name: 'Open in Issues'})).toBeInTheDocument();
-
- // Ensure transaction filter button exists
- expect(
- screen.getByRole('button', {name: 'Filter Slow Transactions (p95)'})
- ).toBeInTheDocument();
-
- // Ensure create alert from discover is hidden without metric alert
- expect(
- screen.queryByRole('button', {name: 'Create Alert'})
- ).not.toBeInTheDocument();
-
- // Ensure status breakdown exists
- expect(screen.getByText('Status Breakdown')).toBeInTheDocument();
- });
-
- it('renders feature flagged UI elements', function () {
- const {organization, router, routerContext} = initializeData({
- features: ['incidents'],
- });
-
- render(<TestComponent router={router} location={router.location} />, {
- context: routerContext,
- organization,
- });
+ await screen.findByRole('heading', {name: 'Apdex'});
+ expect(await screen.findByTestId('apdex-summary-value')).toHaveTextContent('0.6');
- // Ensure create alert from discover is shown with metric alerts
- expect(screen.getByRole('button', {name: 'Create Alert'})).toBeInTheDocument();
+ expect(eventStatsMock).toHaveBeenNthCalledWith(
+ 1,
+ expect.anything(),
+ expect.objectContaining({
+ query: expect.objectContaining({
+ environment: [],
+ interval: '30m',
+ partial: '1',
+ project: [2],
+ query:
+ 'transaction.op:pageload event.type:transaction transaction:/performance',
+ referrer: 'api.performance.transaction-summary.duration-chart',
+ statsPeriod: '14d',
+ yAxis: ['p50()', 'p75()', 'p95()', 'p99()', 'p100()'],
+ }),
+ })
+ );
});
- it('renders Web Vitals widget', async function () {
+ it('uses MEP dataset for stats query', async function () {
const {organization, router, routerContext} = initializeData({
- project: TestStubs.Project({teams, platform: 'javascript'}),
- query: {
- query:
- 'transaction.duration:<15m transaction.op:pageload event.type:transaction transaction:/organizations/:orgId/issues/',
- },
+ query: {query: 'transaction.op:pageload'}, // transaction.op is covered by the metrics dataset
+ features: ['dynamic-sampling', 'mep-rollout-flag'],
});
render(<TestComponent router={router} location={router.location} />, {
@@ -969,28 +879,23 @@ describe('Performance > TransactionSummary', function () {
organization,
});
- // It renders the web vitals widget
- await screen.findByRole('heading', {name: 'Web Vitals'});
-
- const vitalStatues = screen.getAllByTestId('vital-status');
- expect(vitalStatues).toHaveLength(3);
-
- expect(vitalStatues[0]).toHaveTextContent('31%');
- expect(vitalStatues[1]).toHaveTextContent('65%');
- expect(vitalStatues[2]).toHaveTextContent('3%');
- });
-
- it('renders sidebar widgets', async function () {
- const {organization, router, routerContext} = initializeData({});
-
- render(<TestComponent router={router} location={router.location} />, {
- context: routerContext,
- organization,
- });
+ await screen.findByText('Transaction Summary');
// Renders Apdex widget
await screen.findByRole('heading', {name: 'Apdex'});
- expect(await screen.findByTestId('apdex-summary-value')).toHaveTextContent('0.6');
+ expect(await screen.findByTestId('apdex-summary-value')).toHaveTextContent('0.5');
+
+ expect(eventStatsMock).toHaveBeenNthCalledWith(
+ 1,
+ expect.anything(),
+ expect.objectContaining({
+ query: expect.objectContaining({
+ query:
+ 'transaction.op:pageload event.type:transaction transaction:/performance',
+ dataset: 'metricsEnhanced',
+ }),
+ })
+ );
// Renders Failure Rate widget
expect(screen.getByRole('heading', {name: 'Failure Rate'})).toBeInTheDocument();
@@ -1003,212 +908,63 @@ describe('Performance > TransactionSummary', function () {
expect(screen.getByTestId('count-percentage-summary-value')).toHaveTextContent(
'100%'
);
- });
-
- it('fetches transaction threshold', function () {
- const {organization, router, routerContext} = initializeData();
-
- const getTransactionThresholdMock = MockApiClient.addMockResponse({
- url: '/organizations/org-slug/project-transaction-threshold-override/',
- method: 'GET',
- body: {
- threshold: '800',
- metric: 'lcp',
- },
- });
-
- const getProjectThresholdMock = MockApiClient.addMockResponse({
- url: '/projects/org-slug/project-slug/transaction-threshold/configure/',
- method: 'GET',
- body: {
- threshold: '200',
- metric: 'duration',
- },
- });
-
- render(<TestComponent router={router} location={router.location} />, {
- context: routerContext,
- organization,
- });
- expect(getTransactionThresholdMock).toHaveBeenCalledTimes(1);
- expect(getProjectThresholdMock).not.toHaveBeenCalled();
+ expect(
+ screen.queryByTestId('search-metrics-fallback-warning')
+ ).not.toBeInTheDocument();
});
- it('fetches project transaction threshdold', async function () {
- const {organization, router, routerContext} = initializeData();
-
- const getTransactionThresholdMock = MockApiClient.addMockResponse({
- url: '/organizations/org-slug/project-transaction-threshold-override/',
- method: 'GET',
- statusCode: 404,
+ it('uses MEP dataset for stats query and shows fallback warning', async function () {
+ MockApiClient.addMockResponse({
+ url: '/organizations/org-slug/issues/?limit=5&project=2&query=has%3Anot-compatible%20is%3Aunresolved%20transaction%3A%2Fperformance&sort=new&statsPeriod=14d',
+ body: [],
});
-
- const getProjectThresholdMock = MockApiClient.addMockResponse({
- url: '/projects/org-slug/project-slug/transaction-threshold/configure/',
- method: 'GET',
+ MockApiClient.addMockResponse({
+ url: '/organizations/org-slug/events/',
body: {
- threshold: '200',
- metric: 'duration',
- },
- });
-
- render(<TestComponent router={router} location={router.location} />, {
- context: routerContext,
- organization,
- });
-
- await screen.findByText('Transaction Summary');
-
- expect(getTransactionThresholdMock).toHaveBeenCalledTimes(1);
- expect(getProjectThresholdMock).toHaveBeenCalledTimes(1);
- });
-
- it('triggers a navigation on search', async function () {
- const {organization, router, routerContext} = initializeData();
-
- render(<TestComponent router={router} location={router.location} />, {
- context: routerContext,
- organization,
- });
-
- // Fill out the search box, and submit it.
- await userEvent.type(
- screen.getByLabelText('Search events'),
- 'user.email:uhoh*{enter}'
- );
-
- // Check the navigation.
- expect(browserHistory.push).toHaveBeenCalledTimes(1);
- expect(browserHistory.push).toHaveBeenCalledWith({
- pathname: undefined,
- query: {
- transaction: '/performance',
- project: '2',
- statsPeriod: '14d',
- query: 'user.email:uhoh*',
- transactionCursor: '1:0:0',
- },
- });
- });
-
- it('can mark a transaction as key', async function () {
- const {organization, router, routerContext} = initializeData();
-
- render(<TestComponent router={router} location={router.location} />, {
- context: routerContext,
- organization,
- });
-
- const mockUpdate = MockApiClient.addMockResponse({
- url: `/organizations/org-slug/key-transactions/`,
- method: 'POST',
- body: {},
- });
-
- await screen.findByRole('button', {name: 'Star for Team'});
-
- // Click the key transaction button
- await userEvent.click(screen.getByRole('button', {name: 'Star for Team'}));
-
- await userEvent.click(screen.getByText('team1'));
-
- // Ensure request was made.
- expect(mockUpdate).toHaveBeenCalled();
- });
-
- it('triggers a navigation on transaction filter', async function () {
- const {organization, router, routerContext} = initializeData();
-
- render(<TestComponent router={router} location={router.location} />, {
- context: routerContext,
- organization,
- });
-
- await screen.findByText('Transaction Summary');
- await waitFor(() => {
- expect(screen.queryByTestId('loading-indicator')).not.toBeInTheDocument();
- });
-
- // Open the transaction filter dropdown
- await userEvent.click(
- screen.getByRole('button', {name: 'Filter Slow Transactions (p95)'})
- );
-
- await userEvent.click(screen.getAllByText('Slow Transactions (p95)')[1]);
-
- // Check the navigation.
- expect(browserHistory.push).toHaveBeenCalledWith({
- pathname: undefined,
- query: {
- transaction: '/performance',
- project: '2',
- showTransactions: 'slow',
- transactionCursor: undefined,
- },
- });
- });
-
- it('renders pagination buttons', async function () {
- const {organization, router, routerContext} = initializeData();
-
- render(<TestComponent router={router} location={router.location} />, {
- context: routerContext,
- organization,
- });
-
- await screen.findByText('Transaction Summary');
-
- expect(await screen.findByLabelText('Previous')).toBeInTheDocument();
-
- // Click the 'next' button
- await userEvent.click(screen.getByLabelText('Next'));
-
- // Check the navigation.
- expect(browserHistory.push).toHaveBeenCalledWith({
- pathname: undefined,
- query: {
- transaction: '/performance',
- project: '2',
- transactionCursor: '2:0:0',
+ meta: {
+ fields: {
+ 'count()': 'number',
+ 'apdex()': 'number',
+ 'count_miserable_user()': 'number',
+ 'user_misery()': 'number',
+ 'count_unique_user()': 'number',
+ 'p95()': 'number',
+ 'failure_rate()': 'number',
+ 'tpm()': 'number',
+ project_threshold_config: 'string',
+ },
+ isMetricsData: false, // The total response is setting the metrics fallback behaviour.
+ },
+ data: [
+ {
+ 'count()': 200,
+ 'apdex()': 0.5,
+ 'count_miserable_user()': 120,
+ 'user_misery()': 0.1,
+ 'count_unique_user()': 100,
+ 'p95()': 731.3132,
+ 'failure_rate()': 1,
+ 'tpm()': 100,
+ project_threshold_config: ['duration', 300],
+ },
+ ],
},
- });
- });
-
- it('forwards conditions to related issues', async function () {
- const issueGet = MockApiClient.addMockResponse({
- url: '/organizations/org-slug/issues/?limit=5&project=2&query=tag%3Avalue%20is%3Aunresolved%20transaction%3A%2Fperformance&sort=new&statsPeriod=14d',
- body: [],
- });
-
- const {organization, router, routerContext} = initializeData({
- query: {query: 'tag:value'},
- });
-
- render(<TestComponent router={router} location={router.location} />, {
- context: routerContext,
- organization,
- });
-
- await screen.findByText('Transaction Summary');
-
- expect(issueGet).toHaveBeenCalled();
- });
-
- it('does not forward event type to related issues', async function () {
- const issueGet = MockApiClient.addMockResponse({
- url: '/organizations/org-slug/issues/?limit=5&project=2&query=tag%3Avalue%20is%3Aunresolved%20transaction%3A%2Fperformance&sort=new&statsPeriod=14d',
- body: [],
match: [
- (_, options) => {
- // event.type must NOT be in the query params
- return !options.query?.query?.includes('event.type');
+ (_url, options) => {
+ const isMetricsEnhanced =
+ options.query?.dataset === DiscoverDatasets.METRICS_ENHANCED;
+ return (
+ options.query?.field?.includes('p95()') &&
+ isMetricsEnhanced &&
+ options.query?.query?.includes('not-compatible')
+ );
},
],
});
-
const {organization, router, routerContext} = initializeData({
- query: {query: 'tag:value event.type:transaction'},
+ query: {query: 'transaction.op:pageload has:not-compatible'}, // Adds incompatible w/ metrics tag
+ features: ['dynamic-sampling', 'mep-rollout-flag'],
});
render(<TestComponent router={router} location={router.location} />, {
@@ -1218,89 +974,35 @@ describe('Performance > TransactionSummary', function () {
await screen.findByText('Transaction Summary');
- expect(issueGet).toHaveBeenCalled();
- });
-
- it('renders the suspect spans table if the feature is enabled', async function () {
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/events-spans-performance/',
- body: [],
- });
-
- const {organization, router, routerContext} = initializeData({
- features: ['performance-suspect-spans-view'],
- });
-
- render(<TestComponent router={router} location={router.location} />, {
- context: routerContext,
- organization,
- });
-
- expect(await screen.findByText('Suspect Spans')).toBeInTheDocument();
- });
-
- it('adds search condition on transaction status when clicking on status breakdown', async function () {
- const {organization, router, routerContext} = initializeData();
-
- render(<TestComponent router={router} location={router.location} />, {
- context: routerContext,
- organization,
- });
-
- await screen.findByTestId('status-ok');
-
- await userEvent.click(screen.getByTestId('status-ok'));
+ // Renders Apdex widget
+ await screen.findByRole('heading', {name: 'Apdex'});
+ expect(await screen.findByTestId('apdex-summary-value')).toHaveTextContent('0.5');
- expect(browserHistory.push).toHaveBeenCalledTimes(1);
- expect(browserHistory.push).toHaveBeenCalledWith(
+ expect(eventStatsMock).toHaveBeenNthCalledWith(
+ 1,
+ expect.anything(),
expect.objectContaining({
query: expect.objectContaining({
- query: expect.stringContaining('transaction.status:ok'),
+ query:
+ 'transaction.op:pageload has:not-compatible event.type:transaction transaction:/performance',
+ dataset: 'metricsEnhanced',
}),
})
);
- });
-
- it('appends tag value to existing query when clicked', async function () {
- const {organization, router, routerContext} = initializeData();
- render(<TestComponent router={router} location={router.location} />, {
- context: routerContext,
- organization,
- });
-
- await screen.findByText('Tag Summary');
+ // Renders Failure Rate widget
+ expect(screen.getByRole('heading', {name: 'Failure Rate'})).toBeInTheDocument();
+ expect(screen.getByTestId('failure-rate-summary-value')).toHaveTextContent('100%');
- await userEvent.click(
- await screen.findByLabelText(
- 'environment, dev, 100% of all events. View events with this tag value.'
- )
- );
- await userEvent.click(
- await screen.findByLabelText(
- 'foo, bar, 100% of all events. View events with this tag value.'
- )
+ // Renders TPM widget
+ expect(
+ screen.getByRole('heading', {name: 'Percentage of Total Transactions'})
+ ).toBeInTheDocument();
+ expect(screen.getByTestId('count-percentage-summary-value')).toHaveTextContent(
+ '100%'
);
- expect(router.push).toHaveBeenCalledTimes(2);
-
- expect(router.push).toHaveBeenNthCalledWith(1, {
- query: {
- project: '2',
- query: 'tags[environment]:dev',
- transaction: '/performance',
- transactionCursor: '1:0:0',
- },
- });
-
- expect(router.push).toHaveBeenNthCalledWith(2, {
- query: {
- project: '2',
- query: 'foo:bar',
- transaction: '/performance',
- transactionCursor: '1:0:0',
- },
- });
+ expect(screen.getByTestId('search-metrics-fallback-warning')).toBeInTheDocument();
});
});
});
diff --git a/static/app/views/performance/transactionSummary/transactionOverview/index.tsx b/static/app/views/performance/transactionSummary/transactionOverview/index.tsx
index 379948d8bddebb..833d001b6bc232 100644
--- a/static/app/views/performance/transactionSummary/transactionOverview/index.tsx
+++ b/static/app/views/performance/transactionSummary/transactionOverview/index.tsx
@@ -10,6 +10,10 @@ import {useDiscoverQuery} from 'sentry/utils/discover/discoverQuery';
import EventView from 'sentry/utils/discover/eventView';
import {Column, isAggregateField, QueryFieldValue} from 'sentry/utils/discover/fields';
import {WebVital} from 'sentry/utils/fields';
+import {
+ getIsMetricsDataFromResults,
+ useMEPDataContext,
+} from 'sentry/utils/performance/contexts/metricsEnhancedPerformanceDataContext';
import {
MEPSettingProvider,
useMEPSettingContext,
@@ -93,11 +97,8 @@ function OverviewContentWrapper(props: ChildProps) {
} = props;
const mepSetting = useMEPSettingContext();
- const queryExtras = getTransactionMEPParamsIfApplicable(
- mepSetting,
- organization,
- location
- );
+ const mepContext = useMEPDataContext();
+ const queryExtras = getTransactionMEPParamsIfApplicable(mepSetting, organization);
const queryData = useDiscoverQuery({
eventView: getTotalsEventView(organization, eventView),
@@ -131,6 +132,11 @@ function OverviewContentWrapper(props: ChildProps) {
referrer: 'api.performance.transaction-summary',
});
+ useEffect(() => {
+ const isMetricsData = getIsMetricsDataFromResults(queryData.data);
+ mepContext.setIsMetricsData(isMetricsData);
+ }, [mepContext, queryData.data]);
+
const {data: tableData, isLoading, error} = queryData;
const {
data: unfilteredTableData,
diff --git a/static/app/views/performance/transactionSummary/transactionOverview/sidebarCharts.tsx b/static/app/views/performance/transactionSummary/transactionOverview/sidebarCharts.tsx
index 77771fa383345a..a79ea4a2ab45a1 100644
--- a/static/app/views/performance/transactionSummary/transactionOverview/sidebarCharts.tsx
+++ b/static/app/views/performance/transactionSummary/transactionOverview/sidebarCharts.tsx
@@ -222,11 +222,7 @@ function SidebarChartsContainer({
const utc = normalizeDateTimeParams(location.query).utc === 'true';
const mepSetting = useMEPSettingContext();
- const queryExtras = getTransactionMEPParamsIfApplicable(
- mepSetting,
- organization,
- location
- );
+ const queryExtras = getTransactionMEPParamsIfApplicable(mepSetting, organization);
const axisLineConfig = {
scale: true,
diff --git a/static/app/views/performance/transactionSummary/transactionOverview/userStats.tsx b/static/app/views/performance/transactionSummary/transactionOverview/userStats.tsx
index 3e7b59b3033932..b49bc203d0b1a2 100644
--- a/static/app/views/performance/transactionSummary/transactionOverview/userStats.tsx
+++ b/static/app/views/performance/transactionSummary/transactionOverview/userStats.tsx
@@ -74,11 +74,7 @@ function UserStats({
});
const mepSetting = useMEPSettingContext();
- const queryExtras = getTransactionMEPParamsIfApplicable(
- mepSetting,
- organization,
- location
- );
+ const queryExtras = getTransactionMEPParamsIfApplicable(mepSetting, organization);
return (
<Fragment>
diff --git a/static/app/views/performance/transactionSummary/transactionOverview/utils.tsx b/static/app/views/performance/transactionSummary/transactionOverview/utils.tsx
index d26f86f7651ace..3f1ecf403462d0 100644
--- a/static/app/views/performance/transactionSummary/transactionOverview/utils.tsx
+++ b/static/app/views/performance/transactionSummary/transactionOverview/utils.tsx
@@ -3,6 +3,7 @@ import {Location} from 'history';
import {Organization} from 'sentry/types';
import EventView from 'sentry/utils/discover/eventView';
import {AggregationKeyWithAlias, QueryFieldValue} from 'sentry/utils/discover/fields';
+import {MetricsEnhancedPerformanceDataContext} from 'sentry/utils/performance/contexts/metricsEnhancedPerformanceDataContext';
import {
canUseMetricsData,
MetricsEnhancedSettingContext,
@@ -11,22 +12,17 @@ import {decodeScalar} from 'sentry/utils/queryString';
import {MutableSearch} from 'sentry/utils/tokenizeSearch';
import {getMEPQueryParams} from 'sentry/views/performance/landing/widgets/utils';
-export function canUseTransactionMetricsData(organization, location) {
+export function canUseTransactionMetricsData(
+ organization: Organization,
+ mepDataContext: MetricsEnhancedPerformanceDataContext
+) {
const isUsingMetrics = canUseMetricsData(organization);
if (!isUsingMetrics) {
return false;
}
- // span op breakdown filters aren't compatible with metrics
- const breakdown = decodeScalar(location.query.breakdown, '');
- if (breakdown) {
- return false;
- }
-
- // in the short term, using any filter will force indexed event search
- const query = decodeScalar(location.query.query, '');
- if (query) {
+ if (mepDataContext.isMetricsData === false) {
return false;
}
@@ -34,18 +30,6 @@ export function canUseTransactionMetricsData(organization, location) {
}
export function getTransactionMEPParamsIfApplicable(
- mepContext: MetricsEnhancedSettingContext,
- organization: Organization,
- location: Location
-) {
- if (!canUseTransactionMetricsData(organization, location)) {
- return undefined;
- }
-
- return getMEPQueryParams(mepContext);
-}
-
-export function getTransactionTotalsMEPParamsIfApplicable(
mepContext: MetricsEnhancedSettingContext,
organization: Organization
) {
@@ -53,7 +37,7 @@ export function getTransactionTotalsMEPParamsIfApplicable(
return undefined;
}
- return getMEPQueryParams(mepContext);
+ return getMEPQueryParams(mepContext, true);
}
export function getUnfilteredTotalsEventView(
|
abacb2842f6a80acc3d5f989420480a683f79332
|
2019-11-15 01:17:17
|
Evan Purkhiser
|
fix(member-invites): Use withTeams over organizations.teams (#15596)
| false
|
Use withTeams over organizations.teams (#15596)
|
fix
|
diff --git a/src/sentry/static/sentry/app/components/modals/inviteMembersModal/index.tsx b/src/sentry/static/sentry/app/components/modals/inviteMembersModal/index.tsx
index 7fc5a94384591f..e593f70a8093c1 100644
--- a/src/sentry/static/sentry/app/components/modals/inviteMembersModal/index.tsx
+++ b/src/sentry/static/sentry/app/components/modals/inviteMembersModal/index.tsx
@@ -11,8 +11,9 @@ import Button from 'app/components/button';
import HookOrDefault from 'app/components/hookOrDefault';
import space from 'app/styles/space';
import AsyncComponent from 'app/components/asyncComponent';
-import {Organization} from 'app/types';
+import {Organization, Team} from 'app/types';
import withLatestContext from 'app/utils/withLatestContext';
+import withTeams from 'app/utils/withTeams';
import LoadingIndicator from 'app/components/loadingIndicator';
import Tooltip from 'app/components/tooltip';
@@ -22,6 +23,7 @@ import InviteRowControl from './inviteRowControl';
type Props = AsyncComponent['props'] &
ModalRenderProps & {
organization: Organization;
+ teams: Team[];
source?: string;
};
@@ -281,7 +283,7 @@ class InviteMembersModal extends AsyncComponent<Props, State> {
}
render() {
- const {Footer, closeModal, organization} = this.props;
+ const {Footer, closeModal, organization, teams: allTeams} = this.props;
const {pendingInvites, sendingInvites, complete, inviteStatus, member} = this.state;
const disableInputs = sendingInvites || complete;
@@ -331,7 +333,7 @@ class InviteMembersModal extends AsyncComponent<Props, State> {
teams={[...teams]}
roleOptions={member ? member.roles : MEMBER_ROLES}
roleDisabledUnallowed={this.willInvite}
- teamOptions={organization.teams}
+ teamOptions={allTeams}
inviteStatus={inviteStatus}
onRemove={() => this.removeInviteRow(i)}
onChangeEmails={opts => this.setEmails(opts.map(v => v.value), i)}
@@ -404,7 +406,7 @@ class InviteMembersModal extends AsyncComponent<Props, State> {
return (
<InviteModalHook
- organization={this.props.organization}
+ organization={organization}
willInvite={this.willInvite}
onSendInvites={this.sendInvites}
>
@@ -485,4 +487,4 @@ const modalClassName = css`
}
`;
export {modalClassName};
-export default withLatestContext(InviteMembersModal);
+export default withLatestContext(withTeams(InviteMembersModal));
|
0c860be04d4a04699182190a3196925823b5d046
|
2023-08-16 00:43:29
|
Seiji Chew
|
chore(codeowners): Update codeowners with project creation files (#54774)
| false
|
Update codeowners with project creation files (#54774)
|
chore
|
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 3052615fbd6c6d..761f41b3b8d0d2 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -361,19 +361,17 @@ yarn.lock @getsentry/owners-js-de
## Enterprise
-/static/app/views/organizationStats @getsentry/enterprise
-/src/sentry/api/endpoints/organization_stats*.py @getsentry/enterprise
-
-/src/sentry/api/endpoints/organization_auditlogs.py @getsentry/enterprise
-
-/static/app/views/settings/organizationAuth/ @getsentry/enterprise
-/tests/sentry/api/endpoints/test_auth*.py @getsentry/enterprise
-
-/tests/sentry/api/test_data_secrecy.py @getsentry/enterprise
-
-/src/sentry/scim/ @getsentry/enterprise
-/tests/sentry/api/test_scim*.py @getsentry/enterprise
-/src/sentry/tasks/integrations/github/pr_comment.py @getsentry/enterprise
+/static/app/views/organizationStats @getsentry/enterprise
+/src/sentry/api/endpoints/organization_stats*.py @getsentry/enterprise
+/src/sentry/api/endpoints/organization_auditlogs.py @getsentry/enterprise
+/static/app/views/settings/organizationAuth/ @getsentry/enterprise
+/tests/sentry/api/endpoints/test_auth*.py @getsentry/enterprise
+/tests/sentry/api/test_data_secrecy.py @getsentry/enterprise
+/src/sentry/scim/ @getsentry/enterprise
+/tests/sentry/api/test_scim*.py @getsentry/enterprise
+/src/sentry/tasks/integrations/github/pr_comment.py @getsentry/enterprise
+/src/sentry/api/endpoints/organization_projects_experiment.py @getsentry/enterprise
+/tests/sentry/api/endpoints/test_organization_projects_experiment.py @getsentry/enterprise
## End of Enterprise
|
3966a9ce921656b72a808a290cafc5c7bed589f8
|
2024-01-24 00:00:40
|
Jonas
|
deps(platformicons): bump to 5.10 which includes optimized svgs (#63686)
| false
|
bump to 5.10 which includes optimized svgs (#63686)
|
deps
|
diff --git a/package.json b/package.json
index 171164a6cd8372..fbb3edc4982be5 100644
--- a/package.json
+++ b/package.json
@@ -136,7 +136,7 @@
"papaparse": "^5.3.2",
"pegjs": "^0.10.0",
"pegjs-loader": "^0.5.6",
- "platformicons": "^5.9.2",
+ "platformicons": "^5.10.0",
"po-catalog-loader": "2.0.0",
"prettier": "3.0.3",
"prismjs": "^1.29.0",
diff --git a/yarn.lock b/yarn.lock
index 07fbb671200e2e..8331df56a3a960 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -8719,10 +8719,10 @@ platform@^1.3.3:
resolved "https://registry.yarnpkg.com/platform/-/platform-1.3.6.tgz#48b4ce983164b209c2d45a107adb31f473a6e7a7"
integrity sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==
-platformicons@^5.9.2:
- version "5.9.2"
- resolved "https://registry.yarnpkg.com/platformicons/-/platformicons-5.9.2.tgz#36513c899663df165bba85d1bde930baebaaa093"
- integrity sha512-5ll5KOUkTMJEdS2v5GJy1tYdQPRQ+JkjvP1dkeiR5pp7zHq4+OGYrLw02dSfGRvf21btbu/P6by9wSTh0FxaBQ==
+platformicons@^5.10.0:
+ version "5.10.0"
+ resolved "https://registry.yarnpkg.com/platformicons/-/platformicons-5.10.0.tgz#4f3269ed2401810faee88495ba3d530a613ed66b"
+ integrity sha512-wEFi1Vt0fld9woHmqkP/nAZluAztnO8i2dkzfXPpTY5rx/LeTrcwlZUbaxyHEesMm+oDHRGNi8LukEIeo1uJuQ==
dependencies:
"@types/node" "*"
"@types/react" "*"
|
7c6356096773524de83f19b1614fa54da5e1e21a
|
2025-03-19 16:34:45
|
Ogi
|
fix(demo-mode): session expired (#87271)
| false
|
session expired (#87271)
|
fix
|
diff --git a/static/app/api.tsx b/static/app/api.tsx
index a2dd950fe30f09..fd0d6b17eee54d 100644
--- a/static/app/api.tsx
+++ b/static/app/api.tsx
@@ -13,6 +13,7 @@ import {
import controlsilopatterns from 'sentry/data/controlsiloUrlPatterns';
import {metric} from 'sentry/utils/analytics';
import {browserHistory} from 'sentry/utils/browserHistory';
+import {isDemoModeActive} from 'sentry/utils/demoMode';
import getCsrfToken from 'sentry/utils/getCsrfToken';
import {uniqueId} from 'sentry/utils/guid';
import RequestError from 'sentry/utils/requestError/requestError';
@@ -170,8 +171,10 @@ export const initApiClientErrorHandling = () =>
return true;
}
- // Otherwise, the user has become unauthenticated. Send them to auth
- Cookies.set('session_expired', '1');
+ if (!isDemoModeActive()) {
+ // Demo user can occasionally get 401s back. Otherwise, the user has become unauthenticated. Send them to auth
+ Cookies.set('session_expired', '1');
+ }
if (EXPERIMENTAL_SPA) {
browserHistory.replace('/auth/login/');
diff --git a/static/app/components/demo/demoHeader.tsx b/static/app/components/demo/demoHeader.tsx
index dd15f59aacf4a3..cca9e4c48bad04 100644
--- a/static/app/components/demo/demoHeader.tsx
+++ b/static/app/components/demo/demoHeader.tsx
@@ -11,9 +11,9 @@ import {
extraQueryParameter,
extraQueryParameterWithEmail,
isDemoModeActive,
- openDemoEmailModal,
urlAttachQueryParams,
} from 'sentry/utils/demoMode';
+import {openDemoEmailModal} from 'sentry/utils/demoMode/utils';
export const DEMO_HEADER_HEIGHT_PX = 70;
diff --git a/static/app/utils/demoMode/index.tsx b/static/app/utils/demoMode/index.tsx
index 3e9a12cbbacde5..48e67e537359ff 100644
--- a/static/app/utils/demoMode/index.tsx
+++ b/static/app/utils/demoMode/index.tsx
@@ -1,17 +1,6 @@
-import {setForceHide} from 'sentry/actionCreators/guides';
-import {Client} from 'sentry/api';
import ConfigStore from 'sentry/stores/configStore';
import {isActiveSuperuser} from 'sentry/utils/isActiveSuperuser';
-import {logout} from '../../actionCreators/account';
-import {demoEmailModal, demoSignupModal} from '../../actionCreators/modal';
-
-const SIGN_UP_MODAL_DELAY = 2 * 60 * 1000;
-
-const INACTIVITY_TIMEOUT_MS = 10 * 1000;
-
-const DEMO_MODE_EMAIL_KEY = 'demo-mode:email';
-
export function extraQueryParameter(): URLSearchParams {
const extraQueryString = window.SandboxData?.extraQueryString || '';
const extraQuery = new URLSearchParams(extraQueryString);
@@ -38,53 +27,3 @@ export function urlAttachQueryParams(url: string, params: URLSearchParams): stri
export function isDemoModeActive(): boolean {
return ConfigStore.get('demoMode') && !isActiveSuperuser();
}
-
-export function openDemoSignupModal() {
- if (!isDemoModeActive()) {
- return;
- }
- setTimeout(() => {
- demoSignupModal();
- }, SIGN_UP_MODAL_DELAY);
-}
-
-export function openDemoEmailModal() {
- if (!isDemoModeActive()) {
- return;
- }
-
- // email already added
- if (localStorage.getItem(DEMO_MODE_EMAIL_KEY)) {
- return;
- }
-
- demoEmailModal({
- onAddedEmail,
- onFailure: () => {
- setForceHide(false);
- },
- });
-}
-
-function onAddedEmail(email: string) {
- setForceHide(false);
- localStorage.setItem(DEMO_MODE_EMAIL_KEY, email);
- openDemoSignupModal();
-}
-
-let inactivityTimeout: number | undefined;
-
-window.addEventListener('blur', () => {
- if (isDemoModeActive()) {
- inactivityTimeout = window.setTimeout(() => {
- logout(new Client());
- }, INACTIVITY_TIMEOUT_MS);
- }
-});
-
-window.addEventListener('focus', () => {
- if (inactivityTimeout) {
- window.clearTimeout(inactivityTimeout);
- inactivityTimeout = undefined;
- }
-});
diff --git a/static/app/utils/demoMode/modal.tsx b/static/app/utils/demoMode/modal.tsx
new file mode 100644
index 00000000000000..e69de29bb2d1d6
diff --git a/static/app/utils/demoMode/utils.tsx b/static/app/utils/demoMode/utils.tsx
new file mode 100644
index 00000000000000..70adb346976f68
--- /dev/null
+++ b/static/app/utils/demoMode/utils.tsx
@@ -0,0 +1,63 @@
+import {logout} from 'sentry/actionCreators/account';
+import {setForceHide} from 'sentry/actionCreators/guides';
+import {Client} from 'sentry/api';
+
+import {demoEmailModal, demoSignupModal} from '../../actionCreators/modal';
+
+import {isDemoModeActive} from './index';
+
+const SIGN_UP_MODAL_DELAY = 2 * 60 * 1000;
+
+const DEMO_MODE_EMAIL_KEY = 'demo-mode:email';
+
+const INACTIVITY_TIMEOUT_MS = 10 * 1000;
+
+export function openDemoSignupModal() {
+ if (!isDemoModeActive()) {
+ return;
+ }
+ setTimeout(() => {
+ demoSignupModal();
+ }, SIGN_UP_MODAL_DELAY);
+}
+
+export function openDemoEmailModal() {
+ if (!isDemoModeActive()) {
+ return;
+ }
+
+ // email already added
+ if (localStorage.getItem(DEMO_MODE_EMAIL_KEY)) {
+ return;
+ }
+
+ demoEmailModal({
+ onAddedEmail,
+ onFailure: () => {
+ setForceHide(false);
+ },
+ });
+}
+
+function onAddedEmail(email: string) {
+ setForceHide(false);
+ localStorage.setItem(DEMO_MODE_EMAIL_KEY, email);
+ openDemoSignupModal();
+}
+
+let inactivityTimeout: number | undefined;
+
+window.addEventListener('blur', () => {
+ if (isDemoModeActive()) {
+ inactivityTimeout = window.setTimeout(() => {
+ logout(new Client());
+ }, INACTIVITY_TIMEOUT_MS);
+ }
+});
+
+window.addEventListener('focus', () => {
+ if (inactivityTimeout) {
+ window.clearTimeout(inactivityTimeout);
+ inactivityTimeout = undefined;
+ }
+});
|
b3f39c22a8e4091225cff850100e1dabdf075ff2
|
2025-01-08 04:43:13
|
Hubert Deng
|
feat(devservices): Add rabbitmq (#83047)
| false
|
Add rabbitmq (#83047)
|
feat
|
diff --git a/devservices/config.yml b/devservices/config.yml
index f4cf7a263b0160..03e151e0d6c6d4 100644
--- a/devservices/config.yml
+++ b/devservices/config.yml
@@ -49,12 +49,15 @@ x-sentry-service-config:
branch: main
repo_link: https://github.com/getsentry/taskbroker.git
mode: containerized
+ rabbitmq:
+ description: Messaging and streaming broker
modes:
default: [snuba, postgres, relay]
migrations: [postgres, redis]
acceptance-ci: [postgres, snuba, chartcuterie]
taskbroker: [snuba, postgres, relay, taskbroker]
backend-ci: [snuba, postgres, redis, bigtable, redis-cluster, symbolicator]
+ rabbitmq: [postgres, snuba, rabbitmq]
services:
postgres:
@@ -111,6 +114,17 @@ services:
- host.docker.internal:host-gateway
environment:
- IP=0.0.0.0
+ rabbitmq:
+ image: ghcr.io/getsentry/image-mirror-library-rabbitmq:3-management
+ ports:
+ - '127.0.0.1:5672:5672'
+ - '127.0.0.1:15672:15672'
+ networks:
+ - devservices
+ extra_hosts:
+ - host.docker.internal:host-gateway
+ environment:
+ - IP=0.0.0.0
networks:
devservices:
|
4e0bd4d5943274127b0fa28bb926d0bdd3411efc
|
2024-11-26 23:10:23
|
Gabe Villalobos
|
ref(ecosystem): Changes IntegrationFormError metrics from failures to halts (#81276)
| false
|
Changes IntegrationFormError metrics from failures to halts (#81276)
|
ref
|
diff --git a/src/sentry/rules/actions/integrations/create_ticket/utils.py b/src/sentry/rules/actions/integrations/create_ticket/utils.py
index 7df60330ef03b3..ba45ad1aba7468 100644
--- a/src/sentry/rules/actions/integrations/create_ticket/utils.py
+++ b/src/sentry/rules/actions/integrations/create_ticket/utils.py
@@ -16,6 +16,7 @@
from sentry.integrations.services.integration.model import RpcIntegration
from sentry.integrations.services.integration.service import integration_service
from sentry.models.grouplink import GroupLink
+from sentry.shared_integrations.exceptions import IntegrationFormError
from sentry.silo.base import region_silo_function
from sentry.types.rules import RuleFuture
from sentry.utils import metrics
@@ -130,17 +131,11 @@ def create_issue(event: GroupEvent, futures: Sequence[RuleFuture]) -> None:
try:
response = installation.create_issue(data)
except Exception as e:
- logger.info(
- "%s.rule_trigger.create_ticket.failure",
- provider,
- extra={
- "rule_id": rule_id,
- "provider": provider,
- "integration_id": integration.id,
- "error_message": str(e),
- "exception_type": type(e).__name__,
- },
- )
+ if isinstance(e, IntegrationFormError):
+ # Most of the time, these aren't explicit failures, they're
+ # some misconfiguration of an issue field - typically Jira.
+ lifecycle.record_halt(e)
+
metrics.incr(
f"{provider}.rule_trigger.create_ticket.failure",
tags={
diff --git a/tests/sentry/integrations/jira/test_ticket_action.py b/tests/sentry/integrations/jira/test_ticket_action.py
index 3aa0bc05bb674b..b1c36471deb665 100644
--- a/tests/sentry/integrations/jira/test_ticket_action.py
+++ b/tests/sentry/integrations/jira/test_ticket_action.py
@@ -10,24 +10,19 @@
from sentry.integrations.models.external_issue import ExternalIssue
from sentry.integrations.types import EventLifecycleOutcome
from sentry.models.rule import Rule
-from sentry.shared_integrations.exceptions import ApiInvalidRequestError, IntegrationError
+from sentry.shared_integrations.exceptions import (
+ ApiInvalidRequestError,
+ IntegrationError,
+ IntegrationFormError,
+)
from sentry.testutils.cases import RuleTestCase
from sentry.testutils.skips import requires_snuba
from sentry.types.rules import RuleFuture
+from sentry.utils import json
pytestmark = [requires_snuba]
-class BrokenJiraMock(MockJira):
- """
- Subclass of MockJira client, which implements a broken create_issue method
- to simulate a misconfigured alert rule for Jira.
- """
-
- def create_issue(self, raw_form_data):
- raise ApiInvalidRequestError("Invalid data entered")
-
-
class JiraTicketRulesTestCase(RuleTestCase, BaseAPITestCase):
rule_cls = JiraCreateTicketAction
mock_jira = None
@@ -38,11 +33,6 @@ def get_client(self):
self.mock_jira = MockJira()
return self.mock_jira
- def get_broken_client(self):
- if not self.broken_mock_jira:
- self.broken_mock_jira = BrokenJiraMock()
- return self.broken_mock_jira
-
def setUp(self):
super().setUp()
self.project_name = "Jira Cloud"
@@ -140,10 +130,14 @@ def test_ticket_rules(self, mock_record_event):
mock_record_event.assert_called_with(EventLifecycleOutcome.SUCCESS, None)
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_failure")
- def test_misconfigured_ticket_rule(self, mock_record_failure):
+ @mock.patch.object(MockJira, "create_issue")
+ def test_misconfigured_ticket_rule(self, mock_create_issue, mock_record_failure):
+ def raise_api_error(*args, **kwargs):
+ raise ApiInvalidRequestError("Invalid data entered")
+
+ mock_create_issue.side_effect = raise_api_error
with mock.patch(
- "sentry.integrations.jira.integration.JiraIntegration.get_client",
- self.get_broken_client,
+ "sentry.integrations.jira.integration.JiraIntegration.get_client", self.get_client
):
response = self.configure_valid_alert_rule()
@@ -195,3 +189,32 @@ def test_fails_validation(self):
)
assert response.status_code == 400
assert response.data["actions"][0] == "Must configure issue link settings."
+
+ @mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_halt")
+ @mock.patch.object(MockJira, "create_issue")
+ def test_fails_with_field_configuration_error(self, mock_create_issue, mock_record_halt):
+ # Mock an error from the client response that cotains a field
+
+ def raise_api_error_with_payload(*args, **kwargs):
+ raise ApiInvalidRequestError(json.dumps({"errors": {"foo": "bar"}}))
+
+ mock_create_issue.side_effect = raise_api_error_with_payload
+ with mock.patch(
+ "sentry.integrations.jira.integration.JiraIntegration.get_client", self.get_client
+ ):
+ response = self.configure_valid_alert_rule()
+
+ rule_object = Rule.objects.get(id=response.data["id"])
+ event = self.get_event()
+
+ with pytest.raises(IntegrationFormError):
+ # Trigger its `after`, but with a broken client which should raise
+ # an ApiInvalidRequestError, which is reraised as an IntegrationError.
+ self.trigger(event, rule_object)
+
+ assert mock_record_halt.call_count == 1
+ mock_record_event_args = mock_record_halt.call_args_list[0][0]
+ assert mock_record_event_args[0] is not None
+
+ metric_exception = mock_record_event_args[0]
+ assert isinstance(metric_exception, IntegrationError)
|
1037f0b49a512ac898865ff61b8c15d8d3696d3f
|
2021-05-27 07:10:06
|
Evan Purkhiser
|
ref(search): More clarity cleanup in grammar (#26250)
| false
|
More clarity cleanup in grammar (#26250)
|
ref
|
diff --git a/src/sentry/api/event_search.py b/src/sentry/api/event_search.py
index 5dca33f9054cb3..802d846ba09b3d 100644
--- a/src/sentry/api/event_search.py
+++ b/src/sentry/api/event_search.py
@@ -37,85 +37,93 @@
event_search_grammar = Grammar(
r"""
-search = (boolean_operator / paren_term / search_term)*
+search = spaces term*
-boolean_operator = spaces (or_operator / and_operator) spaces
-paren_term = spaces open_paren spaces (paren_term / boolean_operator / search_term)+ spaces closed_paren spaces
-search_term = key_val_term / free_text_quoted / free_text
+term = (boolean_operator / paren_group / filter / free_text) spaces
-free_text = (spaces !key_val_term !or_operator !and_operator (free_parens / ~r"[^()\n ]+") spaces)+
-free_parens = spaces open_paren spaces free_text? spaces closed_paren spaces
-free_text_quoted = spaces quoted_value spaces
+boolean_operator = or_operator / and_operator
-# All key:value filter types
-key_val_term = spaces key_val_filter spaces
-key_val_filter = time_filter
- / rel_time_filter
- / specific_time_filter
- / duration_filter
- / boolean_filter
- / numeric_in_filter
- / numeric_filter
- / aggregate_filter
- / aggregate_date_filter
- / aggregate_rel_date_filter
- / has_filter
- / is_filter
- / text_in_filter
- / text_filter
+paren_group = open_paren spaces term+ closed_paren
-# standard key:val filter
-text_filter = negation? text_key sep search_value
+free_text = free_text_quoted / free_text_unquoted
+free_text_unquoted = (!filter !boolean_operator (free_parens / ~r"[^()\n ]+") spaces)+
+free_text_quoted = quoted_value
+free_parens = open_paren free_text? closed_paren
-# in filter key:[val1, val2]
-text_in_filter = negation? text_key sep text_in_list
+# All key:value filter types
+filter = date_filter
+ / specific_date_filter
+ / rel_date_filter
+ / duration_filter
+ / boolean_filter
+ / numeric_in_filter
+ / numeric_filter
+ / aggregate_filter
+ / aggregate_date_filter
+ / aggregate_rel_date_filter
+ / has_filter
+ / is_filter
+ / text_in_filter
+ / text_filter
# filter for dates
-time_filter = search_key sep operator iso_8601_date_format
+date_filter = search_key sep operator iso_8601_date_format
+
+# exact date filter for dates
+specific_date_filter = search_key sep iso_8601_date_format
# filter for relative dates
-rel_time_filter = search_key sep rel_date_format
+rel_date_filter = search_key sep rel_date_format
# filter for durations
duration_filter = search_key sep operator? duration_format
-# exact time filter for dates
-specific_time_filter = search_key sep iso_8601_date_format
-
-# numeric comparison filter
-numeric_filter = search_key sep operator? numeric_value
+# boolean comparison filter
+boolean_filter = negation? search_key sep boolean_value
# numeric in filter
numeric_in_filter = search_key sep numeric_in_list
-# boolean comparison filter
-boolean_filter = negation? search_key sep boolean_value
+# numeric comparison filter
+numeric_filter = search_key sep operator? numeric_value
# aggregate numeric filter
-aggregate_filter = negation? aggregate_key sep operator? (duration_format / numeric_value / percentage_format)
-aggregate_date_filter = negation? aggregate_key sep operator? iso_8601_date_format
+aggregate_filter = negation? aggregate_key sep operator? (duration_format / numeric_value / percentage_format)
+
+# aggregate for dates
+aggregate_date_filter = negation? aggregate_key sep operator? iso_8601_date_format
+
+# aggregate for relative dates
aggregate_rel_date_filter = negation? aggregate_key sep operator? rel_date_format
# has filter for not null type checks
has_filter = negation? "has" sep (search_key / search_value)
+
+# is filter. Specific to issue search
is_filter = negation? "is" sep search_value
+# in filter key:[val1, val2]
+text_in_filter = negation? text_key sep text_in_list
+
+# standard key:val filter
+text_filter = negation? text_key sep search_value
+
+key = ~r"[a-zA-Z0-9_\.-]+"
+quoted_key = ~r"\"([a-zA-Z0-9_\.:-]+)\""
+explicit_tag_key = "tags" open_bracket search_key closed_bracket
aggregate_key = key open_paren spaces function_args? spaces closed_paren
+function_args = key (spaces comma spaces key)*
search_key = key / quoted_key
-search_value = quoted_value / value
+text_key = explicit_tag_key / search_key
value = ~r"[^()\s]*"
+quoted_value = ~r"\"((?:\\\"|[^\"])*)?\""s
in_value = ~r"[^(),\s]*(?:[^\],\s)]|](?=]))"
+text_value = quoted_value / in_value
+search_value = quoted_value / value
numeric_value = ~r"([-]?[0-9\.]+)([kmb])?(?=\s|\)|$|,|])"
boolean_value = ~r"(true|1|false|0)(?=\s|\)|$)"i
-key = ~r"[a-zA-Z0-9_\.-]+"
-function_args = key (spaces comma spaces key)*
-quoted_key = ~r"\"([a-zA-Z0-9_\.:-]+)\""
-explicit_tag_key = "tags" open_bracket search_key closed_bracket
-text_key = explicit_tag_key / search_key
-text_value = quoted_value / in_value
-quoted_value = ~r"\"((?:\\\"|[^\"])*)?\""s
-numeric_in_list = open_bracket numeric_value (spaces comma spaces numeric_value)* closed_bracket
text_in_list = open_bracket text_value (spaces comma spaces text_value)* closed_bracket
+numeric_in_list = open_bracket numeric_value (spaces comma spaces numeric_value)* closed_bracket
# Formats
iso_8601_date_format = ~r"(\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d{1,6})?)?(Z|([+-]\d{2}:\d{2}))?)(?=\s|\)|$)"
@@ -356,29 +364,32 @@ def is_percentage_key(self, key):
return key in self.percentage_keys
def visit_search(self, node, children):
- return self.flatten(children)
+ return self.flatten(self.remove_space(children[1]))
- def visit_key_val_term(self, node, children):
- _, key_val_term, _ = children
- # key_val_term is a list because of group
- return key_val_term[0]
+ def visit_term(self, node, children):
+ return self.flatten(self.remove_space(children[0]))
- def visit_free_text(self, node, children):
- value = node.text.strip(" ")
- if not value:
- return None
+ def visit_boolean_operator(self, node, children):
+ if not self.allow_boolean:
+ raise InvalidSearchQuery(
+ 'Boolean statements containing "OR" or "AND" are not supported in this search'
+ )
+
+ children = self.flatten(self.remove_space(children))
+ return children[0].text.upper()
- return SearchFilter(SearchKey("message"), "=", SearchValue(value))
+ def visit_free_text_unquoted(self, node, children):
+ return node.text.strip(" ") or None
- def visit_free_text_quoted(self, node, children):
- value = children[1]
- if not value:
+ def visit_free_text(self, node, children):
+ if not children[0]:
return None
- return SearchFilter(SearchKey("message"), "=", SearchValue(value))
+ return SearchFilter(SearchKey("message"), "=", SearchValue(children[0]))
- def visit_paren_term(self, node, children):
+ def visit_paren_group(self, node, children):
if not self.allow_boolean:
- # It's possible to have a valid search that includes parens, so we can't just error out when we find a paren expression.
+ # It's possible to have a valid search that includes parens, so we
+ # can't just error out when we find a paren expression.
return self.visit_free_text(node, children)
children = self.remove_space(self.remove_optional_nodes(self.flatten(children)))
@@ -535,7 +546,7 @@ def visit_aggregate_rel_date_filter(self, node, children):
search_value = operator + search_value.text if operator != "=" else search_value
return AggregateFilter(search_key, "=", SearchValue(search_value))
- def visit_time_filter(self, node, children):
+ def visit_date_filter(self, node, children):
(search_key, _, operator, search_value) = children
if search_key.name in self.date_keys:
@@ -564,7 +575,7 @@ def visit_duration_filter(self, node, children):
search_value = operator + search_value.text if operator != "=" else search_value.text
return self._handle_basic_filter(search_key, "=", SearchValue(search_value))
- def visit_rel_time_filter(self, node, children):
+ def visit_rel_date_filter(self, node, children):
(search_key, _, value) = children
if search_key.name in self.date_keys:
@@ -584,7 +595,7 @@ def visit_rel_time_filter(self, node, children):
else:
return self._handle_basic_filter(search_key, "=", SearchValue(value.text))
- def visit_specific_time_filter(self, node, children):
+ def visit_specific_date_filter(self, node, children):
# If we specify a specific date, it means any event on that day, and if
# we specify a specific datetime then it means a few minutes interval
# on either side of that datetime
@@ -706,15 +717,6 @@ def visit_closed_paren(self, node, children):
def visit_open_paren(self, node, children):
return node.text
- def visit_boolean_operator(self, node, children):
- if not self.allow_boolean:
- raise InvalidSearchQuery(
- 'Boolean statements containing "OR" or "AND" are not supported in this search'
- )
-
- children = self.flatten(self.remove_space(children))
- return children[0].text.upper()
-
def visit_value(self, node, children):
# A properly quoted value will match the quoted value regex, so any unescaped
# quotes are errors.
diff --git a/tests/sentry/api/test_event_search.py b/tests/sentry/api/test_event_search.py
index c7f2529bc7a7bd..3dce466a9ba47f 100644
--- a/tests/sentry/api/test_event_search.py
+++ b/tests/sentry/api/test_event_search.py
@@ -174,7 +174,7 @@ def test_simple_in(self):
),
]
- def test_raw_search_anywhere(self):
+ def test_free_text_search_anywhere(self):
assert parse_search_query(
"hello what user.email:[email protected] where release:1.2.1 when"
) == [
@@ -228,7 +228,7 @@ def test_raw_search_anywhere(self):
),
]
- def test_quoted_raw_search_anywhere(self):
+ def test_quoted_free_text_search_anywhere(self):
assert parse_search_query('"hello there" user.email:[email protected] "general kenobi"') == [
SearchFilter(
key=SearchKey(name="message"),
|
41a2e0a3dd8048c41d551d7301709ea0600d1c59
|
2024-05-28 20:53:30
|
Evan Purkhiser
|
ref(ui): Specialize accordion to replays (#71400)
| false
|
Specialize accordion to replays (#71400)
|
ref
|
diff --git a/static/app/components/accordion/accordion.stories.tsx b/static/app/components/accordion/accordion.stories.tsx
deleted file mode 100644
index 2c92480488b39b..00000000000000
--- a/static/app/components/accordion/accordion.stories.tsx
+++ /dev/null
@@ -1,99 +0,0 @@
-import {Fragment, useState} from 'react';
-
-import Accordion from 'sentry/components/accordion/accordion';
-import JSXNode from 'sentry/components/stories/jsxNode';
-import JSXProperty from 'sentry/components/stories/jsxProperty';
-import SideBySide from 'sentry/components/stories/sideBySide';
-import SizingWindow from 'sentry/components/stories/sizingWindow';
-import storyBook from 'sentry/stories/storyBook';
-
-const ACCORDION_ITEMS = [
- {header: 'Header 1', content: 'Content 1'},
- {header: 'Header 2', content: 'Content 2'},
- {header: 'Header 3', content: 'Content 3'},
-];
-
-export default storyBook(Accordion, story => {
- story('Default', () => {
- const [expanded, setExpanded] = useState(0);
- return (
- <Fragment>
- <p>
- The <JSXNode name="Accordion" /> component is
- <JSXProperty name="collapsible" value /> and has the chevron button on the right
- by default.
- </p>
- <SizingWindow display="block">
- <Accordion
- items={ACCORDION_ITEMS}
- expandedIndex={expanded}
- setExpandedIndex={setExpanded}
- />
- </SizingWindow>
- <p>Besides the accordion headers and content, required props to pass in are</p>
- <ul>
- <li>
- <JSXProperty name="expandedIndex" value={Number} /> to set the default
- expanded panel (the top panel is indexed <code>0</code>). To set all panels as
- collapsed, you can set
- <JSXProperty name="expandedIndex" value={-1} />.
- </li>
- <li>
- <JSXProperty name="setExpandedIndex" value={Function} /> - a callback which
- details the behavior when setting a new expanded panel.
- </li>
- </ul>
- </Fragment>
- );
- });
-
- story('Props', () => {
- const [expanded, setExpanded] = useState(0);
- const [collapsibleExpanded, setCollapsibleExpanded] = useState(0);
- const [leftExpanded, setLeftExpanded] = useState(0);
- const [rightExpanded, setRightExpanded] = useState(0);
- return (
- <Fragment>
- <p>
- <JSXProperty name="items" value={Array} /> specifies the accordion content. Each
- array item should specify a <code>ReactNode</code> for the header and content.
- </p>
- <SideBySide>
- {[true, false].map(collapsible => (
- <div key={'collapsible_' + collapsible}>
- <p>
- <JSXProperty name="collapsible" value={collapsible} />
- </p>
- <SizingWindow display="block">
- <Accordion
- items={ACCORDION_ITEMS}
- expandedIndex={collapsible ? collapsibleExpanded : expanded}
- setExpandedIndex={collapsible ? setCollapsibleExpanded : setExpanded}
- collapsible={collapsible}
- />
- </SizingWindow>
- </div>
- ))}
- </SideBySide>
- <br />
- <SideBySide>
- {[true, false].map(buttoOnLeft => (
- <div key={'left_' + buttoOnLeft}>
- <p>
- <JSXProperty name="buttoOnLeft" value={buttoOnLeft} />
- </p>
- <SizingWindow display="block">
- <Accordion
- items={ACCORDION_ITEMS}
- expandedIndex={buttoOnLeft ? leftExpanded : rightExpanded}
- setExpandedIndex={buttoOnLeft ? setLeftExpanded : setRightExpanded}
- buttonOnLeft={buttoOnLeft}
- />
- </SizingWindow>
- </div>
- ))}
- </SideBySide>
- </Fragment>
- );
- });
-});
diff --git a/static/app/components/accordion/accordion.tsx b/static/app/components/accordion/accordion.tsx
deleted file mode 100644
index 5027e4eff3ace7..00000000000000
--- a/static/app/components/accordion/accordion.tsx
+++ /dev/null
@@ -1,146 +0,0 @@
-import type {ReactNode} from 'react';
-import styled from '@emotion/styled';
-
-import {Button} from 'sentry/components/button';
-import {IconChevron} from 'sentry/icons';
-import {t} from 'sentry/locale';
-import {space} from 'sentry/styles/space';
-
-interface AccordionItemContent {
- content: ReactNode;
- header: ReactNode;
-}
-
-interface Props {
- expandedIndex: number;
- items: AccordionItemContent[];
- setExpandedIndex: (index: number) => void;
- buttonOnLeft?: boolean;
- collapsible?: boolean;
-}
-
-export default function Accordion({
- expandedIndex,
- setExpandedIndex,
- items,
- buttonOnLeft,
- collapsible = true,
-}: Props) {
- return (
- <AccordionContainer>
- {items.map((item, index) => (
- <AccordionItem
- isExpanded={index === expandedIndex}
- currentIndex={index}
- key={index}
- content={item.content}
- setExpandedIndex={setExpandedIndex}
- buttonOnLeft={buttonOnLeft}
- collapsible={collapsible}
- >
- {item.header}
- </AccordionItem>
- ))}
- </AccordionContainer>
- );
-}
-
-function AccordionItem({
- isExpanded,
- currentIndex: index,
- children,
- setExpandedIndex,
- content,
- buttonOnLeft,
- collapsible,
-}: {
- children: ReactNode;
- content: ReactNode;
- currentIndex: number;
- isExpanded: boolean;
- setExpandedIndex: (index: number) => void;
- buttonOnLeft?: boolean;
- collapsible?: boolean;
-}) {
- const button = collapsible ? (
- <Button
- icon={<IconChevron size="xs" direction={isExpanded ? 'up' : 'down'} />}
- aria-label={isExpanded ? t('Collapse') : t('Expand')}
- aria-expanded={isExpanded}
- size="zero"
- borderless
- onClick={() => setExpandedIndex(isExpanded ? -1 : index)}
- />
- ) : (
- <Button
- icon={<IconChevron size="xs" direction={isExpanded ? 'up' : 'down'} />}
- aria-label={t('Expand')}
- aria-expanded={isExpanded}
- disabled={isExpanded}
- size="zero"
- borderless
- onClick={() => setExpandedIndex(index)}
- />
- );
-
- return buttonOnLeft ? (
- <StyledLineItem>
- <ButtonLeftListItemContainer>
- {button}
- <StyledPanel
- onClick={() => setExpandedIndex(isExpanded && collapsible ? -1 : index)}
- >
- {children}
- </StyledPanel>
- </ButtonLeftListItemContainer>
- <LeftContentContainer>{isExpanded && content}</LeftContentContainer>
- </StyledLineItem>
- ) : (
- <StyledLineItem>
- <ListItemContainer>
- {children}
- {button}
- </ListItemContainer>
- <StyledContentContainer>{isExpanded && content}</StyledContentContainer>
- </StyledLineItem>
- );
-}
-
-const StyledLineItem = styled('li')`
- line-height: ${p => p.theme.text.lineHeightBody};
-`;
-
-const AccordionContainer = styled('ul')`
- padding: ${space(1)} 0 0 0;
- margin: 0;
- list-style-type: none;
-`;
-
-const ButtonLeftListItemContainer = styled('div')`
- display: flex;
- border-top: 1px solid ${p => p.theme.border};
- padding: ${space(1)} ${space(2)};
- font-size: ${p => p.theme.fontSizeMedium};
- column-gap: ${space(1.5)};
-`;
-
-const ListItemContainer = styled('div')`
- display: flex;
- border-top: 1px solid ${p => p.theme.border};
- padding: ${space(1)} ${space(2)};
- font-size: ${p => p.theme.fontSizeMedium};
-`;
-
-const StyledContentContainer = styled('div')`
- padding: ${space(0)} ${space(2)};
-`;
-
-const LeftContentContainer = styled('div')`
- padding: ${space(0)} ${space(0.25)};
-`;
-
-const StyledPanel = styled('div')`
- display: grid;
- grid-template-columns: 1fr max-content;
- flex: 1;
-`;
diff --git a/static/app/components/accordion/accordion.spec.tsx b/static/app/components/replays/accordion.spec.tsx
similarity index 82%
rename from static/app/components/accordion/accordion.spec.tsx
rename to static/app/components/replays/accordion.spec.tsx
index 944cb639774f54..da3e41837dfaa6 100644
--- a/static/app/components/accordion/accordion.spec.tsx
+++ b/static/app/components/replays/accordion.spec.tsx
@@ -1,6 +1,6 @@
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
-import Accordion from 'sentry/components/accordion/accordion';
+import Accordion from './accordion';
const items = [
{header: <p>header</p>, content: <p>first content</p>},
@@ -10,6 +10,7 @@ const items = [
describe('Accordion', function () {
it('renders expanded item', async function () {
render(<Accordion expandedIndex={0} setExpandedIndex={() => {}} items={items} />);
+
expect(await screen.findByText('first content')).toBeInTheDocument();
expect(screen.queryByText('second content')).not.toBeInTheDocument();
});
@@ -17,11 +18,8 @@ describe('Accordion', function () {
it('invokes callback on header click', async function () {
const spy = jest.fn();
render(<Accordion expandedIndex={0} setExpandedIndex={spy} items={items} />);
- await userEvent.click(
- screen.getByRole('button', {
- expanded: false,
- })
- );
+
+ await userEvent.click(screen.getByRole('button', {expanded: false}));
expect(spy).toHaveBeenCalled();
});
});
diff --git a/static/app/components/replays/accordion.tsx b/static/app/components/replays/accordion.tsx
new file mode 100644
index 00000000000000..e6c1812309bebd
--- /dev/null
+++ b/static/app/components/replays/accordion.tsx
@@ -0,0 +1,82 @@
+import styled from '@emotion/styled';
+
+import {Button} from 'sentry/components/button';
+import {IconChevron} from 'sentry/icons';
+import {t} from 'sentry/locale';
+import {space} from 'sentry/styles/space';
+
+interface AccordionItemContent {
+ content: React.ReactNode;
+ header: React.ReactNode;
+}
+
+interface Props {
+ expandedIndex: number;
+ items: AccordionItemContent[];
+ setExpandedIndex: (index: number) => void;
+ collapsible?: boolean;
+}
+
+export default function Accordion({
+ expandedIndex,
+ setExpandedIndex,
+ items,
+ collapsible = true,
+}: Props) {
+ return (
+ <AccordionContainer>
+ {items.map((item, index) => {
+ const isExpanded = index === expandedIndex;
+
+ return (
+ <AccordionItem key={index}>
+ <ItemContainer>
+ <Button
+ icon={<IconChevron size="xs" direction={isExpanded ? 'up' : 'down'} />}
+ aria-label={collapsible && isExpanded ? t('Collapse') : t('Expand')}
+ aria-expanded={isExpanded}
+ size="zero"
+ borderless
+ onClick={() => setExpandedIndex(collapsible && isExpanded ? -1 : index)}
+ />
+ <LineItemWrapper
+ onClick={() => setExpandedIndex(isExpanded && collapsible ? -1 : index)}
+ >
+ {item.header}
+ </LineItemWrapper>
+ </ItemContainer>
+ <ContentContainer>{isExpanded && item.content}</ContentContainer>
+ </AccordionItem>
+ );
+ })}
+ </AccordionContainer>
+ );
+}
+
+const AccordionItem = styled('li')`
+ line-height: ${p => p.theme.text.lineHeightBody};
+`;
+
+const AccordionContainer = styled('ul')`
+ padding: ${space(1)} 0 0 0;
+ margin: 0;
+ list-style-type: none;
+`;
+
+const ItemContainer = styled('div')`
+ display: flex;
+ border-top: 1px solid ${p => p.theme.border};
+ padding: ${space(1)} ${space(2)};
+ font-size: ${p => p.theme.fontSizeMedium};
+ column-gap: ${space(1.5)};
+`;
+
+const ContentContainer = styled('div')`
+ padding: ${space(0)} ${space(0.25)};
+`;
+
+const LineItemWrapper = styled('div')`
+ display: grid;
+ grid-template-columns: 1fr max-content;
+ flex: 1;
+`;
diff --git a/static/app/components/sidebar/sidebarAccordion.tsx b/static/app/components/sidebar/sidebarAccordion.tsx
index da8ca13eef54ba..0766ae4728648f 100644
--- a/static/app/components/sidebar/sidebarAccordion.tsx
+++ b/static/app/components/sidebar/sidebarAccordion.tsx
@@ -2,8 +2,6 @@ import {
Children,
cloneElement,
isValidElement,
- type ReactElement,
- type ReactNode,
useCallback,
useContext,
useRef,
@@ -166,7 +164,7 @@ function SidebarAccordion({children, ...itemProps}: SidebarAccordionProps) {
export {SidebarAccordion};
-const renderChildrenWithProps = (children: ReactNode): ReactNode => {
+const renderChildrenWithProps = (children: React.ReactNode): React.ReactNode => {
const propsToAdd: Partial<SidebarItemProps> = {
isNested: true,
};
@@ -175,9 +173,11 @@ const renderChildrenWithProps = (children: ReactNode): ReactNode => {
if (!isValidElement(child)) {
return child;
}
- return cloneElement(child as ReactElement<any>, {
+ return cloneElement(child as React.ReactElement<any>, {
...propsToAdd,
- children: renderChildrenWithProps((child as ReactElement<any>).props.children),
+ children: renderChildrenWithProps(
+ (child as React.ReactElement<any>).props.children
+ ),
});
});
};
diff --git a/static/app/views/replays/deadRageClick/deadRageSelectorCards.tsx b/static/app/views/replays/deadRageClick/deadRageSelectorCards.tsx
index d55f3ab0660d59..59d2f98f17acd4 100644
--- a/static/app/views/replays/deadRageClick/deadRageSelectorCards.tsx
+++ b/static/app/views/replays/deadRageClick/deadRageSelectorCards.tsx
@@ -2,12 +2,12 @@ import type {ComponentProps, ReactNode} from 'react';
import {useState} from 'react';
import styled from '@emotion/styled';
-import Accordion from 'sentry/components/accordion/accordion';
import {LinkButton} from 'sentry/components/button';
import EmptyStateWarning from 'sentry/components/emptyStateWarning';
import Placeholder from 'sentry/components/placeholder';
import {Flex} from 'sentry/components/profiling/flex';
import QuestionTooltip from 'sentry/components/questionTooltip';
+import Accordion from 'sentry/components/replays/accordion';
import TextOverflow from 'sentry/components/textOverflow';
import {IconCursorArrow, IconSearch} from 'sentry/icons';
import {t, tct} from 'sentry/locale';
@@ -133,7 +133,6 @@ function AccordionWidget({
) : (
<LeftAlignedContentContainer>
<Accordion
- buttonOnLeft
collapsible
expandedIndex={selectedListIndex}
setExpandedIndex={setSelectListIndex}
diff --git a/static/app/views/replays/list/replayOnboardingPanel.tsx b/static/app/views/replays/list/replayOnboardingPanel.tsx
index 820b037df416fa..7df9de6547ac8e 100644
--- a/static/app/views/replays/list/replayOnboardingPanel.tsx
+++ b/static/app/views/replays/list/replayOnboardingPanel.tsx
@@ -3,13 +3,13 @@ import styled from '@emotion/styled';
import emptyStateImg from 'sentry-images/spot/replays-empty-state.svg';
-import Accordion from 'sentry/components/accordion/accordion';
import {Button} from 'sentry/components/button';
import ButtonBar from 'sentry/components/buttonBar';
import HookOrDefault from 'sentry/components/hookOrDefault';
import ExternalLink from 'sentry/components/links/externalLink';
import {useProjectCreationAccess} from 'sentry/components/projects/useProjectCreationAccess';
import QuestionTooltip from 'sentry/components/questionTooltip';
+import Accordion from 'sentry/components/replays/accordion';
import ReplayUnsupportedAlert from 'sentry/components/replays/alerts/replayUnsupportedAlert';
import {Tooltip} from 'sentry/components/tooltip';
import {mobile, replayPlatforms} from 'sentry/data/platformCategories';
@@ -284,12 +284,7 @@ export function SetupReplaysCTA({
})}
/>
</StyledHeaderContainer>
- <Accordion
- items={FAQ}
- expandedIndex={expanded}
- setExpandedIndex={setExpanded}
- buttonOnLeft
- />
+ <Accordion items={FAQ} expandedIndex={expanded} setExpandedIndex={setExpanded} />
</StyledWidgetContainer>
</CenteredContent>
);
|
86a07c0cbb8d7ad88b6df0984d9a6e232ca5073a
|
2024-02-06 02:41:23
|
Ash
|
ref(plugins): Remove old component annotation plugin (#64597)
| false
|
Remove old component annotation plugin (#64597)
|
ref
|
diff --git a/babel.config.ts b/babel.config.ts
index 0266dfcf4131cc..f7cebd18e6a222 100644
--- a/babel.config.ts
+++ b/babel.config.ts
@@ -44,14 +44,12 @@ const config: TransformOptions = {
},
],
['babel-plugin-add-react-displayname'],
- ['@fullstory/babel-plugin-annotate-react'],
],
},
development: {
plugins: [
'@emotion/babel-plugin',
'@babel/plugin-transform-react-jsx-source',
- ['@fullstory/babel-plugin-annotate-react'],
...(process.env.SENTRY_UI_HOT_RELOAD ? ['react-refresh/babel'] : []),
],
},
|
b299c9691a92b0213a870ee54996b9110a4072a5
|
2023-08-07 23:05:08
|
Julia Hoge
|
build(most-helpful-event): Add backend key for popup guide (#54295)
| false
|
Add backend key for popup guide (#54295)
|
build
|
diff --git a/src/sentry/assistant/guides.py b/src/sentry/assistant/guides.py
index eb9c5649019ba8..1d3b82835f01a2 100644
--- a/src/sentry/assistant/guides.py
+++ b/src/sentry/assistant/guides.py
@@ -27,6 +27,7 @@
"create_conditional_rule": 28,
"explain_archive_button_issue_details": 29,
"explain_archive_tab_issue_stream": 30,
+ "explain_new_default_event_issue_detail": 31,
}
# demo mode has different guides
|
e06b87c48a76cdd560ed9431892a7e1989d93c87
|
2024-03-08 22:23:14
|
George Gritsouk
|
ref(perf): Remove boolean filter value condition from data hooks (#66435)
| false
|
Remove boolean filter value condition from data hooks (#66435)
|
ref
|
diff --git a/static/app/views/performance/browser/resources/resourceSummaryPage/resourceSummaryCharts.tsx b/static/app/views/performance/browser/resources/resourceSummaryPage/resourceSummaryCharts.tsx
index c225a132ac6a45..25ae1d76b4df94 100644
--- a/static/app/views/performance/browser/resources/resourceSummaryPage/resourceSummaryCharts.tsx
+++ b/static/app/views/performance/browser/resources/resourceSummaryPage/resourceSummaryCharts.tsx
@@ -48,6 +48,7 @@ function ResourceSummaryCharts(props: {groupId: string}) {
`avg(${HTTP_DECODED_RESPONSE_CONTENT_LENGTH})`,
`avg(${HTTP_RESPONSE_TRANSFER_SIZE})`,
],
+ enabled: Boolean(props.groupId),
});
if (spanMetricsSeriesData) {
diff --git a/static/app/views/performance/database/databaseLandingPage.tsx b/static/app/views/performance/database/databaseLandingPage.tsx
index faa1de4bcea488..fce703aab64425 100644
--- a/static/app/views/performance/database/databaseLandingPage.tsx
+++ b/static/app/views/performance/database/databaseLandingPage.tsx
@@ -1,7 +1,6 @@
import React, {Fragment} from 'react';
import {browserHistory} from 'react-router';
import styled from '@emotion/styled';
-import pickBy from 'lodash/pickBy';
import Alert from 'sentry/components/alert';
import {Breadcrumbs} from 'sentry/components/breadcrumbs';
@@ -81,7 +80,7 @@ export function DatabaseLandingPage() {
const cursor = decodeScalar(location.query?.[QueryParameterNames.SPANS_CURSOR]);
const queryListResponse = useSpanMetrics({
- filters: pickBy(tableFilters, value => value !== undefined),
+ filters: tableFilters,
fields: [
'project.id',
'span.group',
diff --git a/static/app/views/performance/database/databaseSpanSummaryPage.tsx b/static/app/views/performance/database/databaseSpanSummaryPage.tsx
index 9081c09db57f28..1530b94d840f9b 100644
--- a/static/app/views/performance/database/databaseSpanSummaryPage.tsx
+++ b/static/app/views/performance/database/databaseSpanSummaryPage.tsx
@@ -61,6 +61,9 @@ function SpanSummaryPage({params}: Props) {
if (endpoint) {
filters.transaction = endpoint;
+ }
+
+ if (endpointMethod) {
filters['transaction.method'] = endpointMethod;
}
@@ -80,6 +83,7 @@ function SpanSummaryPage({params}: Props) {
`${SpanFunction.TIME_SPENT_PERCENTAGE}()`,
`${SpanFunction.HTTP_ERROR_COUNT}()`,
],
+ enabled: Boolean(groupId),
referrer: 'api.starfish.span-summary-page-metrics',
});
@@ -103,6 +107,7 @@ function SpanSummaryPage({params}: Props) {
} = useSpanMetricsSeries({
filters,
yAxis: ['spm()'],
+ enabled: Boolean(groupId),
referrer: 'api.starfish.span-summary-page-metrics-chart',
});
@@ -113,6 +118,7 @@ function SpanSummaryPage({params}: Props) {
} = useSpanMetricsSeries({
filters,
yAxis: [`${selectedAggregate}(${SpanMetricsField.SPAN_SELF_TIME})`],
+ enabled: Boolean(groupId),
referrer: 'api.starfish.span-summary-page-metrics-chart',
});
diff --git a/static/app/views/performance/http/httpDomainSummaryPage.tsx b/static/app/views/performance/http/httpDomainSummaryPage.tsx
index 494754919700d2..23c0e8364448c0 100644
--- a/static/app/views/performance/http/httpDomainSummaryPage.tsx
+++ b/static/app/views/performance/http/httpDomainSummaryPage.tsx
@@ -53,6 +53,7 @@ export function HTTPDomainSummaryPage() {
`sum(${SpanMetricsField.SPAN_SELF_TIME})`,
`${SpanFunction.TIME_SPENT_PERCENTAGE}()`,
],
+ enabled: Boolean(domain),
referrer: 'api.starfish.http-module-domain-summary-metrics-ribbon',
});
@@ -63,6 +64,7 @@ export function HTTPDomainSummaryPage() {
} = useSpanMetricsSeries({
filters,
yAxis: ['spm()'],
+ enabled: Boolean(domain),
referrer: 'api.starfish.http-module-domain-summary-throughput-chart',
});
@@ -73,6 +75,7 @@ export function HTTPDomainSummaryPage() {
} = useSpanMetricsSeries({
filters,
yAxis: [`${selectedAggregate}(${SpanMetricsField.SPAN_SELF_TIME})`],
+ enabled: Boolean(domain),
referrer: 'api.starfish.http-module-domain-summary-duration-chart',
});
diff --git a/static/app/views/performance/http/httpLandingPage.tsx b/static/app/views/performance/http/httpLandingPage.tsx
index 31797561ce3645..b4f30a8582898b 100644
--- a/static/app/views/performance/http/httpLandingPage.tsx
+++ b/static/app/views/performance/http/httpLandingPage.tsx
@@ -1,5 +1,4 @@
import React, {Fragment} from 'react';
-import pickBy from 'lodash/pickBy';
import {Breadcrumbs} from 'sentry/components/breadcrumbs';
import FloatingFeedbackWidget from 'sentry/components/feedback/widget/floatingFeedbackWidget';
@@ -69,7 +68,7 @@ export function HTTPLandingPage() {
});
const domainsListResponse = useSpanMetrics({
- filters: pickBy(tableFilters, value => value !== undefined),
+ filters: tableFilters,
fields: [
'project.id',
'span.domain',
diff --git a/static/app/views/starfish/queries/useSpanMetrics.spec.tsx b/static/app/views/starfish/queries/useSpanMetrics.spec.tsx
index b5ab20be6b52c7..e829275d90396f 100644
--- a/static/app/views/starfish/queries/useSpanMetrics.spec.tsx
+++ b/static/app/views/starfish/queries/useSpanMetrics.spec.tsx
@@ -97,6 +97,7 @@ describe('useSpanMetrics', () => {
'span.group': '221aa7ebd216',
transaction: '/api/details',
release: '0.0.1',
+ environment: undefined,
},
fields: ['spm()'] as MetricsProperty[],
sorts: [{field: 'spm()', kind: 'desc' as const}],
diff --git a/static/app/views/starfish/queries/useSpanMetrics.tsx b/static/app/views/starfish/queries/useSpanMetrics.tsx
index e8d8ce9e734382..810c4d6e7896ad 100644
--- a/static/app/views/starfish/queries/useSpanMetrics.tsx
+++ b/static/app/views/starfish/queries/useSpanMetrics.tsx
@@ -30,15 +30,11 @@ export const useSpanMetrics = <Fields extends MetricsProperty[]>(
const eventView = getEventView(filters, fields, sorts, pageFilters.selection);
- // TODO: Checking that every filter has a value might not be a good choice, since this API is not convenient. Instead, it's probably fine to omit keys with blank values
- const enabled =
- options.enabled && Object.values(filters).every(value => Boolean(value));
-
const result = useWrappedDiscoverQuery({
eventView,
initialData: [],
limit,
- enabled,
+ enabled: options.enabled,
referrer,
cursor,
});
@@ -50,7 +46,7 @@ export const useSpanMetrics = <Fields extends MetricsProperty[]>(
return {
...result,
data,
- isEnabled: enabled,
+ isEnabled: options.enabled,
};
};
diff --git a/static/app/views/starfish/queries/useSpanMetricsSeries.spec.tsx b/static/app/views/starfish/queries/useSpanMetricsSeries.spec.tsx
index 427a5579e2cde1..0da3ca5559026c 100644
--- a/static/app/views/starfish/queries/useSpanMetricsSeries.spec.tsx
+++ b/static/app/views/starfish/queries/useSpanMetricsSeries.spec.tsx
@@ -105,6 +105,7 @@ describe('useSpanMetricsSeries', () => {
transaction: '/api/details',
release: '0.0.1',
'resource.render_blocking_status': 'blocking' as const,
+ environment: undefined,
},
yAxis: ['spm()'] as MetricsProperty[],
},
diff --git a/static/app/views/starfish/queries/useSpanMetricsSeries.tsx b/static/app/views/starfish/queries/useSpanMetricsSeries.tsx
index 94ce872ff2444b..ce00de57930fc4 100644
--- a/static/app/views/starfish/queries/useSpanMetricsSeries.tsx
+++ b/static/app/views/starfish/queries/useSpanMetricsSeries.tsx
@@ -35,15 +35,11 @@ export const useSpanMetricsSeries = <Fields extends MetricsProperty[]>(
const eventView = getEventView(filters, pageFilters.selection, yAxis);
- // TODO: Checking that every filter has a value might not be a good choice, since this API is not convenient. Instead, it's probably fine to omit keys with blank values
- const enabled =
- options.enabled && Object.values(filters).every(value => Boolean(value));
-
const result = useWrappedDiscoverTimeseriesQuery<SpanMetricTimeseriesRow[]>({
eventView,
initialData: [],
referrer,
- enabled,
+ enabled: options.enabled,
});
const parsedData = keyBy(
diff --git a/static/app/views/starfish/queries/useSpanSamples.tsx b/static/app/views/starfish/queries/useSpanSamples.tsx
index 0a30e90251ace1..305dcb41b9f36d 100644
--- a/static/app/views/starfish/queries/useSpanSamples.tsx
+++ b/static/app/views/starfish/queries/useSpanSamples.tsx
@@ -79,6 +79,9 @@ export const useSpanSamples = (options: Options) => {
const {isLoading: isLoadingSeries, data: spanMetricsSeriesData} = useSpanMetricsSeries({
filters: {'span.group': groupId, ...filters},
yAxis: [`avg(${SPAN_SELF_TIME})`],
+ enabled: Object.values({'span.group': groupId, ...filters}).every(value =>
+ Boolean(value)
+ ),
referrer: 'api.starfish.sidebar-span-metrics',
});
diff --git a/static/app/views/starfish/views/screens/screenLoadSpans/samples/samplesContainer.tsx b/static/app/views/starfish/views/screens/screenLoadSpans/samples/samplesContainer.tsx
index 2ee2e11ef7e49f..e81ad157f0836a 100644
--- a/static/app/views/starfish/views/screens/screenLoadSpans/samples/samplesContainer.tsx
+++ b/static/app/views/starfish/views/screens/screenLoadSpans/samples/samplesContainer.tsx
@@ -101,6 +101,7 @@ export function ScreenLoadSampleContainer({
const {data} = useSpanMetrics({
filters: {...filters, ...additionalFilters},
fields: [`avg(${SPAN_SELF_TIME})`, 'count()', SPAN_OP],
+ enabled: Boolean(groupId) && Boolean(transactionName),
referrer: 'api.starfish.span-summary-panel-samples-table-avg',
});
diff --git a/static/app/views/starfish/views/spanSummaryPage/index.tsx b/static/app/views/starfish/views/spanSummaryPage/index.tsx
index 64b562a3a803f1..31a1eae2e93683 100644
--- a/static/app/views/starfish/views/spanSummaryPage/index.tsx
+++ b/static/app/views/starfish/views/spanSummaryPage/index.tsx
@@ -65,6 +65,7 @@ function SpanSummaryPage({params, location}: Props) {
const {data, isLoading: isSpanMetricsLoading} = useSpanMetrics({
filters,
fields: ['span.op', 'span.group', 'project.id', 'sps()'],
+ enabled: Boolean(groupId),
referrer: 'api.starfish.span-summary-page-metrics',
});
diff --git a/static/app/views/starfish/views/spanSummaryPage/sampleList/durationChart/index.tsx b/static/app/views/starfish/views/spanSummaryPage/sampleList/durationChart/index.tsx
index 1c3f32bda3bc00..5aae02e93766a4 100644
--- a/static/app/views/starfish/views/spanSummaryPage/sampleList/durationChart/index.tsx
+++ b/static/app/views/starfish/views/spanSummaryPage/sampleList/durationChart/index.tsx
@@ -108,12 +108,16 @@ function DurationChart({
} = useSpanMetricsSeries({
filters: {...filters, ...additionalFilters},
yAxis: [`avg(${SPAN_SELF_TIME})`],
+ enabled: Object.values({...filters, ...additionalFilters}).every(value =>
+ Boolean(value)
+ ),
referrer: 'api.starfish.sidebar-span-metrics-chart',
});
const {data, error: spanMetricsError} = useSpanMetrics({
filters,
fields: [`avg(${SPAN_SELF_TIME})`, SPAN_OP],
+ enabled: Object.values(filters).every(value => Boolean(value)),
referrer: 'api.starfish.span-summary-panel-samples-table-avg',
});
diff --git a/static/app/views/starfish/views/spanSummaryPage/sampleList/sampleInfo/index.tsx b/static/app/views/starfish/views/spanSummaryPage/sampleList/sampleInfo/index.tsx
index 7404440f415e58..dfa305f7ccb173 100644
--- a/static/app/views/starfish/views/spanSummaryPage/sampleList/sampleInfo/index.tsx
+++ b/static/app/views/starfish/views/spanSummaryPage/sampleList/sampleInfo/index.tsx
@@ -52,6 +52,7 @@ function SampleInfo(props: Props) {
'time_spent_percentage()',
'count()',
],
+ enabled: Object.values(filters).every(value => Boolean(value)),
referrer: 'api.starfish.span-summary-panel-metrics',
});
diff --git a/static/app/views/starfish/views/spanSummaryPage/sampleList/sampleTable/sampleTable.tsx b/static/app/views/starfish/views/spanSummaryPage/sampleList/sampleTable/sampleTable.tsx
index 13bd65b4a99570..30eaabbe2f13ca 100644
--- a/static/app/views/starfish/views/spanSummaryPage/sampleList/sampleTable/sampleTable.tsx
+++ b/static/app/views/starfish/views/spanSummaryPage/sampleList/sampleTable/sampleTable.tsx
@@ -67,6 +67,9 @@ function SampleTable({
const {data, isFetching: isFetchingSpanMetrics} = useSpanMetrics({
filters: {...filters, ...additionalFilters},
fields: [`avg(${SPAN_SELF_TIME})`, SPAN_OP],
+ enabled: Object.values({...filters, ...additionalFilters}).every(value =>
+ Boolean(value)
+ ),
referrer: 'api.starfish.span-summary-panel-samples-table-avg',
});
diff --git a/static/app/views/starfish/views/spanSummaryPage/spanSummaryView.tsx b/static/app/views/starfish/views/spanSummaryPage/spanSummaryView.tsx
index 9af1829ba288d2..189fc46d61fd9e 100644
--- a/static/app/views/starfish/views/spanSummaryPage/spanSummaryView.tsx
+++ b/static/app/views/starfish/views/spanSummaryPage/spanSummaryView.tsx
@@ -64,6 +64,7 @@ export function SpanSummaryView({groupId}: Props) {
`${SpanFunction.TIME_SPENT_PERCENTAGE}()`,
`${SpanFunction.HTTP_ERROR_COUNT}()`,
],
+ enabled: Boolean(groupId),
referrer: 'api.starfish.span-summary-page-metrics',
});
@@ -93,6 +94,7 @@ export function SpanSummaryView({groupId}: Props) {
useSpanMetricsSeries({
filters: {'span.group': groupId, ...seriesQueryFilter},
yAxis: [`avg(${SpanMetricsField.SPAN_SELF_TIME})`, 'spm()', 'http_error_count()'],
+ enabled: Boolean(groupId),
referrer: 'api.starfish.span-summary-page-metrics-chart',
});
|
823ff5e9d08ee6fb30d23e33efb19a8998144eb2
|
2022-05-27 00:28:51
|
Leander Rodrigues
|
fix(integrations): Ignore 30x errors in response type #35031
| false
|
Ignore 30x errors in response type #35031
|
fix
|
diff --git a/src/sentry/shared_integrations/response/base.py b/src/sentry/shared_integrations/response/base.py
index d7b68025a591c4..458e66f2172bf0 100644
--- a/src/sentry/shared_integrations/response/base.py
+++ b/src/sentry/shared_integrations/response/base.py
@@ -61,9 +61,9 @@ def from_response(
elif response.text.startswith("<"):
if not allow_text:
raise ValueError(f"Not a valid response type: {response.text[:128]}")
- elif ignore_webhook_errors and response.status_code >= 300:
+ elif ignore_webhook_errors and response.status_code >= 400:
return BaseApiResponse()
- elif response.status_code < 200 or response.status_code >= 300:
+ elif response.status_code < 200 or response.status_code >= 400:
raise ValueError(
f"Received unexpected plaintext response for code {response.status_code}"
)
diff --git a/tests/sentry/integrations/test_client.py b/tests/sentry/integrations/test_client.py
index 62d32b97af3560..83480a701f8ed7 100644
--- a/tests/sentry/integrations/test_client.py
+++ b/tests/sentry/integrations/test_client.py
@@ -105,6 +105,42 @@ def test_head_cached_query_param(self):
ApiClient().head_cached("http://example.com", params={"param": "different"})
assert len(responses.calls) == 2
+ @responses.activate
+ def test_default_redirect_behaviour(self):
+ destination_url = "http://example.com/destination"
+ destination_status = 202
+ destination_headers = {"Location": destination_url}
+
+ responses.add(responses.GET, destination_url, status=destination_status, json={})
+ responses.add(responses.DELETE, destination_url, status=destination_status, json={})
+
+ responses.add(
+ responses.GET, "http://example.com/1", status=301, headers=destination_headers
+ )
+ resp = ApiClient().get("http://example.com/1")
+ assert resp.status_code == destination_status
+
+ # By default, non GET requests are not allowed to redirect
+ responses.add(
+ responses.DELETE,
+ "http://example.com/2",
+ status=301,
+ headers=destination_headers,
+ json={},
+ )
+ resp = ApiClient().delete("http://example.com/2")
+ assert resp.status_code == 301
+
+ responses.add(
+ responses.DELETE,
+ "http://example.com/3",
+ status=301,
+ headers=destination_headers,
+ json={},
+ )
+ resp = ApiClient().delete("http://example.com/3", allow_redirects=True)
+ assert resp.status_code == destination_status
+
class OAuthProvider(OAuth2Provider):
key = "oauth"
|
9ce6767a14924815259f5d376e63e81848b8e95a
|
2023-08-17 00:20:08
|
Evan Purkhiser
|
ref(crons): Move constants to sentry.monitors.constants (#54852)
| false
|
Move constants to sentry.monitors.constants (#54852)
|
ref
|
diff --git a/src/sentry/monitors/constants.py b/src/sentry/monitors/constants.py
new file mode 100644
index 00000000000000..289ab55563aae2
--- /dev/null
+++ b/src/sentry/monitors/constants.py
@@ -0,0 +1,9 @@
+# default maximum runtime for a monitor, in minutes
+TIMEOUT = 30
+
+# hard maximum runtime for a monitor, in minutes
+# current limit is 28 days
+MAX_TIMEOUT = 40_320
+
+# Format to use in the issue subtitle for the missed check-in timestamp
+SUBTITLE_DATETIME_FORMAT = "%b %d, %I:%M %p"
diff --git a/src/sentry/monitors/tasks.py b/src/sentry/monitors/tasks.py
index ac6c7f8bceb4e5..6fe9bc537649f8 100644
--- a/src/sentry/monitors/tasks.py
+++ b/src/sentry/monitors/tasks.py
@@ -9,6 +9,7 @@
from django.utils import timezone
from sentry.constants import ObjectStatus
+from sentry.monitors.constants import SUBTITLE_DATETIME_FORMAT, TIMEOUT
from sentry.monitors.types import ClockPulseMessage
from sentry.silo import SiloMode
from sentry.tasks.base import instrumented_task
@@ -27,13 +28,6 @@
logger = logging.getLogger("sentry")
-# default maximum runtime for a monitor, in minutes
-TIMEOUT = 30
-
-# hard maximum runtime for a monitor, in minutes
-# current limit is 28 days
-MAX_TIMEOUT = 40_320
-
# This is the MAXIMUM number of MONITOR this job will check.
#
# NOTE: We should keep an eye on this as we have more and more usage of
@@ -46,9 +40,6 @@
# monitors the larger the number of checkins to check will exist.
CHECKINS_LIMIT = 10_000
-# Format to use in the issue subtitle for the missed check-in timestamp
-SUBTITLE_DATETIME_FORMAT = "%b %d, %I:%M %p"
-
# This key is used to store the last timestamp that the tasks were triggered.
MONITOR_TASKS_LAST_TRIGGERED_KEY = "sentry.monitors.last_tasks_ts"
diff --git a/src/sentry/monitors/utils.py b/src/sentry/monitors/utils.py
index 1a148773061e73..d677e9d4209dfc 100644
--- a/src/sentry/monitors/utils.py
+++ b/src/sentry/monitors/utils.py
@@ -13,8 +13,8 @@
from sentry.models.project import Project
from sentry.signals import first_cron_checkin_received, first_cron_monitor_created
+from .constants import MAX_TIMEOUT, TIMEOUT
from .models import CheckInStatus, Monitor, MonitorCheckIn
-from .tasks import MAX_TIMEOUT, TIMEOUT
def signal_first_checkin(project: Project, monitor: Monitor):
diff --git a/src/sentry/monitors/validators.py b/src/sentry/monitors/validators.py
index ad993264b77666..b0b382e8536179 100644
--- a/src/sentry/monitors/validators.py
+++ b/src/sentry/monitors/validators.py
@@ -11,6 +11,7 @@
from sentry.api.serializers.rest_framework.project import ProjectField
from sentry.constants import ObjectStatus
from sentry.db.models import BoundedPositiveIntegerField
+from sentry.monitors.constants import MAX_TIMEOUT
from sentry.monitors.models import (
MAX_SLUG_LENGTH,
CheckInStatus,
@@ -18,7 +19,6 @@
MonitorType,
ScheduleType,
)
-from sentry.monitors.tasks import MAX_TIMEOUT
MONITOR_TYPES = {"cron_job": MonitorType.CRON_JOB}
diff --git a/tests/sentry/monitors/endpoints/test_monitor_ingest_checkin_details.py b/tests/sentry/monitors/endpoints/test_monitor_ingest_checkin_details.py
index f8c42bf0d54b2c..bd3d6f1e7a2b57 100644
--- a/tests/sentry/monitors/endpoints/test_monitor_ingest_checkin_details.py
+++ b/tests/sentry/monitors/endpoints/test_monitor_ingest_checkin_details.py
@@ -5,6 +5,7 @@
from sentry.db.models import BoundedPositiveIntegerField
from sentry.models import Environment
+from sentry.monitors.constants import TIMEOUT
from sentry.monitors.models import (
CheckInStatus,
Monitor,
@@ -13,7 +14,6 @@
MonitorStatus,
MonitorType,
)
-from sentry.monitors.tasks import TIMEOUT
from sentry.testutils.cases import MonitorIngestTestCase
from sentry.testutils.silo import region_silo_test
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 569907b282002d..63663424631c9e 100644
--- a/tests/sentry/monitors/endpoints/test_monitor_ingest_checkin_index.py
+++ b/tests/sentry/monitors/endpoints/test_monitor_ingest_checkin_index.py
@@ -11,6 +11,7 @@
from sentry.constants import ObjectStatus
from sentry.db.models import BoundedPositiveIntegerField
+from sentry.monitors.constants import TIMEOUT
from sentry.monitors.models import (
CheckInStatus,
Monitor,
@@ -20,7 +21,6 @@
MonitorType,
ScheduleType,
)
-from sentry.monitors.tasks import TIMEOUT
from sentry.testutils.cases import MonitorIngestTestCase
from sentry.testutils.silo import region_silo_test
diff --git a/tests/sentry/monitors/test_models.py b/tests/sentry/monitors/test_models.py
index 90cc9f7d012d8e..1c2a07018e03d4 100644
--- a/tests/sentry/monitors/test_models.py
+++ b/tests/sentry/monitors/test_models.py
@@ -13,6 +13,7 @@
MonitorCheckInMissed,
MonitorCheckInTimeout,
)
+from sentry.monitors.constants import SUBTITLE_DATETIME_FORMAT
from sentry.monitors.models import (
CheckInStatus,
Monitor,
@@ -25,7 +26,6 @@
MonitorType,
ScheduleType,
)
-from sentry.monitors.tasks import SUBTITLE_DATETIME_FORMAT
from sentry.monitors.validators import ConfigValidator
from sentry.testutils.cases import TestCase
from sentry.testutils.helpers import with_feature
diff --git a/tests/sentry/monitors/test_monitor_consumer.py b/tests/sentry/monitors/test_monitor_consumer.py
index c08900c09f8261..60f3020a005d86 100644
--- a/tests/sentry/monitors/test_monitor_consumer.py
+++ b/tests/sentry/monitors/test_monitor_consumer.py
@@ -12,6 +12,7 @@
from sentry import killswitches
from sentry.constants import ObjectStatus
from sentry.db.models import BoundedPositiveIntegerField
+from sentry.monitors.constants import TIMEOUT
from sentry.monitors.consumers.monitor_consumer import StoreMonitorCheckInStrategyFactory
from sentry.monitors.models import (
CheckInStatus,
@@ -22,7 +23,6 @@
MonitorType,
ScheduleType,
)
-from sentry.monitors.tasks import TIMEOUT
from sentry.testutils.cases import TestCase
from sentry.utils import json
from sentry.utils.locking.manager import LockManager
|
929e2f15445f1a6b197ffd1928d10632ec8331b0
|
2024-10-01 01:53:19
|
Seiji Chew
|
chore(projects): Increase project slug limit from 50 -> 100 (#75737)
| false
|
Increase project slug limit from 50 -> 100 (#75737)
|
chore
|
diff --git a/migrations_lockfile.txt b/migrations_lockfile.txt
index 77523d6ec01735..38c7df916d9b03 100644
--- a/migrations_lockfile.txt
+++ b/migrations_lockfile.txt
@@ -10,7 +10,7 @@ hybridcloud: 0016_add_control_cacheversion
nodestore: 0002_nodestore_no_dictfield
remote_subscriptions: 0003_drop_remote_subscription
replays: 0004_index_together
-sentry: 0769_add_seer_fields_to_grouphash_metadata
+sentry: 0770_increase_project_slug_max_length
social_auth: 0002_default_auto_field
uptime: 0014_add_uptime_enviromnet
workflow_engine: 0007_loosen_workflow_action_relationship
diff --git a/src/sentry/api/endpoints/organization_teams.py b/src/sentry/api/endpoints/organization_teams.py
index 505c6bc3d76fb0..5b7f1f6bea4562 100644
--- a/src/sentry/api/endpoints/organization_teams.py
+++ b/src/sentry/api/endpoints/organization_teams.py
@@ -18,6 +18,7 @@
from sentry.apidocs.examples.team_examples import TeamExamples
from sentry.apidocs.parameters import CursorQueryParam, GlobalParams, TeamParams
from sentry.apidocs.utils import inline_sentry_response_serializer
+from sentry.db.models.fields.slug import DEFAULT_SLUG_MAX_LENGTH
from sentry.integrations.models.external_actor import ExternalActor
from sentry.models.organizationmember import OrganizationMember
from sentry.models.organizationmemberteam import OrganizationMemberTeam
@@ -44,7 +45,7 @@ class TeamPostSerializer(serializers.Serializer):
slug = SentrySerializerSlugField(
help_text="""Uniquely identifies a team and is used for the interface. If not
provided, it is automatically generated from the name.""",
- max_length=50,
+ max_length=DEFAULT_SLUG_MAX_LENGTH,
required=False,
allow_null=True,
)
diff --git a/src/sentry/api/endpoints/project_details.py b/src/sentry/api/endpoints/project_details.py
index 8643183113771c..96e265e5eec1d2 100644
--- a/src/sentry/api/endpoints/project_details.py
+++ b/src/sentry/api/endpoints/project_details.py
@@ -45,7 +45,7 @@
)
from sentry.lang.native.utils import STORE_CRASH_REPORTS_MAX, convert_crashreport_count
from sentry.models.group import Group, GroupStatus
-from sentry.models.project import Project
+from sentry.models.project import PROJECT_SLUG_MAX_LENGTH, Project
from sentry.models.projectbookmark import ProjectBookmark
from sentry.models.projectredirect import ProjectRedirect
from sentry.notifications.utils import has_alert_integration
@@ -135,7 +135,7 @@ class ProjectAdminSerializer(ProjectMemberSerializer):
)
slug = SentrySerializerSlugField(
help_text="Uniquely identifies a project and is used for the interface.",
- max_length=50,
+ max_length=PROJECT_SLUG_MAX_LENGTH,
required=False,
)
platform = serializers.CharField(
diff --git a/src/sentry/api/endpoints/team_details.py b/src/sentry/api/endpoints/team_details.py
index 69ec7a73b26cdb..13c984e014afe5 100644
--- a/src/sentry/api/endpoints/team_details.py
+++ b/src/sentry/api/endpoints/team_details.py
@@ -23,6 +23,7 @@
)
from sentry.apidocs.examples.team_examples import TeamExamples
from sentry.apidocs.parameters import GlobalParams, TeamParams
+from sentry.db.models.fields.slug import DEFAULT_SLUG_MAX_LENGTH
from sentry.deletions.models.scheduleddeletion import RegionScheduledDeletion
from sentry.models.team import Team, TeamStatus
@@ -30,7 +31,7 @@
@extend_schema_serializer(exclude_fields=["name"])
class TeamDetailsSerializer(CamelSnakeModelSerializer):
slug = SentrySerializerSlugField(
- max_length=50,
+ max_length=DEFAULT_SLUG_MAX_LENGTH,
help_text="Uniquely identifies a team. This is must be available.",
)
diff --git a/src/sentry/api/endpoints/team_projects.py b/src/sentry/api/endpoints/team_projects.py
index 73ce44a11de871..98fadbfd2a7142 100644
--- a/src/sentry/api/endpoints/team_projects.py
+++ b/src/sentry/api/endpoints/team_projects.py
@@ -22,7 +22,7 @@
from sentry.apidocs.parameters import CursorQueryParam, GlobalParams
from sentry.apidocs.utils import inline_sentry_response_serializer
from sentry.constants import RESERVED_PROJECT_SLUGS, ObjectStatus
-from sentry.models.project import Project
+from sentry.models.project import PROJECT_SLUG_MAX_LENGTH, Project
from sentry.models.team import Team
from sentry.seer.similarity.utils import project_is_seer_eligible
from sentry.signals import project_created
@@ -38,7 +38,7 @@ class ProjectPostSerializer(serializers.Serializer):
slug = SentrySerializerSlugField(
help_text="""Uniquely identifies a project and is used for the interface.
If not provided, it is automatically generated from the name.""",
- max_length=50,
+ max_length=PROJECT_SLUG_MAX_LENGTH,
required=False,
allow_null=True,
)
diff --git a/src/sentry/api/fields/sentry_slug.py b/src/sentry/api/fields/sentry_slug.py
index 6301e9483eaffc..24eecce61da290 100644
--- a/src/sentry/api/fields/sentry_slug.py
+++ b/src/sentry/api/fields/sentry_slug.py
@@ -4,6 +4,7 @@
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
+from sentry.db.models.fields.slug import DEFAULT_SLUG_MAX_LENGTH
from sentry.slug.errors import DEFAULT_SLUG_ERROR_MESSAGE, ORG_SLUG_ERROR_MESSAGE
from sentry.slug.patterns import MIXED_SLUG_PATTERN, ORG_SLUG_PATTERN
@@ -24,6 +25,7 @@ def __init__(
self,
error_messages=None,
org_slug: bool = False,
+ max_length: int = DEFAULT_SLUG_MAX_LENGTH,
*args,
**kwargs,
):
@@ -37,4 +39,6 @@ def __init__(
pattern = ORG_SLUG_PATTERN
error_messages["invalid"] = ORG_SLUG_ERROR_MESSAGE
- super().__init__(pattern, error_messages=error_messages, *args, **kwargs)
+ super().__init__(
+ pattern, error_messages=error_messages, max_length=max_length, *args, **kwargs
+ )
diff --git a/src/sentry/api/serializers/models/organization.py b/src/sentry/api/serializers/models/organization.py
index 0b4d6c72caaf19..8cba629e2739c2 100644
--- a/src/sentry/api/serializers/models/organization.py
+++ b/src/sentry/api/serializers/models/organization.py
@@ -51,6 +51,7 @@
UPTIME_AUTODETECTION,
ObjectStatus,
)
+from sentry.db.models.fields.slug import DEFAULT_SLUG_MAX_LENGTH
from sentry.dynamic_sampling.tasks.common import get_organization_volume
from sentry.dynamic_sampling.tasks.helpers.sliding_window import get_sliding_window_org_sample_rate
from sentry.killswitches import killswitch_matches_context
@@ -101,7 +102,7 @@ class BaseOrganizationSerializer(serializers.Serializer):
# 3. cannot end with a dash
slug = SentrySerializerSlugField(
org_slug=True,
- max_length=50,
+ max_length=DEFAULT_SLUG_MAX_LENGTH,
)
def validate_slug(self, value: str) -> str:
diff --git a/src/sentry/db/models/fields/slug.py b/src/sentry/db/models/fields/slug.py
index fa435e4a930665..ebb57ea2efbbc2 100644
--- a/src/sentry/db/models/fields/slug.py
+++ b/src/sentry/db/models/fields/slug.py
@@ -3,6 +3,8 @@
from sentry.slug.validators import no_numeric_validator, org_slug_validator
+DEFAULT_SLUG_MAX_LENGTH = 50
+
class SentrySlugField(SlugField):
default_validators = [*SlugField.default_validators, no_numeric_validator]
diff --git a/src/sentry/migrations/0770_increase_project_slug_max_length.py b/src/sentry/migrations/0770_increase_project_slug_max_length.py
new file mode 100644
index 00000000000000..c131b8b6fe76a2
--- /dev/null
+++ b/src/sentry/migrations/0770_increase_project_slug_max_length.py
@@ -0,0 +1,34 @@
+# Generated by Django 5.1.1 on 2024-09-30 19:46
+
+from django.db import migrations
+
+import sentry.db.models.fields.slug
+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.
+ # This should only be used for operations where it's safe to run the migration after your
+ # code has deployed. So this should not be used for most operations that alter the schema
+ # of a table.
+ # Here are some things that make sense to mark as post deployment:
+ # - Large data migrations. Typically we want these to be run manually so that they can be
+ # monitored and not block the deploy for a long period of time while they run.
+ # - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to
+ # run this outside deployments so that we don't block them. Note that while adding an index
+ # is a schema change, it's completely safe to run the operation after the code has deployed.
+ # Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment
+
+ is_post_deployment = True
+
+ dependencies = [
+ ("sentry", "0769_add_seer_fields_to_grouphash_metadata"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="project",
+ name="slug",
+ field=sentry.db.models.fields.slug.SentrySlugField(max_length=100, null=True),
+ ),
+ ]
diff --git a/src/sentry/models/project.py b/src/sentry/models/project.py
index 7959088256ab8f..8cadf8fad3a5a2 100644
--- a/src/sentry/models/project.py
+++ b/src/sentry/models/project.py
@@ -54,6 +54,7 @@
from sentry.users.models.user import User
SENTRY_USE_SNOWFLAKE = getattr(settings, "SENTRY_USE_SNOWFLAKE", False)
+PROJECT_SLUG_MAX_LENGTH = 100
# NOTE:
# - When you modify this list, ensure that the platform IDs listed in "sentry/static/app/data/platforms.tsx" match.
@@ -232,7 +233,7 @@ class Project(Model, PendingDeletionMixin):
__relocation_scope__ = RelocationScope.Organization
- slug = SentrySlugField(null=True)
+ slug = SentrySlugField(null=True, max_length=PROJECT_SLUG_MAX_LENGTH)
# DEPRECATED do not use, prefer slug
name = models.CharField(max_length=200)
forced_color = models.CharField(max_length=6, null=True, blank=True)
diff --git a/src/sentry/monitors/constants.py b/src/sentry/monitors/constants.py
index 8f06d3589dff4a..fb19678754fc46 100644
--- a/src/sentry/monitors/constants.py
+++ b/src/sentry/monitors/constants.py
@@ -16,9 +16,6 @@
# being marked as missed
DEFAULT_CHECKIN_MARGIN = 1
-# Enforced maximum length of the monitor slug
-MAX_SLUG_LENGTH = 50
-
class PermitCheckInStatus(Enum):
ACCEPT = 0
diff --git a/src/sentry/monitors/models.py b/src/sentry/monitors/models.py
index 01d40e872da4c6..017d0c9e1dbf49 100644
--- a/src/sentry/monitors/models.py
+++ b/src/sentry/monitors/models.py
@@ -31,13 +31,12 @@
sane_repr,
)
from sentry.db.models.fields.hybrid_cloud_foreign_key import HybridCloudForeignKey
-from sentry.db.models.fields.slug import SentrySlugField
+from sentry.db.models.fields.slug import DEFAULT_SLUG_MAX_LENGTH, SentrySlugField
from sentry.db.models.manager.base import BaseManager
from sentry.db.models.utils import slugify_instance
from sentry.locks import locks
from sentry.models.environment import Environment
from sentry.models.rule import Rule, RuleSource
-from sentry.monitors.constants import MAX_SLUG_LENGTH
from sentry.monitors.types import CrontabSchedule, IntervalSchedule
from sentry.types.actor import Actor
from sentry.utils.retries import TimedRetryPolicy
@@ -296,7 +295,7 @@ def save(self, *args, **kwargs):
self,
self.name,
organization_id=self.organization_id,
- max_length=MAX_SLUG_LENGTH,
+ max_length=DEFAULT_SLUG_MAX_LENGTH,
)
return super().save(*args, **kwargs)
diff --git a/src/sentry/monitors/types.py b/src/sentry/monitors/types.py
index 7a1832983c490f..50f17140da8558 100644
--- a/src/sentry/monitors/types.py
+++ b/src/sentry/monitors/types.py
@@ -8,7 +8,7 @@
from django.utils.text import slugify
from sentry_kafka_schemas.schema_types.ingest_monitors_v1 import CheckIn
-from sentry.monitors.constants import MAX_SLUG_LENGTH
+from sentry.db.models.fields.slug import DEFAULT_SLUG_MAX_LENGTH
class CheckinTrace(TypedDict):
@@ -70,7 +70,7 @@ class CheckinItem:
@cached_property
def valid_monitor_slug(self):
- return slugify(self.payload["monitor_slug"])[:MAX_SLUG_LENGTH].strip("-")
+ return slugify(self.payload["monitor_slug"])[:DEFAULT_SLUG_MAX_LENGTH].strip("-")
@property
def processing_key(self):
diff --git a/src/sentry/monitors/validators.py b/src/sentry/monitors/validators.py
index 931c497e6cead2..417540964f9fb2 100644
--- a/src/sentry/monitors/validators.py
+++ b/src/sentry/monitors/validators.py
@@ -16,7 +16,8 @@
from sentry.api.serializers.rest_framework.project import ProjectField
from sentry.constants import ObjectStatus
from sentry.db.models import BoundedPositiveIntegerField
-from sentry.monitors.constants import MAX_SLUG_LENGTH, MAX_THRESHOLD, MAX_TIMEOUT
+from sentry.db.models.fields.slug import DEFAULT_SLUG_MAX_LENGTH
+from sentry.monitors.constants import MAX_THRESHOLD, MAX_TIMEOUT
from sentry.monitors.models import CheckInStatus, Monitor, MonitorType, ScheduleType
from sentry.monitors.schedule import get_next_schedule, get_prev_schedule
from sentry.monitors.types import CrontabSchedule
@@ -246,7 +247,7 @@ class MonitorValidator(CamelSnakeSerializer):
help_text="Name of the monitor. Used for notifications.",
)
slug = SentrySerializerSlugField(
- max_length=MAX_SLUG_LENGTH,
+ max_length=DEFAULT_SLUG_MAX_LENGTH,
required=False,
help_text="Uniquely identifies your monitor within your organization. Changing this slug will require updates to any instrumented check-in calls.",
)
|
ff2709757eaf78a360217db1fe251b16f12d04e5
|
2022-02-15 22:54:57
|
getsentry-bot
|
meta: Bump new development version
| false
|
Bump new development version
|
meta
|
diff --git a/setup.py b/setup.py
index 7583b80473b5c6..66d21b569d1cf9 100755
--- a/setup.py
+++ b/setup.py
@@ -32,7 +32,7 @@
BuildJsSdkRegistryCommand,
)
-VERSION = "22.2.0"
+VERSION = "22.3.0.dev0"
IS_LIGHT_BUILD = os.environ.get("SENTRY_LIGHT_BUILD") == "1"
|
739e31ce63c0b33c96ee86eb287247fee5f83861
|
2022-08-19 01:35:21
|
Stephen Cefali
|
feat(notifications): adds providers to notification settings endpint (#37906)
| false
|
adds providers to notification settings endpint (#37906)
|
feat
|
diff --git a/src/sentry/api/endpoints/user_notification_settings_details.py b/src/sentry/api/endpoints/user_notification_settings_details.py
index 4b3bfe7a648b79..0cfeb0f23931dd 100644
--- a/src/sentry/api/endpoints/user_notification_settings_details.py
+++ b/src/sentry/api/endpoints/user_notification_settings_details.py
@@ -7,6 +7,7 @@
from sentry.api.serializers.models.notification_setting import NotificationSettingsSerializer
from sentry.api.validators.notifications import validate, validate_type_option
from sentry.models import NotificationSetting, User
+from sentry.notifications.helpers import get_providers_for_recipient
class UserNotificationSettingsDetailsEndpoint(UserEndpoint):
@@ -29,16 +30,25 @@ def get(self, request: Request, user: User) -> Response:
"""
type_option = validate_type_option(request.GET.get("type"))
+ v2_format = request.GET.get("v2") == "1"
- return Response(
- serialize(
- user,
- request.user,
- NotificationSettingsSerializer(),
- type=type_option,
- ),
+ notification_preferences = serialize(
+ user,
+ request.user,
+ NotificationSettingsSerializer(),
+ type=type_option,
)
+ if v2_format:
+ return Response(
+ {
+ "providers": list(map(lambda x: x.name, get_providers_for_recipient(user))),
+ "preferences": notification_preferences,
+ }
+ )
+
+ return Response(notification_preferences)
+
def put(self, request: Request, user: User) -> Response:
"""
Update the Notification Settings for a given User.
diff --git a/src/sentry/notifications/helpers.py b/src/sentry/notifications/helpers.py
index 26245d540f1237..da7e318819ac0d 100644
--- a/src/sentry/notifications/helpers.py
+++ b/src/sentry/notifications/helpers.py
@@ -15,7 +15,13 @@
NotificationSettingOptionValues,
NotificationSettingTypes,
)
-from sentry.types.integrations import EXTERNAL_PROVIDERS, ExternalProviders
+from sentry.types.integrations import (
+ EXTERNAL_PROVIDERS,
+ ExternalProviders,
+ get_provider_enum,
+ get_provider_enum_from_string,
+ get_provider_name,
+)
if TYPE_CHECKING:
from sentry.models import (
@@ -583,3 +589,29 @@ def get_values_by_provider(
get_value_for_actor(notification_settings_by_scope, recipient),
get_value_for_parent(notification_settings_by_scope, parent_id, type),
)
+
+
+def get_providers_for_recipient(recipient: User | Team) -> Iterable[ExternalProviders]:
+ from sentry.models import ExternalActor, Identity, Team
+
+ possible_providers = NOTIFICATION_SETTING_DEFAULTS.keys()
+ if isinstance(recipient, Team):
+ return list(
+ map(
+ get_provider_enum,
+ ExternalActor.objects.filter(
+ actor_id=recipient.actor_id, provider__in=possible_providers
+ ).values_list("provider", flat=True),
+ )
+ )
+
+ return list(
+ map(
+ get_provider_enum_from_string,
+ Identity.objects.filter(
+ user=recipient, idp__type__in=list(map(get_provider_name, possible_providers))
+ ).values_list("idp__type", flat=True),
+ )
+ ) + [
+ ExternalProviders.EMAIL
+ ] # always add in email as an option
diff --git a/src/sentry/notifications/notifications/strategies/role_based_recipient_strategy.py b/src/sentry/notifications/notifications/strategies/role_based_recipient_strategy.py
index 5e82828d63e168..b3ba0014a1f237 100644
--- a/src/sentry/notifications/notifications/strategies/role_based_recipient_strategy.py
+++ b/src/sentry/notifications/notifications/strategies/role_based_recipient_strategy.py
@@ -38,7 +38,9 @@ def determine_recipients(
for member in members:
self.set_member_in_cache(member)
# convert members to users
- return map(lambda member: member.user, members)
+ user_map: Iterable[User] = map(lambda member: member.user, members)
+ # convert to list from an interterator
+ return list(user_map)
@abstractmethod
def determine_member_recipients(self) -> Iterable[OrganizationMember]:
diff --git a/src/sentry/types/integrations.py b/src/sentry/types/integrations.py
index d5559e4b23d99f..518ad71be089e7 100644
--- a/src/sentry/types/integrations.py
+++ b/src/sentry/types/integrations.py
@@ -45,3 +45,14 @@ def get_provider_enum(value: Optional[str]) -> Optional[ExternalProviders]:
def get_provider_choices(providers: Set[ExternalProviders]) -> Sequence[str]:
return list(EXTERNAL_PROVIDERS.get(i) for i in providers)
+
+
+def get_provider_enum_from_string(provider: str) -> ExternalProviders:
+ for k, v in EXTERNAL_PROVIDERS.items():
+ if v == provider:
+ return k
+ raise InvalidProviderException("Invalid provider ${provider}")
+
+
+class InvalidProviderException(Exception):
+ pass
diff --git a/tests/sentry/api/endpoints/test_user_notification_settings.py b/tests/sentry/api/endpoints/test_user_notification_settings.py
index a56d1c441b7859..dbc4e6a38c59cc 100644
--- a/tests/sentry/api/endpoints/test_user_notification_settings.py
+++ b/tests/sentry/api/endpoints/test_user_notification_settings.py
@@ -100,6 +100,116 @@ def test_invalid_notification_setting(self):
assert other_project.id not in response.data["workflow"]["project"]
+class UserNotificationSettingsTestBase(APITestCase):
+ endpoint = "sentry-api-0-user-notification-settings"
+
+ def setUp(self):
+ super().setUp()
+ self.login_as(self.user)
+
+
+class UserNotificationSettingsGetTestV2(UserNotificationSettingsTestBase):
+ def get_v2_response(self, qs_params=None, **kwargs):
+ qs_params = qs_params or {}
+ qs_params["v2"] = "1"
+ return self.get_success_response("me", qs_params=qs_params, **kwargs)
+
+ def test_simple(self):
+ NotificationSetting.objects.update_settings(
+ ExternalProviders.EMAIL,
+ NotificationSettingTypes.ISSUE_ALERTS,
+ NotificationSettingOptionValues.NEVER,
+ user=self.user,
+ )
+ NotificationSetting.objects.update_settings(
+ ExternalProviders.EMAIL,
+ NotificationSettingTypes.DEPLOY,
+ NotificationSettingOptionValues.NEVER,
+ user=self.user,
+ organization=self.organization,
+ )
+ NotificationSetting.objects.update_settings(
+ ExternalProviders.SLACK,
+ NotificationSettingTypes.DEPLOY,
+ NotificationSettingOptionValues.ALWAYS,
+ user=self.user,
+ organization=self.organization,
+ )
+ NotificationSetting.objects.update_settings(
+ ExternalProviders.SLACK,
+ NotificationSettingTypes.WORKFLOW,
+ NotificationSettingOptionValues.SUBSCRIBE_ONLY,
+ user=self.user,
+ )
+
+ response = self.get_v2_response()
+
+ # Spot check.
+ preferences = response.data["preferences"]
+ assert preferences["alerts"]["user"][self.user.id]["email"] == "never"
+ assert preferences["deploy"]["organization"][self.organization.id]["email"] == "never"
+ assert preferences["deploy"]["organization"][self.organization.id]["slack"] == "always"
+ assert preferences["workflow"]["user"][self.user.id]["slack"] == "subscribe_only"
+
+ providers = response.data["providers"]
+ assert providers == ["email"]
+
+ def test_slack_enabled(self):
+ self.integration = self.create_slack_integration(self.organization, user=self.user)
+ response = self.get_v2_response()
+ providers = response.data["providers"]
+ assert sorted(providers) == ["email", "slack"]
+
+ def test_notification_settings_empty(self):
+ _ = self.organization # HACK to force creation.
+
+ response = self.get_v2_response()
+
+ # Spot check.
+ preferences = response.data["preferences"]
+ assert preferences["alerts"]["user"][self.user.id]["email"] == "always"
+ assert preferences["deploy"]["organization"][self.organization.id]["email"] == "default"
+ assert preferences["deploy"]["organization"][self.organization.id]["slack"] == "default"
+ assert preferences["workflow"]["user"][self.user.id]["slack"] == "subscribe_only"
+
+ def test_type_querystring(self):
+ response = self.get_v2_response(qs_params={"type": "workflow"})
+
+ assert "alerts" not in response.data["preferences"]
+ assert "workflow" in response.data["preferences"]
+
+ def test_invalid_querystring(self):
+ self.get_error_response(
+ "me", qs_params={"type": "invalid"}, status_code=status.HTTP_400_BAD_REQUEST
+ )
+
+ def test_invalid_user_id(self):
+ self.get_error_response("invalid", status_code=status.HTTP_404_NOT_FOUND)
+
+ def test_wrong_user_id(self):
+ other_user = self.create_user("[email protected]")
+
+ self.get_error_response(other_user.id, status_code=status.HTTP_403_FORBIDDEN)
+
+ def test_invalid_notification_setting(self):
+ other_organization = self.create_organization(name="Rowdy Tiger", owner=None)
+ other_project = self.create_project(
+ organization=other_organization, teams=[], name="Bengal"
+ )
+
+ NotificationSetting.objects.update_settings(
+ ExternalProviders.SLACK,
+ NotificationSettingTypes.WORKFLOW,
+ NotificationSettingOptionValues.SUBSCRIBE_ONLY,
+ user=self.user,
+ project=other_project,
+ )
+
+ response = self.get_v2_response()
+
+ assert other_project.id not in response.data["preferences"]["workflow"]["project"]
+
+
class UserNotificationSettingsTest(UserNotificationSettingsTestBase):
method = "put"
|
fcd632cce639437dbc61081b1d3064c45c1d7b6f
|
2022-05-13 20:24:03
|
Vu Luong
|
ref(release-details): Use DropdownMenuV2 for archive/restore menu (#34498)
| false
|
Use DropdownMenuV2 for archive/restore menu (#34498)
|
ref
|
diff --git a/static/app/views/releases/detail/header/releaseActions.tsx b/static/app/views/releases/detail/header/releaseActions.tsx
index 7044afd8b38eb8..4d837e07e23c97 100644
--- a/static/app/views/releases/detail/header/releaseActions.tsx
+++ b/static/app/views/releases/detail/header/releaseActions.tsx
@@ -5,12 +5,10 @@ import {Location} from 'history';
import {archiveRelease, restoreRelease} from 'sentry/actionCreators/release';
import {Client} from 'sentry/api';
-import Button from 'sentry/components/button';
import ButtonBar from 'sentry/components/buttonBar';
-import Confirm from 'sentry/components/confirm';
-import DropdownLink from 'sentry/components/dropdownLink';
+import {openConfirmModal} from 'sentry/components/confirm';
+import DropdownMenuControlV2 from 'sentry/components/dropdownMenuControlV2';
import ProjectBadge from 'sentry/components/idBadge/projectBadge';
-import MenuItem from 'sentry/components/menuItem';
import NavigationButtonGroup from 'sentry/components/navigationButtonGroup';
import TextOverflow from 'sentry/components/textOverflow';
import Tooltip from 'sentry/components/tooltip';
@@ -133,6 +131,54 @@ function ReleaseActions({
});
}
+ const menuItems = [
+ isReleaseArchived(release)
+ ? {
+ key: 'restore',
+ label: t('Restore'),
+ onAction: () =>
+ openConfirmModal({
+ onConfirm: handleRestore,
+ header: getModalHeader(
+ tct('Restore Release [release]', {
+ release: formatVersion(release.version),
+ })
+ ),
+ message: getModalMessage(
+ tn(
+ 'You are restoring this release for the following project:',
+ 'By restoring this release, you are also restoring it for the following projects:',
+ releaseMeta.projects.length
+ )
+ ),
+ cancelText: t('Nevermind'),
+ confirmText: t('Restore'),
+ }),
+ }
+ : {
+ key: 'archive',
+ label: t('Archive'),
+ onAction: () =>
+ openConfirmModal({
+ onConfirm: handleArchive,
+ header: getModalHeader(
+ tct('Archive Release [release]', {
+ release: formatVersion(release.version),
+ })
+ ),
+ message: getModalMessage(
+ tn(
+ 'You are archiving this release for the following project:',
+ 'By archiving this release, you are also archiving it for the following projects:',
+ releaseMeta.projects.length
+ )
+ ),
+ cancelText: t('Nevermind'),
+ confirmText: t('Archive'),
+ }),
+ },
+ ];
+
const {
nextReleaseVersion,
prevReleaseVersion,
@@ -156,69 +202,19 @@ function ReleaseActions({
onNewerClick={() => handleNavigationClick('newer')}
onNewestClick={() => handleNavigationClick('newest')}
/>
- <StyledDropdownLink
- caret={false}
- anchorRight={window.innerWidth > 992}
- title={<ActionsButton icon={<IconEllipsis />} aria-label={t('Actions')} />}
- >
- {isReleaseArchived(release) ? (
- <Confirm
- onConfirm={handleRestore}
- header={getModalHeader(
- tct('Restore Release [release]', {
- release: formatVersion(release.version),
- })
- )}
- message={getModalMessage(
- tn(
- 'You are restoring this release for the following project:',
- 'By restoring this release, you are also restoring it for the following projects:',
- releaseMeta.projects.length
- )
- )}
- cancelText={t('Nevermind')}
- confirmText={t('Restore')}
- >
- <MenuItem>{t('Restore')}</MenuItem>
- </Confirm>
- ) : (
- <Confirm
- onConfirm={handleArchive}
- header={getModalHeader(
- tct('Archive Release [release]', {
- release: formatVersion(release.version),
- })
- )}
- message={getModalMessage(
- tn(
- 'You are archiving this release for the following project:',
- 'By archiving this release, you are also archiving it for the following projects:',
- releaseMeta.projects.length
- )
- )}
- cancelText={t('Nevermind')}
- confirmText={t('Archive')}
- >
- <MenuItem>{t('Archive')}</MenuItem>
- </Confirm>
- )}
- </StyledDropdownLink>
+ <DropdownMenuControlV2
+ items={menuItems}
+ triggerProps={{
+ showChevron: false,
+ icon: <IconEllipsis />,
+ 'aria-label': t('Actions'),
+ }}
+ placement="bottom right"
+ />
</ButtonBar>
);
}
-const ActionsButton = styled(Button)`
- width: 40px;
- height: 40px;
- padding: 0;
-`;
-
-const StyledDropdownLink = styled(DropdownLink)`
- & + .dropdown-menu {
- top: 50px !important;
- }
-`;
-
const ProjectsWrapper = styled('div')`
margin: ${space(2)} 0 ${space(2)} ${space(2)};
display: grid;
diff --git a/tests/js/spec/views/releases/detail/header/releaseActions.spec.jsx b/tests/js/spec/views/releases/detail/header/releaseActions.spec.jsx
index a12a4c450b8129..fcac3387ab7f04 100644
--- a/tests/js/spec/views/releases/detail/header/releaseActions.spec.jsx
+++ b/tests/js/spec/views/releases/detail/header/releaseActions.spec.jsx
@@ -49,10 +49,9 @@ describe('ReleaseActions', function () {
userEvent.click(screen.getByLabelText('Actions'));
- const actions = screen.getAllByTestId('menu-item');
- const archiveAction = actions.at(0);
+ const archiveAction = screen.getByTestId('archive');
- expect(actions.length).toBe(1);
+ expect(archiveAction).toBeInTheDocument();
expect(archiveAction).toHaveTextContent('Archive');
userEvent.click(archiveAction);
@@ -98,10 +97,9 @@ describe('ReleaseActions', function () {
userEvent.click(screen.getByLabelText('Actions'));
- const actions = screen.getAllByTestId('menu-item');
- const restoreAction = actions.at(0);
+ const restoreAction = screen.getByTestId('restore');
- expect(actions.length).toBe(1);
+ expect(restoreAction).toBeInTheDocument(1);
expect(restoreAction).toHaveTextContent('Restore');
userEvent.click(restoreAction);
|
b4b7a05e748f572c1a8b34897fb317c673938e8a
|
2020-07-08 23:17:36
|
Stephen Cefali
|
fix(vercel): fix bug in pagination (#19767)
| false
|
fix bug in pagination (#19767)
|
fix
|
diff --git a/src/sentry/integrations/vercel/client.py b/src/sentry/integrations/vercel/client.py
index 8f7fb4185629bf..8ece67c5c43b83 100644
--- a/src/sentry/integrations/vercel/client.py
+++ b/src/sentry/integrations/vercel/client.py
@@ -56,9 +56,9 @@ def get_projects(self):
# if we have less projects than the limit, we are done
if resp["pagination"]["count"] < limit:
return projects
- # continue pagination but increment next by 1
+ # continue pagination by setting the until parameter
params = params.copy()
- params["since"] = resp["pagination"]["next"] + 1
+ params["until"] = resp["pagination"]["next"]
# log the warning if this happens so we can look into solutions
logger.warn("Did not finish project pagination", extra={"team_id": self.team_id})
return projects
|
86ddf6d9c94ad72f50227b34a486708733249577
|
2021-01-18 23:16:30
|
Tony
|
fix(perf): Histogram query should not error on nan duration percentiles (#23152)
| false
|
Histogram query should not error on nan duration percentiles (#23152)
|
fix
|
diff --git a/src/sentry/snuba/discover.py b/src/sentry/snuba/discover.py
index 5e613efc6dc6d4..b7eeac2b782a74 100644
--- a/src/sentry/snuba/discover.py
+++ b/src/sentry/snuba/discover.py
@@ -1122,10 +1122,17 @@ def find_histogram_min_max(fields, min_value, max_value, user_query, params, dat
first_quartile = row[q1_alias]
third_quartile = row[q3_alias]
- if first_quartile is not None and third_quartile is not None:
- interquartile_range = abs(third_quartile - first_quartile)
- upper_outer_fence = third_quartile + 3 * interquartile_range
- fences.append(upper_outer_fence)
+ if (
+ first_quartile is None
+ or third_quartile is None
+ or math.isnan(first_quartile)
+ or math.isnan(third_quartile)
+ ):
+ continue
+
+ interquartile_range = abs(third_quartile - first_quartile)
+ upper_outer_fence = third_quartile + 3 * interquartile_range
+ fences.append(upper_outer_fence)
max_fence_value = max(fences) if fences else None
diff --git a/tests/snuba/api/endpoints/test_organization_events_histogram.py b/tests/snuba/api/endpoints/test_organization_events_histogram.py
index 7e3cceaa8804cc..b41a0d54b3f631 100644
--- a/tests/snuba/api/endpoints/test_organization_events_histogram.py
+++ b/tests/snuba/api/endpoints/test_organization_events_histogram.py
@@ -741,3 +741,23 @@ def test_histogram_ignores_aggregate_conditions(self):
response = self.do_request(query)
assert response.status_code == 200
assert response.data == self.as_response_data(specs)
+
+ def test_histogram_outlier_filtering_with_no_rows(self):
+ specs = [
+ (0, 1, [("transaction.duration", 0)]),
+ (1, 2, [("transaction.duration", 0)]),
+ (2, 3, [("transaction.duration", 0)]),
+ (3, 4, [("transaction.duration", 0)]),
+ (4, 5, [("transaction.duration", 0)]),
+ ]
+
+ query = {
+ "project": [self.project.id],
+ "field": ["transaction.duration"],
+ "numBuckets": 5,
+ "dataFilter": "exclude_outliers",
+ }
+
+ response = self.do_request(query)
+ assert response.status_code == 200
+ assert response.data == self.as_response_data(specs)
|
25be804e2d098da08b857af5d688ab0b2bca3b47
|
2021-09-08 05:26:52
|
Evan Purkhiser
|
ref(js): Allow withTeams wrapped components to have `teams` overridden (#28434)
| false
|
Allow withTeams wrapped components to have `teams` overridden (#28434)
|
ref
|
diff --git a/static/app/utils/withTeams.tsx b/static/app/utils/withTeams.tsx
index ceadb0f4a473a0..5f849039056043 100644
--- a/static/app/utils/withTeams.tsx
+++ b/static/app/utils/withTeams.tsx
@@ -5,7 +5,7 @@ import {Team} from 'app/types';
import getDisplayName from 'app/utils/getDisplayName';
type InjectedTeamsProps = {
- teams: Team[];
+ teams?: Team[];
};
type State = {
@@ -18,7 +18,10 @@ type State = {
function withTeams<P extends InjectedTeamsProps>(
WrappedComponent: React.ComponentType<P>
) {
- class WithTeams extends React.Component<Omit<P, keyof InjectedTeamsProps>, State> {
+ class WithTeams extends React.Component<
+ Omit<P, keyof InjectedTeamsProps> & InjectedTeamsProps,
+ State
+ > {
static displayName = `withTeams(${getDisplayName(WrappedComponent)})`;
state = {
@@ -36,7 +39,7 @@ function withTeams<P extends InjectedTeamsProps>(
render() {
return (
- <WrappedComponent {...(this.props as P)} teams={this.state.teams as Team[]} />
+ <WrappedComponent teams={this.state.teams as Team[]} {...(this.props as P)} />
);
}
}
|
a8fd1e1fc80131c11ae24d8874c56610a55b8e47
|
2023-04-20 22:22:20
|
Richard Roggenkemper
|
feat(rulesnooze): mute alert given query parameter (#47650)
| false
|
mute alert given query parameter (#47650)
|
feat
|
diff --git a/static/app/components/alerts/snoozeAlert.tsx b/static/app/components/alerts/snoozeAlert.tsx
index 85e1c7ec2aad52..83969e2b223a3e 100644
--- a/static/app/components/alerts/snoozeAlert.tsx
+++ b/static/app/components/alerts/snoozeAlert.tsx
@@ -1,13 +1,15 @@
-import {useState} from 'react';
+import {useCallback, useEffect, useState} from 'react';
+import {browserHistory} from 'react-router';
import styled from '@emotion/styled';
-import {addErrorMessage} from 'sentry/actionCreators/indicator';
+import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
import {Button} from 'sentry/components/button';
import ButtonBar from 'sentry/components/buttonBar';
import {DropdownMenu, MenuItemProps} from 'sentry/components/dropdownMenu';
import {IconChevron, IconMute, IconSound} from 'sentry/icons';
import {t} from 'sentry/locale';
import useApi from 'sentry/utils/useApi';
+import {useLocation} from 'sentry/utils/useLocation';
import useOrganization from 'sentry/utils/useOrganization';
type Props = {
@@ -24,38 +26,59 @@ type Props = {
function SnoozeAlert({isSnoozed, onSnooze, projectSlug, ruleId}: Props) {
const organization = useOrganization();
const api = useApi();
+ const location = useLocation();
const [disabled, setDisabled] = useState(false);
- async function handleMute(target: 'me' | 'everyone') {
- setDisabled(true);
- try {
- await api.requestPromise(
- `/projects/${organization.slug}/${projectSlug}/rules/${ruleId}/snooze/`,
- {
- method: 'POST',
- data: {
- target,
- },
+ const handleMute = useCallback(
+ async (target: 'me' | 'everyone', autoMute = false) => {
+ setDisabled(true);
+ try {
+ await api.requestPromise(
+ `/projects/${organization.slug}/${projectSlug}/rules/${ruleId}/snooze/`,
+ {
+ method: 'POST',
+ data: {
+ target,
+ },
+ }
+ );
+
+ if (autoMute) {
+ browserHistory.replace({
+ pathname: location.pathname,
+ query: {...location.query, mute: undefined},
+ });
}
- );
- setDisabled(false);
- onSnooze({
- snooze: !isSnoozed,
- snoozeCreatedBy: 'You',
- snoozeForEveryone: target === 'me' ? false : true,
- });
- } catch (err) {
- if (err.status === 403) {
- addErrorMessage(t('You do not have permission to mute this alert'));
- } else if (err.stats === 410) {
- addErrorMessage(t('This alert has already been muted'));
- } else {
- addErrorMessage(t('Unable to mute this alert'));
+ setDisabled(false);
+ addSuccessMessage(t('Alert muted'));
+ onSnooze({
+ snooze: !isSnoozed,
+ snoozeCreatedBy: 'You',
+ snoozeForEveryone: target === 'me' ? false : true,
+ });
+ } catch (err) {
+ if (err.status === 403) {
+ addErrorMessage(t('You do not have permission to mute this alert'));
+ } else if (err.status === 410) {
+ addErrorMessage(t('This alert has already been muted'));
+ } else {
+ addErrorMessage(t('Unable to mute this alert'));
+ }
}
- }
- }
+ },
+ [
+ api,
+ isSnoozed,
+ location.pathname,
+ location.query,
+ onSnooze,
+ organization.slug,
+ projectSlug,
+ ruleId,
+ ]
+ );
async function handleUnmute() {
setDisabled(true);
@@ -69,6 +92,7 @@ function SnoozeAlert({isSnoozed, onSnooze, projectSlug, ruleId}: Props) {
);
setDisabled(false);
+ addSuccessMessage(t('Alert unmuted'));
onSnooze({snooze: !isSnoozed});
} catch (err) {
if (err.status === 403) {
@@ -79,6 +103,12 @@ function SnoozeAlert({isSnoozed, onSnooze, projectSlug, ruleId}: Props) {
}
}
+ useEffect(() => {
+ if (location.query.mute === '1' && !isSnoozed) {
+ handleMute('me', true);
+ }
+ }, [location.query, isSnoozed, handleMute]);
+
const dropdownItems: MenuItemProps[] = [
{
key: 'me',
diff --git a/static/app/views/alerts/rules/issue/details/ruleDetails.spec.jsx b/static/app/views/alerts/rules/issue/details/ruleDetails.spec.jsx
index 388f40d4c89b0d..905dc8ae6368c7 100644
--- a/static/app/views/alerts/rules/issue/details/ruleDetails.spec.jsx
+++ b/static/app/views/alerts/rules/issue/details/ruleDetails.spec.jsx
@@ -19,26 +19,28 @@ describe('AlertRuleDetails', () => {
});
const member = TestStubs.Member();
- const createWrapper = (props = {}) => {
+ const createWrapper = (props = {}, contextWithQueryParam) => {
const params = {
orgId: organization.slug,
projectId: project.slug,
ruleId: rule.id,
};
+
+ const router = contextWithQueryParam ? contextWithQueryParam.router : context.router;
+ const routerContext = contextWithQueryParam
+ ? contextWithQueryParam.routerContext
+ : context.routerContext;
+
return render(
- <RuleDetailsContainer
- params={params}
- location={{query: {}}}
- router={context.router}
- >
+ <RuleDetailsContainer params={params} location={{query: {}}} router={router}>
<AlertRuleDetails
params={params}
location={{query: {}}}
- router={context.router}
+ router={router}
{...props}
/>
</RuleDetailsContainer>,
- {context: context.routerContext, organization}
+ {context: routerContext, organization}
);
};
@@ -212,6 +214,25 @@ describe('AlertRuleDetails', () => {
expect(deleteRequest).toHaveBeenCalledTimes(1);
});
+ it('mutes alert if query parameter is set', async () => {
+ const request = MockApiClient.addMockResponse({
+ url: `/projects/${organization.slug}/${project.slug}/rules/${rule.id}/snooze/`,
+ method: 'POST',
+ data: {target: 'me'},
+ });
+ const contextWithQueryParam = initializeOrg({
+ organization: {features: ['issue-alert-incompatible-rules', 'mute-alerts']},
+ router: {
+ location: {query: {mute: '1'}},
+ },
+ });
+
+ createWrapper({}, contextWithQueryParam);
+
+ expect(await screen.findByText('Unmute')).toBeInTheDocument();
+ expect(request).toHaveBeenCalledTimes(1);
+ });
+
it('inserts user email into rule notify action', async () => {
// Alert rule with "send a notification to member" action
const sendNotificationRule = TestStubs.ProjectAlertRule({
|
4ea79c8a11f5923bce8d95c9f39685614d0f35cd
|
2023-07-18 00:24:36
|
Gilbert Szeto
|
fix(group-attributes): log metric when post_save.send(update_fields=["status", "subs"]) is called for group (#52996)
| false
|
log metric when post_save.send(update_fields=["status", "subs"]) is called for group (#52996)
|
fix
|
diff --git a/src/sentry/issues/attributes.py b/src/sentry/issues/attributes.py
index a4272057c72d0e..d521c29047be32 100644
--- a/src/sentry/issues/attributes.py
+++ b/src/sentry/issues/attributes.py
@@ -41,7 +41,7 @@ def post_save_log_group_attributes_changed(instance, sender, created, *args, **k
if created:
_log_group_attributes_changed(Operation.CREATED, "group", None)
else:
- if "updated_fields" in kwargs:
+ if "update_fields" in kwargs:
update_fields = kwargs["update_fields"]
# 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
|
54ddb1ae6f99ce45ead142fd8751a365ff836ffc
|
2023-01-18 21:39:00
|
Ash Anand
|
feat(perf-issues): Add Slow DB Span Admin Options (#43360)
| false
|
Add Slow DB Span Admin Options (#43360)
|
feat
|
diff --git a/static/app/views/admin/adminSettings.tsx b/static/app/views/admin/adminSettings.tsx
index b78f310d957595..0d2a1cd85479ed 100644
--- a/static/app/views/admin/adminSettings.tsx
+++ b/static/app/views/admin/adminSettings.tsx
@@ -34,6 +34,10 @@ const optionsAvailable = [
'performance.issues.compressed_assets.ea-rollout',
'performance.issues.compressed_assets.ga-rollout',
'performance.issues.file_io_main_thread.problem-creation',
+ 'performance.issues.slow_span.problem-creation',
+ 'performance.issues.slow_span.la-rollout',
+ 'performance.issues.slow_span.ea-rollout',
+ 'performance.issues.slow_span.ga-rollout',
];
type Field = ReturnType<typeof getOption>;
@@ -139,6 +143,13 @@ export default class AdminSettings extends AsyncView<{}, State> {
<PanelHeader>Performance Issues - File IO on Main Thread</PanelHeader>
{fields['performance.issues.file_io_main_thread.problem-creation']}
</Panel>
+ <Panel>
+ <PanelHeader>Performance Issues - Slow DB Span Detector</PanelHeader>
+ {fields['performance.issues.slow_span.problem-creation']}
+ {fields['performance.issues.slow_span.la-rollout']}
+ {fields['performance.issues.slow_span.ea-rollout']}
+ {fields['performance.issues.slow_span.ga-rollout']}
+ </Panel>
</Feature>
</Form>
</div>
diff --git a/static/app/views/admin/options.tsx b/static/app/views/admin/options.tsx
index d7b856f7985409..4d9c7687cd5013 100644
--- a/static/app/views/admin/options.tsx
+++ b/static/app/views/admin/options.tsx
@@ -279,6 +279,38 @@ const performanceOptionDefinitions: Field[] = [
),
...HIGH_THROUGHPUT_RATE_OPTION,
},
+ {
+ key: 'performance.issues.slow_span.problem-creation',
+ label: t('Problem Creation Rate'),
+ help: t(
+ 'Controls the overall rate at which performance problems are detected by the slow DB span detector.'
+ ),
+ ...HIGH_THROUGHPUT_RATE_OPTION,
+ },
+ {
+ key: 'performance.issues.slow_span.la-rollout',
+ label: t('Limited Availability Detection Rate'),
+ help: t(
+ 'Controls the rate at which performance problems are detected by the slow DB span detector for LA organizations.'
+ ),
+ ...HIGH_THROUGHPUT_RATE_OPTION,
+ },
+ {
+ key: 'performance.issues.slow_span.ea-rollout',
+ label: t('Early Adopter Detection Rate'),
+ help: t(
+ 'Controls the rate at which performance problems are detected by the slow DB span detector for EA organizations.'
+ ),
+ ...HIGH_THROUGHPUT_RATE_OPTION,
+ },
+ {
+ key: 'performance.issues.slow_span.ga-rollout',
+ label: t('General Availability Detection Rate'),
+ help: t(
+ 'Controls the rate at which performance problems are detected by the slow DB span detector for GA organizations.'
+ ),
+ ...HIGH_THROUGHPUT_RATE_OPTION,
+ },
];
// This are ordered based on their display order visually
|
780ca8d25e918e458ebf74ff7d359fd481d94fcc
|
2022-06-13 13:47:29
|
dependabot[bot]
|
chore(deps): bump @emotion/react from 11.4.0 to 11.9.0 (#35338)
| false
|
bump @emotion/react from 11.4.0 to 11.9.0 (#35338)
|
chore
|
diff --git a/package.json b/package.json
index e3a105c32fe6b4..7b5927741b487b 100644
--- a/package.json
+++ b/package.json
@@ -19,7 +19,7 @@
"@dnd-kit/sortable": "^4.0.0",
"@emotion/babel-plugin": "^11.9.2",
"@emotion/css": "^11.1.3",
- "@emotion/react": "^11.4.0",
+ "@emotion/react": "^11.9.0",
"@emotion/styled": "^11.3.0",
"@popperjs/core": "^2.11.5",
"@sentry-internal/global-search": "^0.2.2",
diff --git a/static/app/components/events/interfaces/frame/frameRegisters/value.tsx b/static/app/components/events/interfaces/frame/frameRegisters/value.tsx
index 4286c77ce668f1..a41b165e5d1076 100644
--- a/static/app/components/events/interfaces/frame/frameRegisters/value.tsx
+++ b/static/app/components/events/interfaces/frame/frameRegisters/value.tsx
@@ -53,6 +53,7 @@ function Value({meta, value}: Props) {
setState({view: (state.view + 1) % REGISTER_VIEWS.length});
}}
size="xs"
+ aria-label={t('Toggle register value format')}
/>
</StyledTooltip>
</InlinePre>
diff --git a/tests/js/spec/components/events/interfaces/frame/frameRegisters.spec.jsx b/tests/js/spec/components/events/interfaces/frame/frameRegisters.spec.jsx
index fce4111dfda34f..b6e09c4923845f 100644
--- a/tests/js/spec/components/events/interfaces/frame/frameRegisters.spec.jsx
+++ b/tests/js/spec/components/events/interfaces/frame/frameRegisters.spec.jsx
@@ -39,7 +39,7 @@ describe('RegisterValue', () => {
});
it('should display the numeric value', () => {
- wrapper.find('Toggle').simulate('click');
+ wrapper.find('svg[aria-label="Toggle register value format"]').simulate('click');
expect(wrapper.text()).toBe('10');
});
});
@@ -54,7 +54,7 @@ describe('RegisterValue', () => {
});
it('should display the numeric value', () => {
- wrapper.find('Toggle').simulate('click');
+ wrapper.find('svg[aria-label="Toggle register value format"]').simulate('click');
expect(wrapper.text()).toBe('10');
});
});
@@ -69,7 +69,7 @@ describe('RegisterValue', () => {
});
it('should display the numeric value', () => {
- wrapper.find('Toggle').simulate('click');
+ wrapper.find('svg[aria-label="Toggle register value format"]').simulate('click');
expect(wrapper.text()).toBe('xyz');
});
});
diff --git a/yarn.lock b/yarn.lock
index 90058512f0b18d..3a692ba17282eb 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1328,7 +1328,7 @@
resolved "https://registry.yarnpkg.com/@emmetio/scanner/-/scanner-1.0.0.tgz#065b2af6233fe7474d44823e3deb89724af42b5f"
integrity sha512-8HqW8EVqjnCmWXVpqAOZf+EGESdkR27odcMMMGefgKXtar00SoYNSryGv//TELI4T3QFsECo78p+0lmalk/CFA==
-"@emotion/babel-plugin@^11.0.0", "@emotion/babel-plugin@^11.3.0", "@emotion/babel-plugin@^11.9.2":
+"@emotion/babel-plugin@^11.0.0", "@emotion/babel-plugin@^11.3.0", "@emotion/babel-plugin@^11.7.1", "@emotion/babel-plugin@^11.9.2":
version "11.9.2"
resolved "https://registry.yarnpkg.com/@emotion/babel-plugin/-/babel-plugin-11.9.2.tgz#723b6d394c89fb2ef782229d92ba95a740576e95"
integrity sha512-Pr/7HGH6H6yKgnVFNEj2MVlreu3ADqftqjqwUvDy/OJzKFgxKeTQ+eeUf20FOTuHVkDON2iNa25rAXVYtWJCjw==
@@ -1356,16 +1356,16 @@
"@emotion/utils" "0.11.3"
"@emotion/weak-memoize" "0.2.5"
-"@emotion/cache@^11.1.3", "@emotion/cache@^11.4.0":
- version "11.4.0"
- resolved "https://registry.yarnpkg.com/@emotion/cache/-/cache-11.4.0.tgz#293fc9d9a7a38b9aad8e9337e5014366c3b09ac0"
- integrity sha512-Zx70bjE7LErRO9OaZrhf22Qye1y4F7iDl+ITjet0J+i+B88PrAOBkKvaAWhxsZf72tDLajwCgfCjJ2dvH77C3g==
+"@emotion/cache@^11.1.3", "@emotion/cache@^11.7.1":
+ version "11.7.1"
+ resolved "https://registry.yarnpkg.com/@emotion/cache/-/cache-11.7.1.tgz#08d080e396a42e0037848214e8aa7bf879065539"
+ integrity sha512-r65Zy4Iljb8oyjtLeCuBH8Qjiy107dOYC6SJq7g7GV5UCQWMObY4SJDPGFjiiVpPrOJ2hmJOoBiYTC7hwx9E2A==
dependencies:
"@emotion/memoize" "^0.7.4"
- "@emotion/sheet" "^1.0.0"
+ "@emotion/sheet" "^1.1.0"
"@emotion/utils" "^1.0.0"
"@emotion/weak-memoize" "^0.2.5"
- stylis "^4.0.3"
+ stylis "4.0.13"
"@emotion/core@^10.0.9", "@emotion/core@^10.1.1":
version "10.1.1"
@@ -1433,16 +1433,16 @@
resolved "https://registry.yarnpkg.com/@emotion/memoize/-/memoize-0.7.5.tgz#2c40f81449a4e554e9fc6396910ed4843ec2be50"
integrity sha512-igX9a37DR2ZPGYtV6suZ6whr8pTFtyHL3K/oLUotxpSVO2ASaprmAe2Dkq7tBo7CRY7MMDrAa9nuQP9/YG8FxQ==
-"@emotion/react@^11.4.0":
- version "11.4.0"
- resolved "https://registry.yarnpkg.com/@emotion/react/-/react-11.4.0.tgz#2465ad7b073a691409b88dfd96dc17097ddad9b7"
- integrity sha512-4XklWsl9BdtatLoJpSjusXhpKv9YVteYKh9hPKP1Sxl+mswEFoUe0WtmtWjxEjkA51DQ2QRMCNOvKcSlCQ7ivg==
+"@emotion/react@^11.9.0":
+ version "11.9.0"
+ resolved "https://registry.yarnpkg.com/@emotion/react/-/react-11.9.0.tgz#b6d42b1db3bd7511e7a7c4151dc8bc82e14593b8"
+ integrity sha512-lBVSF5d0ceKtfKCDQJveNAtkC7ayxpVlgOohLgXqRwqWr9bOf4TZAFFyIcNngnV6xK6X4x2ZeXq7vliHkoVkxQ==
dependencies:
"@babel/runtime" "^7.13.10"
- "@emotion/cache" "^11.4.0"
- "@emotion/serialize" "^1.0.2"
- "@emotion/sheet" "^1.0.1"
- "@emotion/utils" "^1.0.0"
+ "@emotion/babel-plugin" "^11.7.1"
+ "@emotion/cache" "^11.7.1"
+ "@emotion/serialize" "^1.0.3"
+ "@emotion/utils" "^1.1.0"
"@emotion/weak-memoize" "^0.2.5"
hoist-non-react-statics "^3.3.1"
@@ -1457,10 +1457,10 @@
"@emotion/utils" "0.11.3"
csstype "^2.5.7"
-"@emotion/serialize@^1.0.0", "@emotion/serialize@^1.0.2":
- version "1.0.2"
- resolved "https://registry.yarnpkg.com/@emotion/serialize/-/serialize-1.0.2.tgz#77cb21a0571c9f68eb66087754a65fa97bfcd965"
- integrity sha512-95MgNJ9+/ajxU7QIAruiOAdYNjxZX7G2mhgrtDWswA21VviYIRP1R5QilZ/bDY42xiKsaktP4egJb3QdYQZi1A==
+"@emotion/serialize@^1.0.0", "@emotion/serialize@^1.0.2", "@emotion/serialize@^1.0.3":
+ version "1.0.3"
+ resolved "https://registry.yarnpkg.com/@emotion/serialize/-/serialize-1.0.3.tgz#99e2060c26c6292469fb30db41f4690e1c8fea63"
+ integrity sha512-2mSSvgLfyV3q+iVh3YWgNlUc2a9ZlDU7DjuP5MjK3AXRR0dYigCrP99aeFtaB2L/hjfEZdSThn5dsZ0ufqbvsA==
dependencies:
"@emotion/hash" "^0.8.0"
"@emotion/memoize" "^0.7.4"
@@ -1473,11 +1473,16 @@
resolved "https://registry.yarnpkg.com/@emotion/sheet/-/sheet-0.9.4.tgz#894374bea39ec30f489bbfc3438192b9774d32e5"
integrity sha512-zM9PFmgVSqBw4zL101Q0HrBVTGmpAxFZH/pYx/cjJT5advXguvcgjHFTCaIO3enL/xr89vK2bh0Mfyj9aa0ANA==
-"@emotion/sheet@^1.0.0", "@emotion/sheet@^1.0.1":
+"@emotion/sheet@^1.0.0":
version "1.0.1"
resolved "https://registry.yarnpkg.com/@emotion/sheet/-/sheet-1.0.1.tgz#245f54abb02dfd82326e28689f34c27aa9b2a698"
integrity sha512-GbIvVMe4U+Zc+929N1V7nW6YYJtidj31lidSmdYcWozwoBIObXBnaJkKNDjZrLm9Nc0BR+ZyHNaRZxqNZbof5g==
+"@emotion/sheet@^1.1.0":
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/@emotion/sheet/-/sheet-1.1.0.tgz#56d99c41f0a1cda2726a05aa6a20afd4c63e58d2"
+ integrity sha512-u0AX4aSo25sMAygCuQTzS+HsImZFuS8llY8O7b9MDRzbJM0kVJlAz6KNDqcG7pOuQZJmj/8X/rAW+66kMnMW+g==
+
"@emotion/styled-base@^10.0.27":
version "10.0.31"
resolved "https://registry.yarnpkg.com/@emotion/styled-base/-/styled-base-10.0.31.tgz#940957ee0aa15c6974adc7d494ff19765a2f742a"
@@ -1522,10 +1527,10 @@
resolved "https://registry.yarnpkg.com/@emotion/utils/-/utils-0.11.3.tgz#a759863867befa7e583400d322652a3f44820924"
integrity sha512-0o4l6pZC+hI88+bzuaX/6BgOvQVhbt2PfmxauVaYOGgbsAw14wdKyvMCZXnsnsHys94iadcF+RG/wZyx6+ZZBw==
-"@emotion/utils@^1.0.0":
- version "1.0.0"
- resolved "https://registry.yarnpkg.com/@emotion/utils/-/utils-1.0.0.tgz#abe06a83160b10570816c913990245813a2fd6af"
- integrity sha512-mQC2b3XLDs6QCW+pDQDiyO/EdGZYOygE8s5N5rrzjSI4M3IejPE/JPndCBwRT9z982aqQNi6beWs1UeayrQxxA==
+"@emotion/utils@^1.0.0", "@emotion/utils@^1.1.0":
+ version "1.1.0"
+ resolved "https://registry.yarnpkg.com/@emotion/utils/-/utils-1.1.0.tgz#86b0b297f3f1a0f2bdb08eeac9a2f49afd40d0cf"
+ integrity sha512-iRLa/Y4Rs5H/f2nimczYmS5kFJEbpiVvgN3XVfZ022IYhuNA1IRSHEizcof88LtCTXtl9S2Cxt32KgaXEu72JQ==
"@emotion/[email protected]", "@emotion/weak-memoize@^0.2.5":
version "0.2.5"
@@ -14568,7 +14573,7 @@ [email protected]:
v8-compile-cache "^2.3.0"
write-file-atomic "^4.0.1"
[email protected], stylis@^4.0.3:
[email protected]:
version "4.0.13"
resolved "https://registry.yarnpkg.com/stylis/-/stylis-4.0.13.tgz#f5db332e376d13cc84ecfe5dace9a2a51d954c91"
integrity sha512-xGPXiFVl4YED9Jh7Euv2V220mriG9u4B2TA6Ybjc1catrstKD2PpIdU3U0RKpkVBC2EhmL/F0sPCr9vrFTNRag==
|
68398f58cdfc1872ee715b1818052587bf99b146
|
2025-01-28 01:27:43
|
anthony sottile
|
ref: remove custom view.response metric_tags (#84101)
| false
|
remove custom view.response metric_tags (#84101)
|
ref
|
diff --git a/src/sentry/middleware/stats.py b/src/sentry/middleware/stats.py
index c381983066ef16..354529df4df024 100644
--- a/src/sentry/middleware/stats.py
+++ b/src/sentry/middleware/stats.py
@@ -14,11 +14,6 @@
from . import ViewFunc, get_path, is_frontend_request
-def add_request_metric_tags(request: Request, **kwargs: Any) -> None:
- metric_tags = getattr(request, "_metric_tags", {})
- setattr(request, "_metric_tags", {**metric_tags, **kwargs})
-
-
class ResponseCodeMiddleware(MiddlewareMixin):
def process_response(self, request: Request, response: Response) -> Response:
metrics.incr("response", instance=str(response.status_code), skip_internal=False)
@@ -42,8 +37,6 @@ def process_view(
view_args: Any,
view_kwargs: Any,
) -> Response | None:
- add_request_metric_tags(request)
-
if request.method not in self.allowed_methods:
return None
@@ -70,17 +63,14 @@ def _record_time(request: Request, status_code: int) -> None:
getattr(request, "rate_limit_metadata", None), "rate_limit_type", None
)
- tags = getattr(request, "_metric_tags", {})
- tags.update(
- {
- "method": request.method,
- "status_code": status_code,
- "ui_request": is_frontend_request(request),
- "rate_limit_type": (
- getattr(rate_limit_type, "value", None) if rate_limit_type else None
- ),
- }
- )
+ tags = {
+ "method": request.method,
+ "status_code": status_code,
+ "ui_request": is_frontend_request(request),
+ "rate_limit_type": (
+ getattr(rate_limit_type, "value", None) if rate_limit_type else None
+ ),
+ }
metrics.incr("view.response", instance=view_path, tags=tags, skip_internal=False)
start_time = getattr(request, "_start_time", None)
diff --git a/src/sentry/sentry_apps/api/bases/sentryapps.py b/src/sentry/sentry_apps/api/bases/sentryapps.py
index cb2c509ed45829..fa8efd655c0263 100644
--- a/src/sentry/sentry_apps/api/bases/sentryapps.py
+++ b/src/sentry/sentry_apps/api/bases/sentryapps.py
@@ -17,7 +17,6 @@
from sentry.auth.superuser import is_active_superuser, superuser_has_permission
from sentry.coreapi import APIError
from sentry.integrations.api.bases.integration import PARANOID_GET
-from sentry.middleware.stats import add_request_metric_tags
from sentry.models.organization import OrganizationStatus
from sentry.organizations.services.organization import (
RpcUserOrganizationContext,
@@ -75,15 +74,6 @@ def ensure_scoped_permission(request: Request, allowed_scopes: Sequence[str] | N
return any(request.access.has_scope(s) for s in set(allowed_scopes))
-def add_integration_platform_metric_tag(func):
- @wraps(func)
- def wrapped(self, *args, **kwargs):
- add_request_metric_tags(self.request, integration_platform=True)
- return func(self, *args, **kwargs)
-
- return wrapped
-
-
class SentryAppsPermission(SentryPermission):
scope_map = {
"GET": PARANOID_GET,
@@ -117,10 +107,6 @@ class SentryAppsAndStaffPermission(StaffPermissionMixin, SentryAppsPermission):
class IntegrationPlatformEndpoint(Endpoint):
- def dispatch(self, request, *args, **kwargs):
- add_request_metric_tags(request, integration_platform=True)
- return super().dispatch(request, *args, **kwargs)
-
def handle_exception_with_details(self, request, exc, handler_context=None, scope=None):
return self._handle_sentry_app_exception(
exception=exc
diff --git a/src/sentry/sentry_apps/api/endpoints/organization_sentry_apps.py b/src/sentry/sentry_apps/api/endpoints/organization_sentry_apps.py
index 13d6e9017fcc7b..5b77dde34cc9fd 100644
--- a/src/sentry/sentry_apps/api/endpoints/organization_sentry_apps.py
+++ b/src/sentry/sentry_apps/api/endpoints/organization_sentry_apps.py
@@ -10,7 +10,6 @@
from sentry.constants import SentryAppStatus
from sentry.organizations.services.organization import RpcOrganization
from sentry.organizations.services.organization.model import RpcUserOrganizationContext
-from sentry.sentry_apps.api.bases.sentryapps import add_integration_platform_metric_tag
from sentry.sentry_apps.api.serializers.sentry_app import (
SentryAppSerializer as ResponseSentryAppSerializer,
)
@@ -24,7 +23,6 @@ class OrganizationSentryAppsEndpoint(ControlSiloOrganizationEndpoint):
"GET": ApiPublishStatus.UNKNOWN,
}
- @add_integration_platform_metric_tag
def get(
self,
request: Request,
diff --git a/src/sentry/sentry_apps/api/endpoints/sentry_app_components.py b/src/sentry/sentry_apps/api/endpoints/sentry_app_components.py
index e32767df4a9949..a4722b45e81ef7 100644
--- a/src/sentry/sentry_apps/api/endpoints/sentry_app_components.py
+++ b/src/sentry/sentry_apps/api/endpoints/sentry_app_components.py
@@ -13,10 +13,7 @@
RpcOrganization,
RpcUserOrganizationContext,
)
-from sentry.sentry_apps.api.bases.sentryapps import (
- SentryAppBaseEndpoint,
- add_integration_platform_metric_tag,
-)
+from sentry.sentry_apps.api.bases.sentryapps import SentryAppBaseEndpoint
from sentry.sentry_apps.api.serializers.sentry_app_component import SentryAppComponentSerializer
from sentry.sentry_apps.components import SentryAppComponentPreparer
from sentry.sentry_apps.models.sentry_app_component import SentryAppComponent
@@ -51,7 +48,6 @@ class OrganizationSentryAppComponentsEndpoint(ControlSiloOrganizationEndpoint):
"GET": ApiPublishStatus.PRIVATE,
}
- @add_integration_platform_metric_tag
def get(
self,
request: Request,
diff --git a/tests/sentry/middleware/test_stats.py b/tests/sentry/middleware/test_stats.py
index 43ee0700eb1de5..bac084f77dc0a9 100644
--- a/tests/sentry/middleware/test_stats.py
+++ b/tests/sentry/middleware/test_stats.py
@@ -6,7 +6,7 @@
from sentry.api.base import Endpoint
from sentry.middleware.ratelimit import RatelimitMiddleware
-from sentry.middleware.stats import RequestTimingMiddleware, add_request_metric_tags
+from sentry.middleware.stats import RequestTimingMiddleware
from sentry.testutils.cases import TestCase
from sentry.types.ratelimit import RateLimit, RateLimitCategory
@@ -87,50 +87,3 @@ def test_records_ui_request(self, incr):
tags={"method": "GET", "status_code": 200, "ui_request": True, "rate_limit_type": None},
skip_internal=False,
)
-
- @patch("sentry.utils.metrics.incr")
- def test_records_endpoint_specific_metrics(self, incr):
- request = self.factory.get("/")
- request._view_path = "/"
- request._metric_tags = {"a": "b"}
-
- response = Mock(status_code=200)
-
- self.middleware.process_response(request, response)
-
- incr.assert_called_with(
- "view.response",
- instance=request._view_path,
- tags={
- "method": "GET",
- "status_code": 200,
- "ui_request": False,
- "a": "b",
- "rate_limit_type": None,
- },
- skip_internal=False,
- )
-
- @patch("sentry.utils.metrics.incr")
- def test_add_request_metric_tags(self, incr):
- request = self.factory.get("/")
- request._view_path = "/"
-
- add_request_metric_tags(request, foo="bar")
-
- response = Mock(status_code=200)
-
- self.middleware.process_response(request, response)
-
- incr.assert_called_with(
- "view.response",
- instance=request._view_path,
- tags={
- "method": "GET",
- "status_code": 200,
- "ui_request": False,
- "foo": "bar",
- "rate_limit_type": None,
- },
- skip_internal=False,
- )
diff --git a/tests/sentry/sentry_apps/api/bases/test_sentryapps.py b/tests/sentry/sentry_apps/api/bases/test_sentryapps.py
index aeb444252c3d72..d0fb4310ded741 100644
--- a/tests/sentry/sentry_apps/api/bases/test_sentryapps.py
+++ b/tests/sentry/sentry_apps/api/bases/test_sentryapps.py
@@ -1,6 +1,3 @@
-import unittest
-from unittest.mock import Mock, patch
-
import pytest
from django.contrib.auth.models import AnonymousUser
from django.test.utils import override_settings
@@ -12,7 +9,6 @@
SentryAppInstallationBaseEndpoint,
SentryAppInstallationPermission,
SentryAppPermission,
- add_integration_platform_metric_tag,
)
from sentry.sentry_apps.utils.errors import SentryAppError
from sentry.testutils.cases import TestCase
@@ -244,19 +240,3 @@ def test_retrieves_installation(self):
def test_raises_when_sentry_app_not_found(self):
with pytest.raises(SentryAppError):
self.endpoint.convert_args(self.request, "1234")
-
-
-@control_silo_test
-class AddIntegrationPlatformMetricTagTest(unittest.TestCase):
- @patch("sentry.sentry_apps.api.bases.sentryapps.add_request_metric_tags")
- def test_record_platform_integration_metric(self, add_request_metric_tags):
- @add_integration_platform_metric_tag
- def get(self, request, *args, **kwargs):
- pass
-
- request = Mock()
- endpoint = Mock(request=request)
-
- get(endpoint, request)
-
- add_request_metric_tags.assert_called_with(request, integration_platform=True)
|
e0bfb657d520897d7802ad3e5a588700c3d48d72
|
2023-01-10 21:43:15
|
George Gritsouk
|
feat(perf-issues): Hook up N+1 API Calls feature flag and base option (#43000)
| false
|
Hook up N+1 API Calls feature flag and base option (#43000)
|
feat
|
diff --git a/src/sentry/utils/performance_issues/performance_detection.py b/src/sentry/utils/performance_issues/performance_detection.py
index 273e3e55950e23..72d1a060ebb05f 100644
--- a/src/sentry/utils/performance_issues/performance_detection.py
+++ b/src/sentry/utils/performance_issues/performance_detection.py
@@ -15,7 +15,7 @@
import sentry_sdk
from symbolic import ProguardMapper # type: ignore
-from sentry import nodestore, options, projectoptions
+from sentry import features, nodestore, options, projectoptions
from sentry.eventstore.models import Event
from sentry.models import Organization, Project, ProjectDebugFile, ProjectOption
from sentry.types.issues import GroupType
@@ -77,6 +77,7 @@ class DetectorType(Enum):
DETECTOR_TYPE_ISSUE_CREATION_TO_SYSTEM_OPTION = {
DetectorType.N_PLUS_ONE_DB_QUERIES: "performance.issues.n_plus_one_db.problem-creation",
DetectorType.N_PLUS_ONE_DB_QUERIES_EXTENDED: "performance.issues.n_plus_one_db_ext.problem-creation",
+ DetectorType.N_PLUS_ONE_API_CALLS: "performance.issues.n_plus_one_api_calls.problem-creation",
}
@@ -667,10 +668,12 @@ def visit_span(self, span: Span) -> None:
self.spans = [span]
def is_creation_allowed_for_organization(self, organization: Organization) -> bool:
- return False # Fully turned off
+ return features.has(
+ "organizations:performance-n-plus-one-api-calls-detector", organization, actor=None
+ )
def is_creation_allowed_for_project(self, project: Project) -> bool:
- return False # Fully turned off
+ return True # Detection always allowed by project for now
@classmethod
def is_event_eligible(cls, event):
diff --git a/tests/sentry/utils/performance_issues/test_n_plus_one_api_calls_detector.py b/tests/sentry/utils/performance_issues/test_n_plus_one_api_calls_detector.py
index c921d449dda942..a9df1ce1bc67b0 100644
--- a/tests/sentry/utils/performance_issues/test_n_plus_one_api_calls_detector.py
+++ b/tests/sentry/utils/performance_issues/test_n_plus_one_api_calls_detector.py
@@ -1,9 +1,9 @@
-import unittest
from typing import List
import pytest
from sentry.eventstore.models import Event
+from sentry.testutils import TestCase
from sentry.testutils.performance_issues.event_generators import get_event
from sentry.testutils.silo import region_silo_test
from sentry.types.issues import GroupType
@@ -17,7 +17,7 @@
@region_silo_test
@pytest.mark.django_db
-class NPlusOneAPICallsDetectorTest(unittest.TestCase):
+class NPlusOneAPICallsDetectorTest(TestCase):
def setUp(self):
super().setUp()
self.settings = get_detection_settings()
@@ -74,6 +74,17 @@ def test_does_not_detect_problem_with_concurrent_calls_to_different_urls(self):
event = get_event("n-plus-one-api-calls/not-n-plus-one-api-calls")
assert self.find_problems(event) == []
+ def test_respects_feature_flag(self):
+ project = self.create_project()
+ event = get_event("n-plus-one-api-calls/n-plus-one-api-calls-in-issue-stream")
+
+ detector = NPlusOneAPICallsDetector(self.settings, event)
+
+ assert not detector.is_creation_allowed_for_organization(project.organization)
+
+ with self.feature({"organizations:performance-n-plus-one-api-calls-detector": True}):
+ assert detector.is_creation_allowed_for_organization(project.organization)
+
@pytest.mark.parametrize(
"span",
|
05b324f332d8139b75ecd4b0304a4130d0e68868
|
2023-01-07 06:01:00
|
Snigdha Sharma
|
feat(alerts): Add a default fallback option for issue alerts (#42860)
| false
|
Add a default fallback option for issue alerts (#42860)
|
feat
|
diff --git a/src/sentry/mail/actions.py b/src/sentry/mail/actions.py
index 3b09e63ed2b0a2..f8f0099423e3c6 100644
--- a/src/sentry/mail/actions.py
+++ b/src/sentry/mail/actions.py
@@ -35,9 +35,11 @@ def __init__(self, *args, **kwargs):
self.form_fields["fallthroughType"] = {"type": "choice", "choices": FALLTHROUGH_CHOICES}
def render_label(self) -> str:
- if self.data.get("fallthroughType", None) and features.has(
+ if features.has(
"organizations:issue-alert-fallback-targeting", self.project.organization, actor=None
):
+ if "fallthroughType" not in self.data:
+ self.data["fallthroughType"] = FallthroughChoiceType.ACTIVE_MEMBERS.value
return self.label.format(**self.data)
return "Send a notification to {targetType}".format(**self.data)
@@ -57,7 +59,9 @@ def after(self, event, state):
):
fallthrough_choice = self.data.get("fallthroughType", None)
fallthrough_type = (
- FallthroughChoiceType(fallthrough_choice) if fallthrough_choice else None
+ FallthroughChoiceType(fallthrough_choice)
+ if fallthrough_choice
+ else FallthroughChoiceType.ACTIVE_MEMBERS
)
if not determine_eligible_recipients(
diff --git a/src/sentry/notifications/utils/participants.py b/src/sentry/notifications/utils/participants.py
index a49cb878b6a856..108a8e5a6a4136 100644
--- a/src/sentry/notifications/utils/participants.py
+++ b/src/sentry/notifications/utils/participants.py
@@ -292,8 +292,7 @@ def determine_eligible_recipients(
if owners:
return owners
- if fallthrough_choice:
- return get_fallthrough_recipients(project, fallthrough_choice)
+ return get_fallthrough_recipients(project, fallthrough_choice)
return set()
@@ -351,7 +350,7 @@ def get_send_to(
def get_fallthrough_recipients(
- project: Project, fallthrough_choice: FallthroughChoiceType
+ project: Project, fallthrough_choice: FallthroughChoiceType | None
) -> Iterable[APIUser]:
if not features.has(
"organizations:issue-alert-fallback-targeting",
@@ -360,6 +359,10 @@ def get_fallthrough_recipients(
):
return []
+ if not fallthrough_choice:
+ logger.warning(f"Missing fallthrough type in project: {project}")
+ return []
+
if fallthrough_choice == FallthroughChoiceType.NO_ONE:
return []
diff --git a/tests/sentry/mail/test_actions.py b/tests/sentry/mail/test_actions.py
index 143806f9beee80..e3fce2986c798f 100644
--- a/tests/sentry/mail/test_actions.py
+++ b/tests/sentry/mail/test_actions.py
@@ -205,6 +205,44 @@ def test_full_integration_fallthrough(self):
assert sent.to == [self.user.email]
assert "uh oh" in sent.subject
+ @with_feature("organizations:issue-alert-fallback-targeting")
+ def test_full_integration_fallthrough_not_provided(self):
+ one_min_ago = iso_format(before_now(minutes=1))
+ event = self.store_event(
+ data={
+ "message": "hello",
+ "exception": {"type": "Foo", "value": "uh oh"},
+ "level": "error",
+ "timestamp": one_min_ago,
+ },
+ project_id=self.project.id,
+ assert_no_errors=False,
+ )
+ action_data = {
+ "id": "sentry.mail.actions.NotifyEmailAction",
+ "targetType": "IssueOwners",
+ }
+ condition_data = {"id": "sentry.rules.conditions.first_seen_event.FirstSeenEventCondition"}
+ Rule.objects.filter(project=event.project).delete()
+ Rule.objects.create(
+ project=event.project, data={"conditions": [condition_data], "actions": [action_data]}
+ )
+
+ with self.tasks():
+ post_process_group(
+ is_new=True,
+ is_regression=False,
+ is_new_group_environment=False,
+ cache_key=write_event_to_cache(event),
+ group_id=event.group_id,
+ )
+
+ # See that the ActiveMembers default results in notifications still being sent
+ assert len(mail.outbox) == 1
+ sent = mail.outbox[0]
+ assert sent.to == [self.user.email]
+ assert "uh oh" in sent.subject
+
def test_full_integration_performance(self):
event_data = load_data(
"transaction",
@@ -310,8 +348,13 @@ def test_hack_mail_workflow(self):
@with_feature("organizations:issue-alert-fallback-targeting")
def test_render_label_fallback_none(self):
+ # Check that the label defaults to ActiveMembers
rule = self.get_rule(data={"targetType": ActionTargetType.ISSUE_OWNERS.value})
- assert rule.render_label() == "Send a notification to IssueOwners"
+ assert (
+ rule.render_label()
+ == "Send a notification to IssueOwners and if none can be found then send a notification to ActiveMembers"
+ )
+
rule = self.get_rule(
data={
"targetType": ActionTargetType.ISSUE_OWNERS.value,
diff --git a/tests/sentry/notifications/utils/test_participants.py b/tests/sentry/notifications/utils/test_participants.py
index 8f22d9afb621d4..7b055035329314 100644
--- a/tests/sentry/notifications/utils/test_participants.py
+++ b/tests/sentry/notifications/utils/test_participants.py
@@ -545,7 +545,6 @@ def test_get_owner_reason_member(self):
assert owner_reason is None
-# @apply_feature_flag_on_cls("organizations:issue-alert-fallback-targeting")
class GetSendToFallthroughTest(TestCase):
def get_send_to_fallthrough(
self,
|
5398b750cc72b968a4f2647fb538484e42080551
|
2023-05-12 02:35:08
|
Ryan Albrecht
|
fix(replays): include `project=-1` by default for /replay-count/ api calls (#48962)
| false
|
include `project=-1` by default for /replay-count/ api calls (#48962)
|
fix
|
diff --git a/static/app/components/replays/issuesReplayCountProvider.tsx b/static/app/components/replays/issuesReplayCountProvider.tsx
index 42665dc8736355..78d976d555a248 100644
--- a/static/app/components/replays/issuesReplayCountProvider.tsx
+++ b/static/app/components/replays/issuesReplayCountProvider.tsx
@@ -1,9 +1,8 @@
-import {Fragment, ReactNode, useMemo} from 'react';
+import {Fragment, ReactNode} from 'react';
import ReplayCountContext from 'sentry/components/replays/replayCountContext';
import useReplaysCount from 'sentry/components/replays/useReplaysCount';
-import GroupStore from 'sentry/stores/groupStore';
-import type {Group, Organization} from 'sentry/types';
+import type {Organization} from 'sentry/types';
import useOrganization from 'sentry/utils/useOrganization';
type Props = {
@@ -41,19 +40,9 @@ function Provider({
groupIds,
organization,
}: Props & {organization: Organization}) {
- const [groups, projectIds] = useMemo(() => {
- const pIds = new Set<number>();
- const gIds = groupIds.map(id => GroupStore.get(id) as Group).filter(Boolean);
-
- return [gIds, Array.from(pIds)];
- }, [groupIds]);
-
- const replayGroupIds = useMemo(() => groups.map(group => group.id), [groups]);
-
const counts = useReplaysCount({
- groupIds: replayGroupIds,
+ groupIds,
organization,
- projectIds,
});
return (
diff --git a/static/app/components/replays/replayIdCountProvider.tsx b/static/app/components/replays/replayIdCountProvider.tsx
index 860507d9eb196e..7d89b72d6e8e94 100644
--- a/static/app/components/replays/replayIdCountProvider.tsx
+++ b/static/app/components/replays/replayIdCountProvider.tsx
@@ -14,14 +14,11 @@ function unique<T>(arr: T[]) {
return Array.from(new Set(arr));
}
-const projectIds = [];
-
function ReplayIdCountProvider({children, organization, replayIds}: Props) {
const ids = useMemo(() => replayIds?.map(String)?.filter(Boolean) || [], [replayIds]);
const counts = useReplaysCount({
replayIds: unique(ids),
organization,
- projectIds,
});
return (
diff --git a/static/app/components/replays/useReplaysCount.spec.tsx b/static/app/components/replays/useReplaysCount.spec.tsx
index 928585da6eeb94..57f5ff33694901 100644
--- a/static/app/components/replays/useReplaysCount.spec.tsx
+++ b/static/app/components/replays/useReplaysCount.spec.tsx
@@ -26,16 +26,11 @@ describe('useReplaysCount', () => {
const organization = TestStubs.Organization({
features: ['session-replay'],
});
- const project = TestStubs.Project({
- platform: 'javascript',
- });
- const projectIds = [Number(project.id)];
it('should throw if none of groupIds, replayIds, transactionNames is provided', () => {
const {result} = reactHooks.renderHook(useReplaysCount, {
initialProps: {
organization,
- projectIds,
},
});
expect(result.error).toBeTruthy();
@@ -45,7 +40,6 @@ describe('useReplaysCount', () => {
const {result: result1} = reactHooks.renderHook(useReplaysCount, {
initialProps: {
organization,
- projectIds,
groupIds: [],
transactionNames: [],
},
@@ -55,7 +49,6 @@ describe('useReplaysCount', () => {
const {result: result2} = reactHooks.renderHook(useReplaysCount, {
initialProps: {
organization,
- projectIds,
groupIds: [],
replayIds: [],
},
@@ -65,7 +58,6 @@ describe('useReplaysCount', () => {
const {result: result3} = reactHooks.renderHook(useReplaysCount, {
initialProps: {
organization,
- projectIds,
replayIds: [],
transactionNames: [],
},
@@ -83,7 +75,6 @@ describe('useReplaysCount', () => {
const {result, waitForNextUpdate} = reactHooks.renderHook(useReplaysCount, {
initialProps: {
organization,
- projectIds,
groupIds: mockGroupIds,
},
});
@@ -95,7 +86,7 @@ describe('useReplaysCount', () => {
query: {
query: `issue.id:[${mockGroupIds.join(',')}]`,
statsPeriod: '14d',
- project: [2],
+ project: -1,
},
})
);
@@ -115,7 +106,6 @@ describe('useReplaysCount', () => {
const {result, waitForNextUpdate} = reactHooks.renderHook(useReplaysCount, {
initialProps: {
organization,
- projectIds,
groupIds: mockGroupIds,
},
});
@@ -141,7 +131,6 @@ describe('useReplaysCount', () => {
const {result, rerender, waitForNextUpdate} = reactHooks.renderHook(useReplaysCount, {
initialProps: {
organization,
- projectIds,
groupIds: mockGroupIds,
},
});
@@ -155,7 +144,7 @@ describe('useReplaysCount', () => {
query: {
query: `issue.id:[123,456]`,
statsPeriod: '14d',
- project: [2],
+ project: -1,
},
})
);
@@ -166,7 +155,6 @@ describe('useReplaysCount', () => {
rerender({
organization,
- projectIds,
groupIds: [...mockGroupIds, '789'],
});
@@ -179,7 +167,7 @@ describe('useReplaysCount', () => {
query: {
query: `issue.id:[789]`,
statsPeriod: '14d',
- project: [2],
+ project: -1,
},
})
);
@@ -200,7 +188,6 @@ describe('useReplaysCount', () => {
const {result, rerender, waitForNextUpdate} = reactHooks.renderHook(useReplaysCount, {
initialProps: {
organization,
- projectIds,
groupIds: mockGroupIds,
},
});
@@ -214,7 +201,7 @@ describe('useReplaysCount', () => {
query: {
query: `issue.id:[123,456]`,
statsPeriod: '14d',
- project: [2],
+ project: -1,
},
})
);
@@ -225,7 +212,6 @@ describe('useReplaysCount', () => {
rerender({
organization,
- projectIds,
groupIds: mockGroupIds,
});
@@ -246,7 +232,6 @@ describe('useReplaysCount', () => {
const {result, waitForNextUpdate} = reactHooks.renderHook(useReplaysCount, {
initialProps: {
organization,
- projectIds,
replayIds: mockReplayIds,
},
});
@@ -258,7 +243,7 @@ describe('useReplaysCount', () => {
query: {
query: `replay_id:[abc,def]`,
statsPeriod: '14d',
- project: [2],
+ project: -1,
},
})
);
@@ -278,7 +263,6 @@ describe('useReplaysCount', () => {
const {result, waitForNextUpdate} = reactHooks.renderHook(useReplaysCount, {
initialProps: {
organization,
- projectIds,
replayIds: mockReplayIds,
},
});
@@ -304,7 +288,6 @@ describe('useReplaysCount', () => {
const {result, waitForNextUpdate} = reactHooks.renderHook(useReplaysCount, {
initialProps: {
organization,
- projectIds,
transactionNames: mockTransactionNames,
},
});
@@ -316,7 +299,7 @@ describe('useReplaysCount', () => {
query: {
query: `transaction:["/home","/profile"]`,
statsPeriod: '14d',
- project: [2],
+ project: -1,
},
})
);
@@ -336,7 +319,6 @@ describe('useReplaysCount', () => {
const {result, waitForNextUpdate} = reactHooks.renderHook(useReplaysCount, {
initialProps: {
organization,
- projectIds,
transactionNames: mockTransactionNames,
},
});
diff --git a/static/app/components/replays/useReplaysCount.tsx b/static/app/components/replays/useReplaysCount.tsx
index 9e86d90f118658..b45e6863c26273 100644
--- a/static/app/components/replays/useReplaysCount.tsx
+++ b/static/app/components/replays/useReplaysCount.tsx
@@ -8,20 +8,13 @@ import useApi from 'sentry/utils/useApi';
type Options = {
organization: Organization;
groupIds?: string | string[];
- projectIds?: number[] | undefined;
replayIds?: string | string[];
transactionNames?: string | string[];
};
type CountState = Record<string, undefined | number>;
-function useReplaysCount({
- groupIds,
- organization,
- projectIds,
- replayIds,
- transactionNames,
-}: Options) {
+function useReplaysCount({groupIds, organization, replayIds, transactionNames}: Options) {
const api = useApi();
const [replayCounts, setReplayCounts] = useState<CountState>({});
@@ -107,7 +100,7 @@ function useReplaysCount({
query: {
query: query.conditions,
statsPeriod: '14d',
- project: projectIds,
+ project: -1,
},
}
);
@@ -115,7 +108,7 @@ function useReplaysCount({
} catch (err) {
Sentry.captureException(err);
}
- }, [api, organization.slug, query, zeroCounts, projectIds]);
+ }, [api, organization.slug, query, zeroCounts]);
useEffect(() => {
const hasSessionReplay = organization.features.includes('session-replay');
diff --git a/static/app/views/issueDetails/groupReplays/groupReplays.spec.tsx b/static/app/views/issueDetails/groupReplays/groupReplays.spec.tsx
index 3c290751a51350..a0d8dae075136c 100644
--- a/static/app/views/issueDetails/groupReplays/groupReplays.spec.tsx
+++ b/static/app/views/issueDetails/groupReplays/groupReplays.spec.tsx
@@ -107,6 +107,7 @@ describe('GroupReplays', () => {
returnIds: true,
query: `issue.id:[${mockGroup.id}]`,
statsPeriod: '14d',
+ project: -1,
},
})
);
diff --git a/static/app/views/issueDetails/groupReplays/useReplaysFromIssue.tsx b/static/app/views/issueDetails/groupReplays/useReplaysFromIssue.tsx
index ada1cf4b7e117b..40fcb8cd0eb347 100644
--- a/static/app/views/issueDetails/groupReplays/useReplaysFromIssue.tsx
+++ b/static/app/views/issueDetails/groupReplays/useReplaysFromIssue.tsx
@@ -34,6 +34,7 @@ function useReplayFromIssue({
returnIds: true,
query: `issue.id:[${group.id}]`,
statsPeriod: '14d',
+ project: -1,
},
}
);
diff --git a/static/app/views/performance/transactionSummary/header.tsx b/static/app/views/performance/transactionSummary/header.tsx
index a93f0acd1334c9..c95417243b1fac 100644
--- a/static/app/views/performance/transactionSummary/header.tsx
+++ b/static/app/views/performance/transactionSummary/header.tsx
@@ -1,4 +1,4 @@
-import {useCallback, useMemo} from 'react';
+import {useCallback} from 'react';
import styled from '@emotion/styled';
import {Location} from 'history';
@@ -107,15 +107,9 @@ function TransactionHeader({
[hasWebVitals, location, projects, eventView]
);
- const projectIds = useMemo(
- () => (project?.id ? [Number(project.id)] : []),
- [project?.id]
- );
-
const replaysCount = useReplaysCount({
transactionNames: transactionName,
organization,
- projectIds,
})[transactionName];
return (
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.