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
⌀ |
|---|---|---|---|---|---|---|---|
265fd75a34894da7fb64591512ca72c9d10850ab
|
2021-06-16 13:17:50
|
Matej Minar
|
feat(ui): Add release comparison feature flag (#26635)
| false
|
Add release comparison feature flag (#26635)
|
feat
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index dfc1a53547d1a8..933e2d7b9605ac 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -1003,6 +1003,8 @@ def create_partitioned_queues(name):
"organizations:release-adoption-stage": False,
# Store release bundles as zip files instead of single files
"organizations:release-archives": False,
+ # Enable the new release details experience
+ "organizations:release-comparison": False,
# Enable the project level transaction thresholds
"organizations:project-transaction-threshold": False,
# Enable percent displays in issue stream
diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py
index 109255713cc70a..37c4909a79328e 100644
--- a/src/sentry/features/__init__.py
+++ b/src/sentry/features/__init__.py
@@ -118,6 +118,7 @@
default_manager.add("organizations:release-adoption-chart", OrganizationFeature, True)
default_manager.add("organizations:release-adoption-stage", OrganizationFeature, True)
default_manager.add("organizations:release-archives", OrganizationFeature)
+default_manager.add("organizations:release-comparison", OrganizationFeature, True)
default_manager.add("organizations:reprocessing-v2", OrganizationFeature)
default_manager.add("organizations:required-email-verification", OrganizationFeature, True) # NOQA
default_manager.add("organizations:rule-page", OrganizationFeature)
|
1b712426c2f3924daedaf87d96df473205c28726
|
2022-02-25 00:36:12
|
Mark Story
|
chore: Remove unused feature flags (#32010)
| false
|
Remove unused feature flags (#32010)
|
chore
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index 5be8dd3a912574..eba50d480efa14 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -933,14 +933,10 @@ def create_partitioned_queues(name):
"organizations:api-keys": False,
# Enable multiple Apple app-store-connect sources per project.
"organizations:app-store-connect-multiple": False,
- # Enable explicit use of AND and OR in search.
- "organizations:boolean-search": False,
# Enable the linked event feature in the issue details breadcrumb.
"organizations:breadcrumb-linked-event": False,
# Enable change alerts for an org
"organizations:change-alerts": True,
- # Enable unfurling charts using the Chartcuterie service
- "organizations:chart-unfurls": False,
# Enable alerting based on crash free sessions/users
"organizations:crash-rate-alerts": True,
# Enable creating organizations within sentry (if SENTRY_SINGLE_ORGANIZATION
@@ -950,8 +946,6 @@ def create_partitioned_queues(name):
"organizations:discover": False,
# Enable attaching arbitrary files to events.
"organizations:event-attachments": True,
- # Enable inline preview of attachments.
- "organizations:event-attachments-viewer": True,
# Enable Filters & Sampling in the org settings
"organizations:filters-and-sampling": False,
# Enable Dynamic Sampling errors in the org settings
@@ -960,14 +954,10 @@ def create_partitioned_queues(name):
"organizations:symbol-sources": True,
# Allow organizations to configure custom external symbol sources.
"organizations:custom-symbol-sources": True,
- # Enable the events stream interface.
- "organizations:events": False,
# Enable discover 2 basic functions
"organizations:discover-basic": True,
# Enable discover 2 custom queries and saved queries
"organizations:discover-query": True,
- # Enable discover top events queries with other & higher options
- "organizations:discover-top-events": False,
# Allows an org to have a larger set of project ownership rules per project
"organizations:higher-ownership-limit": False,
# Enable Performance view
@@ -990,8 +980,6 @@ def create_partitioned_queues(name):
"organizations:custom-event-title": True,
# Enable rule page.
"organizations:rule-page": False,
- # Enable improved syntax highlighting + autocomplete on unified search
- "organizations:improved-search": False,
# Enable incidents feature
"organizations:incidents": False,
# Flags for enabling CdcEventsDatasetSnubaSearchBackend in sentry.io. No effect in open-source
@@ -1014,8 +1002,6 @@ def create_partitioned_queues(name):
"organizations:release-health-check-metrics": False,
# True if differences between the metrics and sessions backend should be reported
"organizations:release-health-check-metrics-report": False,
- # Enable metric aggregate in metric alert rule builder
- "organizations:metric-alert-builder-aggregate": False,
# Enable threshold period in metric alert rule builder
"organizations:metric-alert-threshold-period": False,
# Enable integration functionality to create and link groups to issues on
@@ -1057,8 +1043,6 @@ def create_partitioned_queues(name):
"organizations:issues-in-dashboards": False,
# Enable widget viewer modal in dashboards
"organizations:widget-viewer-modal": False,
- # Enable navigation features between Discover and Dashboards
- "organizations:connect-discover-and-dashboards": False,
# Enable experimental performance improvements.
"organizations:enterprise-perf": False,
# Enable the API to importing CODEOWNERS for a project
@@ -1101,8 +1085,6 @@ def create_partitioned_queues(name):
"organizations:native-stack-trace-v2": False,
# Enable version 2 of reprocessing (completely distinct from v1)
"organizations:reprocessing-v2": False,
- # Enable sorting+filtering by semantic version of a release
- "organizations:semver": True,
# Enable the UI for the overage alert settings
"organizations:slack-overage-notifications": False,
# Enable basic SSO functionality, providing configurable single sign on
@@ -1114,16 +1096,12 @@ def create_partitioned_queues(name):
"organizations:sso-saml2": True,
# Enable workaround for migrating IdP instances
"organizations:sso-migration": False,
- # Return unhandled information on the issue level
- "organizations:unhandled-issue-flag": True,
# Enable percent-based conditions on issue rules
"organizations:issue-percent-filters": True,
# Enable the new images loaded design and features
"organizations:images-loaded-v2": True,
# Enable the mobile screenshots feature
"organizations:mobile-screenshots": False,
- # Store release bundles as zip files instead of single files
- "organizations:release-archives": False,
# Enable the release details performance section
"organizations:release-comparison-performance": False,
# Enable percent displays in issue stream
diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py
index 7ec2bf29cb77f0..276f93a0902285 100644
--- a/src/sentry/features/__init__.py
+++ b/src/sentry/features/__init__.py
@@ -56,10 +56,7 @@
default_manager.add("organizations:alert-rule-status-page", OrganizationFeature, True)
default_manager.add("organizations:alert-wizard-v3", OrganizationFeature, True)
default_manager.add("organizations:api-keys", OrganizationFeature)
-default_manager.add("organizations:boolean-search", OrganizationFeature)
default_manager.add("organizations:breadcrumb-linked-event", OrganizationFeature, True)
-default_manager.add("organizations:chart-unfurls", OrganizationFeature, True)
-default_manager.add("organizations:connect-discover-and-dashboards", OrganizationFeature, True)
default_manager.add("organizations:crash-rate-alerts", OrganizationFeature, True)
default_manager.add("organizations:custom-event-title", OrganizationFeature)
default_manager.add("organizations:dashboard-grid-layout", OrganizationFeature, True)
@@ -67,11 +64,8 @@
default_manager.add("organizations:dashboards-template", OrganizationFeature, True)
default_manager.add("organizations:sandbox-kill-switch", OrganizationFeature, True)
default_manager.add("organizations:discover", OrganizationFeature)
-default_manager.add("organizations:discover-top-events", OrganizationFeature, True)
default_manager.add("organizations:discover-use-snql", OrganizationFeature, True)
default_manager.add("organizations:enterprise-perf", OrganizationFeature)
-default_manager.add("organizations:event-attachments-viewer", OrganizationFeature)
-default_manager.add("organizations:events", OrganizationFeature)
default_manager.add("organizations:filters-and-sampling", OrganizationFeature, True)
default_manager.add("organizations:filters-and-sampling-error-rules", OrganizationFeature, True)
default_manager.add("organizations:grouping-stacktrace-ui", OrganizationFeature, True)
@@ -79,18 +73,16 @@
default_manager.add("organizations:grouping-tree-ui", OrganizationFeature, True)
default_manager.add("organizations:higher-ownership-limit", OrganizationFeature)
default_manager.add("organizations:images-loaded-v2", OrganizationFeature)
-default_manager.add("organizations:improved-search", OrganizationFeature, True)
default_manager.add("organizations:invite-members", OrganizationFeature)
default_manager.add("organizations:invite-members-rate-limits", OrganizationFeature)
-default_manager.add("organizations:issue-list-trend-sort", OrganizationFeature, True)
default_manager.add("organizations:issue-list-removal-action", OrganizationFeature, True)
+default_manager.add("organizations:issue-list-trend-sort", OrganizationFeature, True)
default_manager.add("organizations:issue-percent-display", OrganizationFeature, True)
default_manager.add("organizations:issue-percent-filters", OrganizationFeature, True)
default_manager.add("organizations:issue-search-use-cdc-primary", OrganizationFeature, True)
default_manager.add("organizations:issue-search-use-cdc-secondary", OrganizationFeature, True)
default_manager.add("organizations:issues-in-dashboards", OrganizationFeature, True)
default_manager.add("organizations:large-debug-files", OrganizationFeature)
-default_manager.add("organizations:metric-alert-builder-aggregate", OrganizationFeature)
default_manager.add("organizations:metric-alert-threshold-period", OrganizationFeature, True)
default_manager.add("organizations:metrics", OrganizationFeature, True)
default_manager.add("organizations:new-widget-builder-experience", OrganizationFeature, True)
@@ -100,7 +92,9 @@
default_manager.add("organizations:mobile-screenshots", OrganizationFeature, True)
default_manager.add("organizations:monitors", OrganizationFeature)
default_manager.add("organizations:native-stack-trace-v2", OrganizationFeature, True)
+default_manager.add("organizations:new-weekly-report", OrganizationFeature, True)
default_manager.add("organizations:notification-all-recipients", OrganizationFeature, True)
+# Only enabled in sentry.io to enable onboarding flows.
default_manager.add("organizations:onboarding", OrganizationFeature)
default_manager.add("organizations:org-subdomains", OrganizationFeature)
default_manager.add("organizations:performance-chart-interpolation", OrganizationFeature, True)
@@ -114,7 +108,6 @@
default_manager.add("organizations:project-event-date-limit", OrganizationFeature, True)
default_manager.add("organizations:prompt-dashboards", OrganizationFeature)
default_manager.add("organizations:related-events", OrganizationFeature)
-default_manager.add("organizations:release-archives", OrganizationFeature)
default_manager.add("organizations:release-comparison-performance", OrganizationFeature, True)
default_manager.add("organizations:release-health-check-metrics", OrganizationFeature, True)
default_manager.add("organizations:release-health-check-metrics-report", OrganizationFeature, True)
@@ -122,17 +115,13 @@
default_manager.add("organizations:required-email-verification", OrganizationFeature, True) # NOQA
default_manager.add("organizations:rule-page", OrganizationFeature)
default_manager.add("organizations:selection-filters-v2", OrganizationFeature, True)
-default_manager.add("organizations:semver", OrganizationFeature, True)
default_manager.add("organizations:set-grouping-config", OrganizationFeature)
default_manager.add("organizations:slack-overage-notifications", OrganizationFeature, True)
default_manager.add("organizations:sso-migration", OrganizationFeature)
default_manager.add("organizations:symbol-sources", OrganizationFeature)
-default_manager.add("organizations:transaction-events", OrganizationFeature, True)
default_manager.add("organizations:transaction-metrics-extraction", OrganizationFeature)
-default_manager.add("organizations:unhandled-issue-flag", OrganizationFeature)
default_manager.add("organizations:unified-span-view", OrganizationFeature, True)
default_manager.add("organizations:weekly-report-debugging", OrganizationFeature, True)
-default_manager.add("organizations:new-weekly-report", OrganizationFeature, True)
default_manager.add("organizations:widget-library", OrganizationFeature, True)
default_manager.add("organizations:widget-viewer-modal", OrganizationFeature, True)
@@ -198,7 +187,6 @@
# features themselves in the manager with detections like this.
requires_snuba = (
"organizations:discover",
- "organizations:events",
"organizations:global-views",
"organizations:incidents",
"organizations:minute-resolution-sessions",
diff --git a/static/app/views/eventsV2/queryList.tsx b/static/app/views/eventsV2/queryList.tsx
index 3037272d43578d..c95e1dc867a538 100644
--- a/static/app/views/eventsV2/queryList.tsx
+++ b/static/app/views/eventsV2/queryList.tsx
@@ -338,10 +338,7 @@ class QueryList extends React.Component<Props> {
/>
)}
renderContextMenu={() => (
- <Feature
- organization={organization}
- features={['connect-discover-and-dashboards', 'dashboards-edit']}
- >
+ <Feature organization={organization} features={['dashboards-edit']}>
{({hasFeature}) => this.renderDropdownMenu(menuItems(hasFeature))}
</Feature>
)}
diff --git a/tests/js/spec/components/smartSearchBar/index.spec.jsx b/tests/js/spec/components/smartSearchBar/index.spec.jsx
index 0c00b7327f4deb..db544657def193 100644
--- a/tests/js/spec/components/smartSearchBar/index.spec.jsx
+++ b/tests/js/spec/components/smartSearchBar/index.spec.jsx
@@ -26,7 +26,7 @@ describe('SmartSearchBar', function () {
key: 'firstRelease',
name: 'firstRelease',
};
- organization = TestStubs.Organization({id: '123', features: ['improved-search']});
+ organization = TestStubs.Organization({id: '123'});
location = {
pathname: '/organizations/org-slug/recent-searches/',
diff --git a/tests/js/spec/views/eventsV2/queryList.spec.jsx b/tests/js/spec/views/eventsV2/queryList.spec.jsx
index c604b3de8e3210..9061c12a33e865 100644
--- a/tests/js/spec/views/eventsV2/queryList.spec.jsx
+++ b/tests/js/spec/views/eventsV2/queryList.spec.jsx
@@ -204,9 +204,10 @@ describe('EventsV2 > QueryList', function () {
card = wrapper.find('QueryCard').last();
const menuItems = card.find('MenuItemWrap');
- expect(menuItems.length).toEqual(2);
- expect(menuItems.at(0).text()).toEqual('Duplicate Query');
- expect(menuItems.at(1).text()).toEqual('Delete Query');
+ expect(menuItems.length).toEqual(3);
+ expect(menuItems.at(0).text()).toEqual('Add to Dashboard');
+ expect(menuItems.at(1).text()).toEqual('Duplicate Query');
+ expect(menuItems.at(2).text()).toEqual('Delete Query');
});
it('only renders Delete Query and Duplicate Query in context menu', async function () {
diff --git a/tests/sentry/api/serializers/test_organization.py b/tests/sentry/api/serializers/test_organization.py
index c2db2b6f7b0ee6..d4ed38f4e87cfe 100644
--- a/tests/sentry/api/serializers/test_organization.py
+++ b/tests/sentry/api/serializers/test_organization.py
@@ -37,7 +37,6 @@ def test_simple(self):
"discover-basic",
"discover-query",
"event-attachments",
- "event-attachments-viewer",
"images-loaded-v2",
"integrations-alert-rule",
"integrations-chat-unfurl",
@@ -52,13 +51,11 @@ def test_simple(self):
"minute-resolution-sessions",
"open-membership",
"relay",
- "semver",
"shared-issues",
"sso-basic",
"sso-saml2",
"symbol-sources",
"team-insights",
- "unhandled-issue-flag",
}
@mock.patch("sentry.features.batch_has")
|
e4c3d14395ad9cf10b403f2fe15555b9116e869d
|
2021-08-26 16:47:50
|
Priscila Oliveira
|
feat(debug-files): Allow multiple app store connect repos (#28170)
| false
|
Allow multiple app store connect repos (#28170)
|
feat
|
diff --git a/static/app/stores/hookStore.tsx b/static/app/stores/hookStore.tsx
index b747947e7ac8ea..6f4e7cda8f9c02 100644
--- a/static/app/stores/hookStore.tsx
+++ b/static/app/stores/hookStore.tsx
@@ -17,6 +17,7 @@ const validHookNames = new Set<HookName>([
'analytics:log-experiment',
'component:disabled-member',
'component:disabled-member-tooltip',
+ 'component:disabled-app-store-connect-item',
'component:header-date-range',
'component:header-selector-items',
'component:global-notifications',
diff --git a/static/app/types/hooks.tsx b/static/app/types/hooks.tsx
index ec670feb3679cd..ebeb51285921e7 100644
--- a/static/app/types/hooks.tsx
+++ b/static/app/types/hooks.tsx
@@ -63,6 +63,11 @@ type MemberListHeaderProps = {
members: Member[];
organization: Organization;
};
+type DisabledAppStoreConnectItem = {
+ disabled: boolean;
+ onTrialStarted: () => void;
+ children: React.ReactElement;
+};
type DisabledMemberTooltipProps = {children: React.ReactNode};
type DashboardHeadersProps = {organization: Organization};
@@ -76,6 +81,7 @@ export type ComponentHooks = {
'component:disabled-member': () => React.ComponentType<DisabledMemberViewProps>;
'component:member-list-header': () => React.ComponentType<MemberListHeaderProps>;
'component:disabled-member-tooltip': () => React.ComponentType<DisabledMemberTooltipProps>;
+ 'component:disabled-app-store-connect-item': () => React.ComponentType<DisabledAppStoreConnectItem>;
'component:dashboards-header': () => React.ComponentType<DashboardHeadersProps>;
};
diff --git a/static/app/views/settings/projectDebugFiles/externalSources/customRepositories/index.tsx b/static/app/views/settings/projectDebugFiles/externalSources/customRepositories/index.tsx
index 343c6103a5b8ce..1743cbfb7fb976 100644
--- a/static/app/views/settings/projectDebugFiles/externalSources/customRepositories/index.tsx
+++ b/static/app/views/settings/projectDebugFiles/externalSources/customRepositories/index.tsx
@@ -1,4 +1,4 @@
-import {useContext, useEffect} from 'react';
+import {Fragment, useContext, useEffect} from 'react';
import {InjectedRouter} from 'react-router';
import styled from '@emotion/styled';
import {Location} from 'history';
@@ -10,6 +10,7 @@ import {Client} from 'app/api';
import DropdownAutoComplete from 'app/components/dropdownAutoComplete';
import DropdownButton from 'app/components/dropdownButton';
import EmptyStateWarning from 'app/components/emptyStateWarning';
+import HookOrDefault from 'app/components/hookOrDefault';
import MenuItem from 'app/components/menuItem';
import {Panel, PanelBody, PanelHeader} from 'app/components/panels';
import AppStoreConnectContext from 'app/components/projects/appStoreConnectContext';
@@ -26,6 +27,11 @@ import {
getRequestMessages,
} from './utils';
+const HookedAppStoreConnectItem = HookOrDefault({
+ hookName: 'component:disabled-app-store-connect-item',
+ defaultComponent: ({children}) => <Fragment>{children}</Fragment>,
+});
+
type Props = {
api: Client;
organization: Organization;
@@ -49,16 +55,23 @@ function CustomRepositories({
openDebugFileSourceDialog();
}, [location.query, appStoreConnectContext]);
- const hasAppConnectStoreFeatureFlag =
+ const hasAppStoreConnectFeatureFlag =
!!organization.features?.includes('app-store-connect');
+ const hasAppStoreConnectMultipleFeatureFlag = !!organization.features?.includes(
+ 'app-store-connect-multiple'
+ );
+
+ const hasAppStoreConnectRepo = !!repositories.find(
+ repository => repository.type === CustomRepoType.APP_STORE_CONNECT
+ );
+
if (
- hasAppConnectStoreFeatureFlag &&
+ hasAppStoreConnectFeatureFlag &&
!appStoreConnectContext &&
!dropDownItems.find(
dropDownItem => dropDownItem.value === CustomRepoType.APP_STORE_CONNECT
- ) &&
- !repositories.find(repository => repository.type === CustomRepoType.APP_STORE_CONNECT)
+ )
) {
dropDownItems.push({
value: CustomRepoType.APP_STORE_CONNECT,
@@ -189,19 +202,34 @@ function CustomRepositories({
{t('Custom Repositories')}
<DropdownAutoComplete
alignMenu="right"
- items={dropDownItems.map(dropDownItem => ({
- ...dropDownItem,
- label: (
- <StyledMenuItem
- onClick={event => {
- event.preventDefault();
- handleAddRepository(dropDownItem.value);
- }}
- >
- {dropDownItem.label}
- </StyledMenuItem>
- ),
- }))}
+ items={dropDownItems.map(dropDownItem => {
+ const disabled =
+ dropDownItem.value === CustomRepoType.APP_STORE_CONNECT &&
+ hasAppStoreConnectRepo &&
+ !hasAppStoreConnectMultipleFeatureFlag;
+
+ return {
+ ...dropDownItem,
+ label: (
+ <HookedAppStoreConnectItem
+ disabled={disabled}
+ onTrialStarted={() => {
+ handleAddRepository(dropDownItem.value);
+ }}
+ >
+ <StyledMenuItem
+ onClick={event => {
+ event.preventDefault();
+ handleAddRepository(dropDownItem.value);
+ }}
+ disabled={disabled}
+ >
+ {dropDownItem.label}
+ </StyledMenuItem>
+ </HookedAppStoreConnectItem>
+ ),
+ };
+ })}
>
{({isOpen}) => (
<DropdownButton isOpen={isOpen} size="small">
|
30ef9dee0596cd665e1d5cf7b582611cfd33daed
|
2023-09-13 22:50:37
|
Seiji Chew
|
feat(slug): Prevent numeric sentry-doc integration slugs (#56057)
| false
|
Prevent numeric sentry-doc integration slugs (#56057)
|
feat
|
diff --git a/src/sentry/api/endpoints/integrations/doc_integrations/index.py b/src/sentry/api/endpoints/integrations/doc_integrations/index.py
index faec4bdc874f05..3695b3788979d7 100644
--- a/src/sentry/api/endpoints/integrations/doc_integrations/index.py
+++ b/src/sentry/api/endpoints/integrations/doc_integrations/index.py
@@ -40,12 +40,13 @@ def post(self, request: Request):
data = request.json_body
data["is_draft"] = True
data["metadata"] = self.generate_incoming_metadata(request)
-
serializer = DocIntegrationSerializer(data=data)
- if serializer.is_valid():
- doc_integration = serializer.save()
- return Response(
- serialize(doc_integration, request.user),
- status=status.HTTP_201_CREATED,
- )
- return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
+
+ if not serializer.is_valid():
+ return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
+
+ doc_integration = serializer.save()
+ return Response(
+ serialize(doc_integration, request.user),
+ status=status.HTTP_201_CREATED,
+ )
diff --git a/src/sentry/api/serializers/rest_framework/doc_integration.py b/src/sentry/api/serializers/rest_framework/doc_integration.py
index b0ce3de4333250..92ce240872f006 100644
--- a/src/sentry/api/serializers/rest_framework/doc_integration.py
+++ b/src/sentry/api/serializers/rest_framework/doc_integration.py
@@ -1,3 +1,5 @@
+import random
+import string
from typing import Any, MutableMapping
from django.db import router, transaction
@@ -6,6 +8,7 @@
from rest_framework import serializers
from rest_framework.serializers import Serializer, ValidationError
+from sentry import options
from sentry.api.fields.avatar import AvatarField
from sentry.api.serializers.rest_framework.sentry_app import URLField
from sentry.api.validators.doc_integration import validate_metadata_schema
@@ -59,6 +62,12 @@ def validate_name(self, value: str) -> str:
def create(self, validated_data: MutableMapping[str, Any]) -> DocIntegration:
slug = self._generate_slug(validated_data["name"])
+
+ # If option is set, add random 3 lowercase letter suffix to prevent numeric slug
+ # eg: 123 -> 123-abc
+ if options.get("api.prevent-numeric-slugs") and slug.isdecimal():
+ slug = f"{slug}-{''.join(random.choice(string.ascii_lowercase) for _ in range(3))}"
+
features = validated_data.pop("features") if validated_data.get("features") else []
with transaction.atomic(router.db_for_write(DocIntegration)):
doc_integration = DocIntegration.objects.create(slug=slug, **validated_data)
diff --git a/tests/sentry/api/endpoints/test_doc_integrations.py b/tests/sentry/api/endpoints/test_doc_integrations.py
index c882cafaab6f10..d7ddfb7b110598 100644
--- a/tests/sentry/api/endpoints/test_doc_integrations.py
+++ b/tests/sentry/api/endpoints/test_doc_integrations.py
@@ -9,6 +9,7 @@
from sentry.models import DocIntegration, IntegrationFeature
from sentry.models.integrations.integration_feature import IntegrationTypes
from sentry.testutils.cases import APITestCase
+from sentry.testutils.helpers.options import override_options
from sentry.testutils.silo import control_silo_test
from sentry.utils.json import JSONData
@@ -130,6 +131,19 @@ def test_create_repeated_slug(self):
response = self.get_error_response(status_code=status.HTTP_400_BAD_REQUEST, **payload)
assert "name" in response.data.keys()
+ @override_options({"api.prevent-numeric-slugs": True})
+ def test_generated_slug_not_entirely_numeric(self):
+ """
+ Tests that generated slug based on name is not entirely numeric
+ """
+ self.login_as(user=self.superuser, superuser=True)
+ payload = {**self.payload, "name": "1234"}
+ response = self.get_success_response(status_code=status.HTTP_201_CREATED, **payload)
+
+ slug = response.data["slug"]
+ assert slug.startswith("1234-")
+ assert not slug.isdecimal()
+
def test_create_invalid_metadata(self):
"""
Tests that incorrectly structured metadata throws an error
|
57b69e7ef11bf649939c0a3e96000be02e71c992
|
2022-08-29 12:10:51
|
Priscila Oliveira
|
ref(data-scrubbing): Convert a couple of tests to rtl (#38083)
| false
|
Convert a couple of tests to rtl (#38083)
|
ref
|
diff --git a/static/app/views/settings/components/dataScrubbing/rules.tsx b/static/app/views/settings/components/dataScrubbing/rules.tsx
index 412b9bb0cfb325..3057d99aac38e0 100644
--- a/static/app/views/settings/components/dataScrubbing/rules.tsx
+++ b/static/app/views/settings/components/dataScrubbing/rules.tsx
@@ -32,7 +32,7 @@ const getListItemDescription = (rule: Rule) => {
);
if (rule.method === MethodType.REPLACE && rule.placeholder) {
- descriptionDetails.push(` with [${rule.placeholder}]`);
+ descriptionDetails.push(`with [${rule.placeholder}]`);
}
return `${descriptionDetails.join(' ')} ${t('from')} [${source}]`;
diff --git a/tests/js/spec/views/settings/components/dataScrubbing/content.spec.tsx b/tests/js/spec/views/settings/components/dataScrubbing/content.spec.tsx
index d5cf25f787c02c..0929a2a669a633 100644
--- a/tests/js/spec/views/settings/components/dataScrubbing/content.spec.tsx
+++ b/tests/js/spec/views/settings/components/dataScrubbing/content.spec.tsx
@@ -1,31 +1,26 @@
-import {mountWithTheme} from 'sentry-test/enzyme';
+import {render, screen} from 'sentry-test/reactTestingLibrary';
import Content from 'sentry/views/settings/components/dataScrubbing/content';
import convertRelayPiiConfig from 'sentry/views/settings/components/dataScrubbing/convertRelayPiiConfig';
-const relayPiiConfig = TestStubs.DataScrubbingRelayPiiConfig();
-const stringRelayPiiConfig = JSON.stringify(relayPiiConfig);
-const convertedRules = convertRelayPiiConfig(stringRelayPiiConfig);
+describe('Content', function () {
+ it('default empty', function () {
+ render(<Content rules={[]} onEditRule={jest.fn()} onDeleteRule={jest.fn()} />);
-const handleEditRule = jest.fn();
-const handleDelete = jest.fn();
-
-describe('Content', () => {
- it('default render - empty', () => {
- const wrapper = mountWithTheme(
- <Content rules={[]} onEditRule={handleEditRule} onDeleteRule={handleDelete} />
- );
- expect(wrapper.text()).toEqual('You have no data scrubbing rules');
+ expect(screen.getByText('You have no data scrubbing rules')).toBeInTheDocument();
});
- it('render rules', () => {
- const wrapper = mountWithTheme(
+ it('render rules', function () {
+ render(
<Content
- rules={convertedRules}
- onEditRule={handleEditRule}
- onDeleteRule={handleDelete}
+ rules={convertRelayPiiConfig(
+ JSON.stringify(TestStubs.DataScrubbingRelayPiiConfig())
+ )}
+ onEditRule={jest.fn()}
+ onDeleteRule={jest.fn()}
/>
);
- expect(wrapper.find('List')).toHaveLength(1);
+
+ expect(screen.getAllByRole('button', {name: 'Edit Rule'})).toHaveLength(3);
});
});
diff --git a/tests/js/spec/views/settings/components/dataScrubbing/dataScrubbing.spec.tsx b/tests/js/spec/views/settings/components/dataScrubbing/dataScrubbing.spec.tsx
deleted file mode 100644
index 43a673a687bebe..00000000000000
--- a/tests/js/spec/views/settings/components/dataScrubbing/dataScrubbing.spec.tsx
+++ /dev/null
@@ -1,244 +0,0 @@
-import {mountWithTheme} from 'sentry-test/enzyme';
-import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
-
-import {openModal} from 'sentry/actionCreators/modal';
-import DataScrubbing from 'sentry/views/settings/components/dataScrubbing';
-import {ProjectId} from 'sentry/views/settings/components/dataScrubbing/types';
-
-jest.mock('sentry/actionCreators/modal');
-
-const relayPiiConfig = TestStubs.DataScrubbingRelayPiiConfig();
-const stringRelayPiiConfig = JSON.stringify(relayPiiConfig);
-const organizationSlug = 'sentry';
-const handleUpdateOrganization = jest.fn();
-const additionalContext = 'These rules can be configured for each project.';
-
-jest.mock('sentry/actionCreators/indicator');
-
-function getOrganization(piiConfig?: string) {
- return TestStubs.Organization(
- piiConfig ? {id: '123', relayPiiConfig: piiConfig} : {id: '123'}
- );
-}
-
-function renderComponent({
- disabled,
- projectId,
- endpoint,
- ...props
-}: Partial<Omit<DataScrubbing<ProjectId>['props'], 'endpoint'>> &
- Pick<DataScrubbing<ProjectId>['props'], 'endpoint'>) {
- const organization = props.organization ?? getOrganization();
- if (projectId) {
- return mountWithTheme(
- <DataScrubbing
- additionalContext={additionalContext}
- endpoint={endpoint}
- projectId={projectId}
- relayPiiConfig={stringRelayPiiConfig}
- disabled={disabled}
- organization={organization}
- onSubmitSuccess={handleUpdateOrganization}
- />
- );
- }
-
- return mountWithTheme(
- <DataScrubbing
- additionalContext={additionalContext}
- endpoint={endpoint}
- relayPiiConfig={stringRelayPiiConfig}
- disabled={disabled}
- organization={organization}
- onSubmitSuccess={handleUpdateOrganization}
- />
- );
-}
-
-describe('Data Scrubbing', () => {
- describe('Organization level', () => {
- const endpoint = `organization/${organizationSlug}/`;
-
- it('default render', () => {
- const wrapper = renderComponent({disabled: false, endpoint});
-
- // PanelHeader
- expect(wrapper.find('PanelHeader').text()).toEqual('Advanced Data Scrubbing');
-
- // PanelAlert
- const panelAlert = wrapper.find('PanelAlert');
- expect(panelAlert.text()).toEqual(
- `${additionalContext} The new rules will only apply to upcoming events. For more details, see full documentation on data scrubbing.`
- );
-
- const readDocsLink = panelAlert.find('a');
- expect(readDocsLink.text()).toEqual('full documentation on data scrubbing');
- expect(readDocsLink.prop('href')).toEqual(
- 'https://docs.sentry.io/product/data-management-settings/scrubbing/advanced-datascrubbing/'
- );
-
- // PanelBody
- const panelBody = wrapper.find('PanelBody');
- expect(panelBody).toHaveLength(1);
- expect(panelBody.find('ListItem')).toHaveLength(3);
-
- // OrganizationRules
- const organizationRules = panelBody.find('OrganizationRules');
- expect(organizationRules).toHaveLength(0);
-
- // PanelAction
- const actionButtons = wrapper.find('PanelAction').find('Button');
- expect(actionButtons).toHaveLength(2);
- expect(actionButtons.at(0).text()).toEqual('Read Docs');
- expect(actionButtons.at(1).text()).toEqual('Add Rule');
- expect(actionButtons.at(1).prop('disabled')).toEqual(false);
- });
-
- it('render disabled', () => {
- const wrapper = renderComponent({disabled: true, endpoint});
-
- // PanelBody
- const panelBody = wrapper.find('PanelBody');
- expect(panelBody).toHaveLength(1);
- expect(panelBody.find('List').prop('isDisabled')).toEqual(true);
-
- // PanelAction
- const actionButtons = wrapper.find('PanelAction').find('StyledButton');
- expect(actionButtons).toHaveLength(2);
- expect(actionButtons.at(0).prop('disabled')).toEqual(false);
- expect(actionButtons.at(1).prop('disabled')).toEqual(true);
- });
- });
-
- describe('Project level', () => {
- const projectId = 'foo';
- const endpoint = `/projects/${organizationSlug}/${projectId}/`;
-
- it('default render', () => {
- const wrapper = renderComponent({
- disabled: false,
- projectId,
- endpoint,
- });
-
- // PanelHeader
- expect(wrapper.find('PanelHeader').text()).toEqual('Advanced Data Scrubbing');
-
- // PanelAlert
- const panelAlert = wrapper.find('PanelAlert');
- expect(panelAlert.text()).toEqual(
- `${additionalContext} The new rules will only apply to upcoming events. For more details, see full documentation on data scrubbing.`
- );
-
- const readDocsLink = panelAlert.find('a');
- expect(readDocsLink.text()).toEqual('full documentation on data scrubbing');
- expect(readDocsLink.prop('href')).toEqual(
- 'https://docs.sentry.io/product/data-management-settings/scrubbing/advanced-datascrubbing/'
- );
-
- // PanelBody
- const panelBody = wrapper.find('PanelBody');
- expect(panelBody).toHaveLength(1);
- expect(panelBody.find('ListItem')).toHaveLength(3);
-
- // OrganizationRules
- const organizationRules = panelBody.find('OrganizationRules');
- expect(organizationRules).toHaveLength(1);
- expect(organizationRules.text()).toEqual(
- 'There are no data scrubbing rules at the organization level'
- );
-
- // PanelAction
- const actionButtons = wrapper.find('PanelAction').find('Button');
- expect(actionButtons).toHaveLength(2);
- expect(actionButtons.at(0).text()).toEqual('Read Docs');
- expect(actionButtons.at(1).text()).toEqual('Add Rule');
- expect(actionButtons.at(1).prop('disabled')).toEqual(false);
- });
-
- it('render disabled', () => {
- const wrapper = renderComponent({disabled: true, endpoint});
-
- // PanelBody
- const panelBody = wrapper.find('PanelBody');
- expect(panelBody).toHaveLength(1);
- expect(panelBody.find('List').prop('isDisabled')).toEqual(true);
-
- // PanelAction
- const actionButtons = wrapper.find('PanelAction').find('StyledButton');
- expect(actionButtons).toHaveLength(2);
- expect(actionButtons.at(0).prop('disabled')).toEqual(false);
- expect(actionButtons.at(1).prop('disabled')).toEqual(true);
- });
-
- it('OrganizationRules has content', () => {
- const wrapper = renderComponent({
- disabled: false,
- organization: getOrganization(stringRelayPiiConfig),
- projectId,
- endpoint,
- });
-
- // OrganizationRules
- const organizationRules = wrapper.find('OrganizationRules');
- expect(organizationRules).toHaveLength(1);
- expect(organizationRules.find('Header').text()).toEqual('Organization Rules');
- const listItems = organizationRules.find('ListItem');
- expect(listItems).toHaveLength(3);
- expect(listItems.at(0).find('[role="button"]')).toHaveLength(0);
- });
-
- it('Delete rule successfully', () => {
- // TODO(test): Improve this test by checking if the confirmation dialog is opened
- render(
- <DataScrubbing
- additionalContext={additionalContext}
- endpoint={endpoint}
- projectId={projectId}
- relayPiiConfig={stringRelayPiiConfig}
- disabled={false}
- organization={getOrganization()}
- onSubmitSuccess={handleUpdateOrganization}
- />
- );
-
- userEvent.click(screen.getAllByLabelText('Delete Rule')[0]);
-
- expect(openModal).toHaveBeenCalled();
- });
-
- it('Open Add Rule Modal', () => {
- const wrapper = renderComponent({
- disabled: false,
- projectId,
- endpoint,
- });
-
- const addbutton = wrapper
- .find('PanelAction')
- .find('[aria-label="Add Rule"]')
- .hostNodes();
-
- addbutton.simulate('click');
-
- expect(openModal).toHaveBeenCalled();
- });
-
- it('Open Edit Rule Modal', () => {
- const wrapper = renderComponent({
- disabled: false,
- projectId,
- endpoint,
- });
-
- const editButton = wrapper
- .find('PanelBody')
- .find('[aria-label="Edit Rule"]')
- .hostNodes();
-
- editButton.at(0).simulate('click');
-
- expect(openModal).toHaveBeenCalled();
- });
- });
-});
diff --git a/tests/js/spec/views/settings/components/dataScrubbing/index.spec.tsx b/tests/js/spec/views/settings/components/dataScrubbing/index.spec.tsx
new file mode 100644
index 00000000000000..9d63a76f26662a
--- /dev/null
+++ b/tests/js/spec/views/settings/components/dataScrubbing/index.spec.tsx
@@ -0,0 +1,192 @@
+import {Fragment} from 'react';
+
+import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
+import {textWithMarkupMatcher} from 'sentry-test/utils';
+
+import GlobalModal from 'sentry/components/globalModal';
+import DataScrubbing from 'sentry/views/settings/components/dataScrubbing';
+
+const relayPiiConfig = JSON.stringify(TestStubs.DataScrubbingRelayPiiConfig());
+
+describe('Data Scrubbing', function () {
+ describe('Organization level', function () {
+ const organization = TestStubs.Organization();
+ const additionalContext = 'These rules can be configured for each project.';
+
+ it('default render', function () {
+ render(
+ <DataScrubbing
+ additionalContext={additionalContext}
+ endpoint={`organization/${organization.slug}/`}
+ relayPiiConfig={relayPiiConfig}
+ organization={organization}
+ onSubmitSuccess={jest.fn()}
+ />
+ );
+
+ // Header
+ expect(screen.getByText('Advanced Data Scrubbing')).toBeInTheDocument();
+
+ // Alert
+ expect(
+ screen.getByText(
+ textWithMarkupMatcher(
+ `${additionalContext} The new rules will only apply to upcoming events. For more details, see full documentation on data scrubbing.`
+ )
+ )
+ ).toBeInTheDocument();
+
+ expect(
+ screen.getByRole('link', {name: 'full documentation on data scrubbing'})
+ ).toHaveAttribute(
+ 'href',
+ `https://docs.sentry.io/product/data-management-settings/scrubbing/advanced-datascrubbing/`
+ );
+
+ // Body
+ expect(screen.getAllByRole('button', {name: 'Edit Rule'})).toHaveLength(3);
+
+ // Actions
+ expect(screen.getByRole('button', {name: 'Read Docs'})).toHaveAttribute(
+ 'href',
+ `https://docs.sentry.io/product/data-management-settings/scrubbing/advanced-datascrubbing/`
+ );
+ expect(screen.getByRole('button', {name: 'Add Rule'})).toBeEnabled();
+ });
+
+ it('render disabled actions', function () {
+ render(
+ <DataScrubbing
+ additionalContext={additionalContext}
+ endpoint={`organization/${organization.slug}/`}
+ relayPiiConfig={relayPiiConfig}
+ organization={organization}
+ onSubmitSuccess={jest.fn()}
+ disabled
+ />
+ );
+
+ // Read Docs is the only enabled action
+ expect(screen.getByRole('button', {name: 'Read Docs'})).toBeEnabled();
+
+ expect(screen.getByRole('button', {name: 'Add Rule'})).toBeDisabled();
+
+ for (const index in JSON.parse(relayPiiConfig).rules) {
+ expect(screen.getAllByRole('button', {name: 'Edit Rule'})[index]).toBeDisabled();
+ expect(
+ screen.getAllByRole('button', {name: 'Delete Rule'})[index]
+ ).toBeDisabled();
+ }
+ });
+ });
+
+ describe('Project level', function () {
+ it('default render', function () {
+ const organization = TestStubs.Organization();
+
+ render(
+ <DataScrubbing
+ endpoint={`/projects/${organization.slug}/foo/`}
+ relayPiiConfig={relayPiiConfig}
+ organization={organization}
+ onSubmitSuccess={jest.fn()}
+ projectId="foo"
+ />
+ );
+
+ // Header
+ expect(
+ screen.getByText('There are no data scrubbing rules at the organization level')
+ ).toBeInTheDocument();
+ });
+
+ it('OrganizationRules has content', function () {
+ const organization = TestStubs.Organization({relayPiiConfig});
+
+ render(
+ <DataScrubbing
+ endpoint={`/projects/${organization.slug}/foo/`}
+ relayPiiConfig={relayPiiConfig}
+ organization={organization}
+ onSubmitSuccess={jest.fn()}
+ projectId="foo"
+ />
+ );
+
+ // Organization Rules
+ expect(screen.getByText('Organization Rules')).toBeInTheDocument();
+ });
+
+ it('Delete rule successfully', async function () {
+ const organization = TestStubs.Organization();
+
+ render(
+ <Fragment>
+ <GlobalModal />
+ <DataScrubbing
+ endpoint={`/projects/${organization.slug}/foo/`}
+ projectId="foo"
+ relayPiiConfig={relayPiiConfig}
+ disabled={false}
+ organization={organization}
+ onSubmitSuccess={jest.fn()}
+ />
+ </Fragment>
+ );
+
+ userEvent.click(screen.getAllByLabelText('Delete Rule')[0]);
+
+ expect(
+ await screen.findByText('Are you sure you wish to delete this rule?')
+ ).toBeInTheDocument();
+ });
+
+ it('Open Add Rule Modal', async function () {
+ const organization = TestStubs.Organization();
+
+ render(
+ <Fragment>
+ <GlobalModal />
+ <DataScrubbing
+ endpoint={`/projects/${organization.slug}/foo/`}
+ projectId="foo"
+ relayPiiConfig={relayPiiConfig}
+ disabled={false}
+ organization={organization}
+ onSubmitSuccess={jest.fn()}
+ />
+ </Fragment>
+ );
+
+ userEvent.click(screen.getByRole('button', {name: 'Add Rule'}));
+
+ expect(
+ await screen.findByText('Add an advanced data scrubbing rule')
+ ).toBeInTheDocument();
+ });
+
+ it('Open Edit Rule Modal', async function () {
+ const organization = TestStubs.Organization();
+
+ render(
+ <Fragment>
+ <GlobalModal />
+ <DataScrubbing
+ endpoint={`/projects/${organization.slug}/foo/`}
+ projectId="foo"
+ relayPiiConfig={relayPiiConfig}
+ disabled={false}
+ organization={organization}
+ onSubmitSuccess={jest.fn()}
+ />
+ </Fragment>
+ );
+
+ userEvent.click(screen.getAllByRole('button', {name: 'Edit Rule'})[0]);
+
+ expect(
+ await screen.findByText('Edit an advanced data scrubbing rule')
+ ).toBeInTheDocument();
+ });
+ });
+});
diff --git a/tests/js/spec/views/settings/components/dataScrubbing/rules.spec.tsx b/tests/js/spec/views/settings/components/dataScrubbing/rules.spec.tsx
index 4116eff1bbdb1e..3260ef11874b89 100644
--- a/tests/js/spec/views/settings/components/dataScrubbing/rules.spec.tsx
+++ b/tests/js/spec/views/settings/components/dataScrubbing/rules.spec.tsx
@@ -1,74 +1,53 @@
-import {mountWithTheme} from 'sentry-test/enzyme';
+import {render, screen} from 'sentry-test/reactTestingLibrary';
+import {textWithMarkupMatcher} from 'sentry-test/utils';
import convertRelayPiiConfig from 'sentry/views/settings/components/dataScrubbing/convertRelayPiiConfig';
import Rules from 'sentry/views/settings/components/dataScrubbing/rules';
-const relayPiiConfig = TestStubs.DataScrubbingRelayPiiConfig();
-const stringRelayPiiConfig = JSON.stringify(relayPiiConfig);
-const convertedRules = convertRelayPiiConfig(stringRelayPiiConfig);
-const rules = convertedRules;
-const handleShowEditRule = jest.fn();
-const handleDelete = jest.fn();
+const relayPiiConfig = convertRelayPiiConfig(
+ JSON.stringify(TestStubs.DataScrubbingRelayPiiConfig())
+);
-describe('Rules', () => {
- it('default render', () => {
- const wrapper = mountWithTheme(<Rules rules={rules} />);
- expect(wrapper.find('ListItem')).toHaveLength(3);
- });
+describe('Rules', function () {
+ it('default render', function () {
+ render(<Rules rules={relayPiiConfig} onEditRule={jest.fn()} />);
- it('render correct description', () => {
- const wrapper = mountWithTheme(<Rules rules={rules} />);
- const listItems = wrapper.find('ListItem');
- expect(listItems.at(1).text()).toEqual(
- '[Mask] [Credit card numbers] from [$message]'
- );
- expect(listItems.at(0).text()).toEqual(
- '[Replace] [Password fields] with [Scrubbed] from [password]'
- );
- });
+ expect(screen.getAllByRole('button', {name: 'Edit Rule'})).toHaveLength(3);
- it('render disabled list', () => {
- const wrapper = mountWithTheme(<Rules rules={rules} disabled />);
- expect(wrapper.find('List').prop('isDisabled')).toEqual(true);
- });
-
- it('render edit and delete buttons', () => {
- const wrapper = mountWithTheme(
- <Rules rules={rules} onEditRule={handleShowEditRule} onDeleteRule={handleDelete} />
- );
- expect(wrapper.find('[aria-label="Edit Rule"]').hostNodes()).toHaveLength(3);
- expect(wrapper.find('[aria-label="Delete Rule"]').hostNodes()).toHaveLength(3);
- });
+ expect(
+ screen.getByText(
+ textWithMarkupMatcher(
+ '[Replace] [[a-zA-Z0-9]+] with [Placeholder] from [$message]'
+ )
+ )
+ ).toBeInTheDocument();
- it('render disabled edit and delete buttons', () => {
- const wrapper = mountWithTheme(
- <Rules
- rules={rules}
- onEditRule={handleShowEditRule}
- onDeleteRule={handleDelete}
- disabled
- />
- );
expect(
- wrapper.find('[aria-label="Edit Rule"]').hostNodes().at(0).prop('aria-disabled')
- ).toEqual(true);
+ screen.getByText('[Mask] [Credit card numbers] from [$message]')
+ ).toBeInTheDocument();
expect(
- wrapper.find('[aria-label="Delete Rule"]').hostNodes().at(0).prop('aria-disabled')
- ).toEqual(true);
+ screen.getByText(
+ textWithMarkupMatcher(
+ '[Replace] [Password fields] with [Scrubbed] from [password]'
+ )
+ )
+ ).toBeInTheDocument();
});
- it('render edit button only', () => {
- const wrapper = mountWithTheme(
- <Rules rules={rules} onEditRule={handleShowEditRule} />
- );
- expect(wrapper.find('[aria-label="Edit Rule"]').hostNodes()).toHaveLength(3);
- expect(wrapper.find('[aria-label="Delete Rule"]')).toHaveLength(0);
+ it('render edit button only', function () {
+ render(<Rules rules={relayPiiConfig} onEditRule={jest.fn()} />);
+
+ expect(screen.getAllByRole('button', {name: 'Edit Rule'})).toHaveLength(3);
+
+ expect(screen.queryByRole('button', {name: 'Delete Rule'})).not.toBeInTheDocument();
});
- it('render delete button only', () => {
- const wrapper = mountWithTheme(<Rules rules={rules} onDeleteRule={handleDelete} />);
- expect(wrapper.find('[aria-label="Edit Rule"]')).toHaveLength(0);
- expect(wrapper.find('[aria-label="Delete Rule"]').hostNodes()).toHaveLength(3);
+ it('render delete button only', function () {
+ render(<Rules rules={relayPiiConfig} onDeleteRule={jest.fn()} />);
+
+ expect(screen.getAllByRole('button', {name: 'Delete Rule'})).toHaveLength(3);
+
+ expect(screen.queryByRole('button', {name: 'Edit Rule'})).not.toBeInTheDocument();
});
});
|
55c5f0cb685f62b19f0184b61115da0a324eafa7
|
2022-05-06 00:47:24
|
Evan Purkhiser
|
ref(js): Avoid import * as React in Fragment only files (#34296)
| false
|
Avoid import * as React in Fragment only files (#34296)
|
ref
|
diff --git a/static/app/components/actions/confirmableAction.tsx b/static/app/components/actions/confirmableAction.tsx
index 8c274fbbf5ce59..1262c98b971608 100644
--- a/static/app/components/actions/confirmableAction.tsx
+++ b/static/app/components/actions/confirmableAction.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import Confirm from 'sentry/components/confirm';
@@ -16,5 +16,5 @@ export default function ConfirmableAction({shouldConfirm, children, ...props}: P
return <Confirm {...props}>{children as ConfirmProps['children']}</Confirm>;
}
- return <React.Fragment>{children}</React.Fragment>;
+ return <Fragment>{children}</Fragment>;
}
diff --git a/static/app/components/breadcrumbs.tsx b/static/app/components/breadcrumbs.tsx
index 35a39ecfbdc08a..36865174043c9d 100644
--- a/static/app/components/breadcrumbs.tsx
+++ b/static/app/components/breadcrumbs.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import {LocationDescriptor} from 'history';
@@ -114,7 +114,7 @@ const Breadcrumbs = ({crumbs, linkLastItem = false, ...props}: Props) => {
key ?? typeof to === 'string' ? `${labelKey}${to}` : `${labelKey}${index}`;
return (
- <React.Fragment key={mapKey}>
+ <Fragment key={mapKey}>
{to ? (
<BreadcrumbLink
to={to}
@@ -130,7 +130,7 @@ const Breadcrumbs = ({crumbs, linkLastItem = false, ...props}: Props) => {
{index < crumbs.length - 1 && (
<BreadcrumbDividerIcon size="xs" direction="right" />
)}
- </React.Fragment>
+ </Fragment>
);
})}
</BreadcrumbList>
diff --git a/static/app/components/bulkController/bulkNotice.tsx b/static/app/components/bulkController/bulkNotice.tsx
index f2d4f3cb0d9d9a..f74dff3167d42c 100644
--- a/static/app/components/bulkController/bulkNotice.tsx
+++ b/static/app/components/bulkController/bulkNotice.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import {t, tct, tn} from 'sentry/locale';
@@ -92,14 +92,14 @@ function BulkNotice({
return (
<Wrapper columnsCount={columnsCount} className={className}>
{isAllSelected ? (
- <React.Fragment>
+ <Fragment>
{noticeText}{' '}
<AlertButton priority="link" onClick={onUnselectAllRows}>
{t('Cancel selection.')}
</AlertButton>
- </React.Fragment>
+ </Fragment>
) : (
- <React.Fragment>
+ <Fragment>
{tn(
'%s item on this page selected.',
'%s items on this page selected.',
@@ -108,7 +108,7 @@ function BulkNotice({
<AlertButton priority="link" onClick={onSelectAllRows}>
{actionText}
</AlertButton>
- </React.Fragment>
+ </Fragment>
)}
</Wrapper>
);
diff --git a/static/app/components/confirmDelete.tsx b/static/app/components/confirmDelete.tsx
index 70a729df30e090..f7ba760f14f2cb 100644
--- a/static/app/components/confirmDelete.tsx
+++ b/static/app/components/confirmDelete.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import Alert from 'sentry/components/alert';
import Confirm from 'sentry/components/confirm';
@@ -19,7 +19,7 @@ const ConfirmDelete = ({message, confirmInput, ...props}: Props) => (
bypass={false}
disableConfirmButton
renderMessage={({disableConfirmButton}) => (
- <React.Fragment>
+ <Fragment>
<Alert type="error">{message}</Alert>
<Field
flexibleControlStateSize
@@ -35,7 +35,7 @@ const ConfirmDelete = ({message, confirmInput, ...props}: Props) => (
onChange={e => disableConfirmButton(e.target.value !== confirmInput)}
/>
</Field>
- </React.Fragment>
+ </Fragment>
)}
/>
);
diff --git a/static/app/components/createAlertButton.tsx b/static/app/components/createAlertButton.tsx
index ddf7428e23883c..deb7cd808a4503 100644
--- a/static/app/components/createAlertButton.tsx
+++ b/static/app/components/createAlertButton.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {withRouter, WithRouterProps} from 'react-router';
import styled from '@emotion/styled';
@@ -139,7 +139,7 @@ function IncompatibleQueryAlert({
}
>
{totalErrors === 1 && (
- <React.Fragment>
+ <Fragment>
{hasProjectError &&
t('An alert can use data from only one Project. Select one and try again.')}
{hasEnvironmentError &&
@@ -158,10 +158,10 @@ function IncompatibleQueryAlert({
yAxis: <StyledCode>{eventView.getYAxis()}</StyledCode>,
}
)}
- </React.Fragment>
+ </Fragment>
)}
{totalErrors > 1 && (
- <React.Fragment>
+ <Fragment>
{t('Yikes! That button didn’t work. Please fix the following problems:')}
<StyledUnorderedList>
{hasProjectError && <li>{t('Select one Project.')}</li>}
@@ -187,7 +187,7 @@ function IncompatibleQueryAlert({
</li>
)}
</StyledUnorderedList>
- </React.Fragment>
+ </Fragment>
)}
</StyledAlert>
);
diff --git a/static/app/components/dashboards/widgetQueryFields.tsx b/static/app/components/dashboards/widgetQueryFields.tsx
index f177ae1939af72..604f174bb8eceb 100644
--- a/static/app/components/dashboards/widgetQueryFields.tsx
+++ b/static/app/components/dashboards/widgetQueryFields.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import Button from 'sentry/components/button';
@@ -216,7 +216,7 @@ function WidgetQueryFields({
const columns = fields.slice(0, fields.length - 1);
return (
- <React.Fragment>
+ <Fragment>
<Field
data-test-id="columns"
label={t('Columns')}
@@ -260,7 +260,7 @@ function WidgetQueryFields({
/>
</QueryFieldWrapper>
</Field>
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/components/events/interfaces/debugMeta-v2/debugImageDetails/candidate/information/index.tsx b/static/app/components/events/interfaces/debugMeta-v2/debugImageDetails/candidate/information/index.tsx
index 6a4d5782897aad..5ee40a055b39af 100644
--- a/static/app/components/events/interfaces/debugMeta-v2/debugImageDetails/candidate/information/index.tsx
+++ b/static/app/components/events/interfaces/debugMeta-v2/debugImageDetails/candidate/information/index.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import capitalize from 'lodash/capitalize';
import moment from 'moment-timezone';
@@ -79,7 +79,7 @@ function Information({
if (hasReprocessWarning) {
return {
tooltipDesc: (
- <React.Fragment>
+ <Fragment>
{tct(
'This debug file was uploaded [when] before this event. It takes up to 1 hour for new files to propagate. To apply new debug information, reprocess this issue.',
{
@@ -87,7 +87,7 @@ function Information({
}
)}
<DateTimeWrapper>{dateTime}</DateTimeWrapper>
- </React.Fragment>
+ </Fragment>
),
displayIcon: true,
};
@@ -104,7 +104,7 @@ function Information({
return {
tooltipDesc: (
- <React.Fragment>
+ <Fragment>
{tct(
'This debug file was uploaded [when] before this event. It takes up to 1 hour for new files to propagate.',
{
@@ -112,7 +112,7 @@ function Information({
}
)}
<DateTimeWrapper>{dateTime}</DateTimeWrapper>
- </React.Fragment>
+ </Fragment>
),
displayIcon: true,
};
@@ -121,7 +121,7 @@ function Information({
if (hasReprocessWarning) {
return {
tooltipDesc: (
- <React.Fragment>
+ <Fragment>
{tct(
'This debug file was uploaded [when] after this event. To apply new debug information, reprocess this issue.',
{
@@ -129,7 +129,7 @@ function Information({
}
)}
<DateTimeWrapper>{dateTime}</DateTimeWrapper>
- </React.Fragment>
+ </Fragment>
),
displayIcon: true,
};
@@ -137,12 +137,12 @@ function Information({
return {
tooltipDesc: (
- <React.Fragment>
+ <Fragment>
{tct('This debug file was uploaded [when] after this event.', {
when: moment(eventDateReceived).from(dateCreated, true),
})}
<DateTimeWrapper>{dateTime}</DateTimeWrapper>
- </React.Fragment>
+ </Fragment>
),
displayIcon: true,
};
@@ -185,10 +185,10 @@ function Information({
}
return (
- <React.Fragment>
+ <Fragment>
<StyledProcessingList items={items} />
<Divider />
- </React.Fragment>
+ </Fragment>
);
}
@@ -208,7 +208,7 @@ function Information({
const {tooltipDesc, displayIcon} = getTimeSinceData(dateCreated);
return (
- <React.Fragment>
+ <Fragment>
<Tooltip title={tooltipDesc}>
<TimeSinceWrapper>
{displayIcon && <IconWarning color="red300" size="xs" />}
@@ -226,7 +226,7 @@ function Information({
: `${symbolType}${fileType ? ` ${fileType}` : ''}`}
</span>
<Divider />
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/components/events/interfaces/frame/contextLine.tsx b/static/app/components/events/interfaces/frame/contextLine.tsx
index 02653f053b17c8..28d93d4b47c80c 100644
--- a/static/app/components/events/interfaces/frame/contextLine.tsx
+++ b/static/app/components/events/interfaces/frame/contextLine.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import classNames from 'classnames';
@@ -12,7 +12,7 @@ type Props = {
isActive: boolean;
line: [number, string];
className?: string;
-} & React.ComponentProps<typeof React.Fragment>;
+} & React.ComponentProps<typeof Fragment>;
const ContextLine = function (props: Props) {
const {line, isActive, className} = props;
@@ -21,7 +21,7 @@ const ContextLine = function (props: Props) {
if (defined(line[1]) && line[1].match) {
[, lineWs, lineCode] = line[1].match(/^(\s*)(.*?)$/m)!;
}
- const Component = !props.children ? React.Fragment : Context;
+ const Component = !props.children ? Fragment : Context;
return (
<li className={classNames(className, 'expandable', {active: isActive})} key={line[0]}>
<Component>
diff --git a/static/app/components/events/interfaces/frame/defaultTitle/index.tsx b/static/app/components/events/interfaces/frame/defaultTitle/index.tsx
index 5b846d11173b54..e59fe70d832bb4 100644
--- a/static/app/components/events/interfaces/frame/defaultTitle/index.tsx
+++ b/static/app/components/events/interfaces/frame/defaultTitle/index.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import AnnotatedText from 'sentry/components/events/meta/annotatedText';
@@ -201,7 +201,7 @@ const DefaultTitle = ({frame, platform, isHoverPreviewed, isUsedForGrouping}: Pr
title.push(<StyledGroupingIndicator key="info-tooltip" />);
}
- return <React.Fragment>{title}</React.Fragment>;
+ return <Fragment>{title}</Fragment>;
};
export default DefaultTitle;
diff --git a/static/app/components/events/interfaces/frame/stacktraceLink.tsx b/static/app/components/events/interfaces/frame/stacktraceLink.tsx
index 445caacdef4cbf..159d1044e7cd27 100644
--- a/static/app/components/events/interfaces/frame/stacktraceLink.tsx
+++ b/static/app/components/events/interfaces/frame/stacktraceLink.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import {openModal} from 'sentry/actionCreators/modal';
@@ -264,7 +264,7 @@ class StacktraceLink extends AsyncComponent<Props, State> {
const {frame} = this.props;
const {config} = this.match;
return (
- <React.Fragment>
+ <Fragment>
<StyledHovercard
header={
error === 'stack_root_mismatch' ? (
@@ -292,7 +292,7 @@ class StacktraceLink extends AsyncComponent<Props, State> {
>
<StyledIconInfo size="xs" />
</StyledHovercard>
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/components/events/interfaces/spans/spanGroupBar.tsx b/static/app/components/events/interfaces/spans/spanGroupBar.tsx
index bfd339304233cf..54b78552edbd72 100644
--- a/static/app/components/events/interfaces/spans/spanGroupBar.tsx
+++ b/static/app/components/events/interfaces/spans/spanGroupBar.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import Count from 'sentry/components/count';
import {
@@ -115,7 +115,7 @@ function renderMeasurements(
const measurements = getMeasurements(event);
return (
- <React.Fragment>
+ <Fragment>
{Array.from(measurements).map(([timestamp, verticalMark]) => {
const bounds = getMeasurementBounds(timestamp, generateBounds);
@@ -135,7 +135,7 @@ function renderMeasurements(
/>
);
})}
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/components/events/interfaces/spans/spanSiblingGroupBar.tsx b/static/app/components/events/interfaces/spans/spanSiblingGroupBar.tsx
index 21406cebbe91ef..7be8e6027ac432 100644
--- a/static/app/components/events/interfaces/spans/spanSiblingGroupBar.tsx
+++ b/static/app/components/events/interfaces/spans/spanSiblingGroupBar.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {
ConnectorBar,
@@ -68,10 +68,10 @@ export default function SpanSiblingGroupBar(props: Props) {
}
return (
- <React.Fragment>
+ <Fragment>
<strong>{`${t('Autogrouped')} \u2014 ${operation} \u2014 `}</strong>
{description}
- </React.Fragment>
+ </Fragment>
);
}
@@ -107,7 +107,7 @@ export default function SpanSiblingGroupBar(props: Props) {
function renderSpanRectangles() {
return (
- <React.Fragment>
+ <Fragment>
{spanGrouping.map((_, index) => (
<SpanRectangle
key={index}
@@ -119,7 +119,7 @@ export default function SpanSiblingGroupBar(props: Props) {
spanGrouping={spanGrouping}
bounds={getSpanGroupBounds(spanGrouping, generateBounds)}
/>
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/components/externalIssues/abstractExternalIssueForm.tsx b/static/app/components/externalIssues/abstractExternalIssueForm.tsx
index eaf52aa37b449f..20a63b530c93e1 100644
--- a/static/app/components/externalIssues/abstractExternalIssueForm.tsx
+++ b/static/app/components/externalIssues/abstractExternalIssueForm.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import debounce from 'lodash/debounce';
import * as qs from 'query-string';
@@ -175,7 +175,7 @@ export default class AbstractExternalIssueForm<
}
if (typeof currentOption.label === 'string') {
currentOption.label = (
- <React.Fragment>
+ <Fragment>
<QuestionTooltip
title={tct('This is your current [label].', {
label: field.label,
@@ -183,7 +183,7 @@ export default class AbstractExternalIssueForm<
size="xs"
/>{' '}
{currentOption.label}
- </React.Fragment>
+ </Fragment>
);
}
const currentOptionResultIndex = result.findIndex(
@@ -332,14 +332,14 @@ export default class AbstractExternalIssueForm<
const {Header, Body} = this.props as ModalRenderProps;
return (
- <React.Fragment>
+ <Fragment>
<Header closeButton>{this.getTitle()}</Header>
{this.renderNavTabs()}
<Body>
{this.shouldRenderLoading ? (
this.renderLoading()
) : (
- <React.Fragment>
+ <Fragment>
{this.renderBodyText()}
<Form initialData={initialData} {...this.getFormProps()}>
{(formFields || [])
@@ -360,10 +360,10 @@ export default class AbstractExternalIssueForm<
/>
))}
</Form>
- </React.Fragment>
+ </Fragment>
)}
</Body>
- </React.Fragment>
+ </Fragment>
);
};
}
diff --git a/static/app/components/forms/controls/radioGroup.tsx b/static/app/components/forms/controls/radioGroup.tsx
index 879e473f833eea..9046f7323fc69d 100644
--- a/static/app/components/forms/controls/radioGroup.tsx
+++ b/static/app/components/forms/controls/radioGroup.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import isPropValid from '@emotion/is-prop-valid';
import styled from '@emotion/styled';
@@ -63,7 +63,7 @@ const RadioGroup = <C extends string>({
const disabledChoiceReason = disabledChoice?.[1];
const disabled = !!disabledChoice || groupDisabled;
const content = (
- <React.Fragment>
+ <Fragment>
<RadioLineItem
role="radio"
index={index}
@@ -80,14 +80,14 @@ const RadioGroup = <C extends string>({
/>
<RadioLineText disabled={disabled}>{name}</RadioLineText>
{description && (
- <React.Fragment>
+ <Fragment>
{/* If there is a description then we want to have a 2x2 grid so the first column width aligns with Radio Button */}
<div />
<Description>{description}</Description>
- </React.Fragment>
+ </Fragment>
)}
</RadioLineItem>
- </React.Fragment>
+ </Fragment>
);
if (!!disabledChoiceReason) {
@@ -98,7 +98,7 @@ const RadioGroup = <C extends string>({
);
}
- return <React.Fragment key={index}>{content}</React.Fragment>;
+ return <Fragment key={index}>{content}</Fragment>;
})}
</Container>
);
diff --git a/static/app/components/group/inboxBadges/inboxReason.tsx b/static/app/components/group/inboxBadges/inboxReason.tsx
index cb2a1aec65a6db..eac0fbe6b49578 100644
--- a/static/app/components/group/inboxBadges/inboxReason.tsx
+++ b/static/app/components/group/inboxBadges/inboxReason.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import DateTime from 'sentry/components/dateTime';
@@ -169,10 +169,10 @@ function InboxReason({inbox, fontSize = 'sm', showDateAdded}: Props) {
<StyledTag type={tagType} tooltipText={tooltip} fontSize={fontSize}>
{reasonBadgeText}
{showDateAdded && dateAdded && (
- <React.Fragment>
+ <Fragment>
<Separator type={tagType ?? 'default'}>{' | '}</Separator>
<TimeSince date={dateAdded} suffix="" extraShort disabledAbsoluteTooltip />
- </React.Fragment>
+ </Fragment>
)}
</StyledTag>
);
diff --git a/static/app/components/group/sidebarSection.tsx b/static/app/components/group/sidebarSection.tsx
index 42316a7ec0560b..1e94d0cd096ef3 100644
--- a/static/app/components/group/sidebarSection.tsx
+++ b/static/app/components/group/sidebarSection.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import space from 'sentry/styles/space';
@@ -43,10 +43,10 @@ function SidebarSection({title, children, secondary, ...props}: SidebarSectionPr
const HeaderComponent = secondary ? Subheading : Heading;
return (
- <React.Fragment>
+ <Fragment>
<HeaderComponent {...props}>{title}</HeaderComponent>
<SectionContent secondary={secondary}>{children}</SectionContent>
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/components/group/suggestedOwners/suggestedOwners.tsx b/static/app/components/group/suggestedOwners/suggestedOwners.tsx
index 7148018186d5a2..91e4dd5c1cf61b 100644
--- a/static/app/components/group/suggestedOwners/suggestedOwners.tsx
+++ b/static/app/components/group/suggestedOwners/suggestedOwners.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {assignToActor, assignToUser} from 'sentry/actionCreators/group';
import {promptsCheck, promptsUpdate} from 'sentry/actionCreators/prompts';
@@ -226,7 +226,7 @@ class SuggestedOwners extends AsyncComponent<Props, State> {
const {codeowners, isDismissed} = this.state;
const owners = this.getOwnerList();
return (
- <React.Fragment>
+ <Fragment>
{owners.length > 0 && (
<SuggestedAssignees owners={owners} onAssign={this.handleAssign} />
)}
@@ -238,7 +238,7 @@ class SuggestedOwners extends AsyncComponent<Props, State> {
isDismissed={isDismissed}
handleCTAClose={this.handleCTAClose}
/>
- </React.Fragment>
+ </Fragment>
);
}
}
diff --git a/static/app/components/highlight.tsx b/static/app/components/highlight.tsx
index d2125c1dae1039..a32a5296396c2d 100644
--- a/static/app/components/highlight.tsx
+++ b/static/app/components/highlight.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
type HighlightProps = {
@@ -22,22 +22,22 @@ type Props = Omit<React.HTMLAttributes<HTMLDivElement>, keyof HighlightProps> &
const HighlightComponent = ({className, children, disabled, text}: Props) => {
// There are instances when children is not string in breadcrumbs but not caught by TS
if (!text || disabled || typeof children !== 'string') {
- return <React.Fragment>{children}</React.Fragment>;
+ return <Fragment>{children}</Fragment>;
}
const highlightText = text.toLowerCase();
const idx = children.toLowerCase().indexOf(highlightText);
if (idx === -1) {
- return <React.Fragment>{children}</React.Fragment>;
+ return <Fragment>{children}</Fragment>;
}
return (
- <React.Fragment>
+ <Fragment>
{children.substr(0, idx)}
<span className={className}>{children.substr(idx, highlightText.length)}</span>
{children.substr(idx + highlightText.length)}
- </React.Fragment>
+ </Fragment>
);
};
diff --git a/static/app/components/issueLink.tsx b/static/app/components/issueLink.tsx
index 11a067661b6d3c..5718b4b2ac187b 100644
--- a/static/app/components/issueLink.tsx
+++ b/static/app/components/issueLink.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import classNames from 'classnames';
@@ -50,7 +50,7 @@ const IssueLink = ({children, orgId, issue, to, card = true}: Props) => {
levelIndicatorSize="9px"
message={message}
annotations={
- <React.Fragment>
+ <Fragment>
{issue.logger && (
<EventAnnotation>
<Link
@@ -66,7 +66,7 @@ const IssueLink = ({children, orgId, issue, to, card = true}: Props) => {
{issue.annotations.map((annotation, i) => (
<EventAnnotation key={i} dangerouslySetInnerHTML={{__html: annotation}} />
))}
- </React.Fragment>
+ </Fragment>
}
/>
</Section>
diff --git a/static/app/components/keyValueTable.tsx b/static/app/components/keyValueTable.tsx
index 071be165ddec04..b030cbc94f349e 100644
--- a/static/app/components/keyValueTable.tsx
+++ b/static/app/components/keyValueTable.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import overflowEllipsis from 'sentry/styles/overflowEllipsis';
@@ -17,10 +17,10 @@ export const KeyValueTable = styled('dl')`
export const KeyValueTableRow = ({keyName, value}: Props) => {
return (
- <React.Fragment>
+ <Fragment>
<Key>{keyName}</Key>
<Value>{value}</Value>
- </React.Fragment>
+ </Fragment>
);
};
diff --git a/static/app/components/modals/dashboardWidgetLibraryModal/libraryTab.tsx b/static/app/components/modals/dashboardWidgetLibraryModal/libraryTab.tsx
index 63e928ca20cef1..ea8c71477c1ad6 100644
--- a/static/app/components/modals/dashboardWidgetLibraryModal/libraryTab.tsx
+++ b/static/app/components/modals/dashboardWidgetLibraryModal/libraryTab.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import Alert from 'sentry/components/alert';
@@ -24,7 +24,7 @@ function DashboardWidgetLibraryTab({
setErrored,
}: Props) {
return (
- <React.Fragment>
+ <Fragment>
{errored && !!!selectedWidgets.length ? (
<Alert type="error">
{t(
@@ -46,7 +46,7 @@ function DashboardWidgetLibraryTab({
);
})}
</WidgetLibraryGrid>
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/components/modals/emailVerificationModal.tsx b/static/app/components/modals/emailVerificationModal.tsx
index 32ca5515cd1a75..8d2f3ccabcd5d0 100644
--- a/static/app/components/modals/emailVerificationModal.tsx
+++ b/static/app/components/modals/emailVerificationModal.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {withRouter, WithRouterProps} from 'react-router';
import {ModalRenderProps} from 'sentry/actionCreators/modal';
@@ -21,7 +21,7 @@ function EmailVerificationModal({
actionMessage = 'taking this action',
}: Props) {
return (
- <React.Fragment>
+ <Fragment>
<Header closeButton>{t('Action Required')}</Header>
<Body>
<TextBlock>
@@ -36,7 +36,7 @@ function EmailVerificationModal({
</TextBlock>
<EmailAddresses />
</Body>
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/components/modals/inviteMembersModal/index.tsx b/static/app/components/modals/inviteMembersModal/index.tsx
index bb80fd4ac17634..fed1249117f406 100644
--- a/static/app/components/modals/inviteMembersModal/index.tsx
+++ b/static/app/components/modals/inviteMembersModal/index.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {css} from '@emotion/react';
import styled from '@emotion/styled';
@@ -322,7 +322,7 @@ class InviteMembersModal extends AsyncComponent<Props, State> {
// eslint-disable-next-line react/prop-types
const hookRenderer: InviteModalRenderFunc = ({sendInvites, canSend, headerInfo}) => (
- <React.Fragment>
+ <Fragment>
<Heading>
{t('Invite New Members')}
{!this.willInvite && (
@@ -386,7 +386,7 @@ class InviteMembersModal extends AsyncComponent<Props, State> {
<div>{this.statusMessage}</div>
{complete ? (
- <React.Fragment>
+ <Fragment>
<Button data-test-id="send-more" size="small" onClick={this.reset}>
{t('Send more invites')}
</Button>
@@ -404,9 +404,9 @@ class InviteMembersModal extends AsyncComponent<Props, State> {
>
{t('Close')}
</Button>
- </React.Fragment>
+ </Fragment>
) : (
- <React.Fragment>
+ <Fragment>
<Button
data-test-id="cancel"
size="small"
@@ -424,11 +424,11 @@ class InviteMembersModal extends AsyncComponent<Props, State> {
>
{this.inviteButtonLabel}
</Button>
- </React.Fragment>
+ </Fragment>
)}
</FooterContent>
</Footer>
- </React.Fragment>
+ </Fragment>
);
return (
diff --git a/static/app/components/modals/sentryAppDetailsModal.tsx b/static/app/components/modals/sentryAppDetailsModal.tsx
index fb7182c90bec8a..9516ba85776236 100644
--- a/static/app/components/modals/sentryAppDetailsModal.tsx
+++ b/static/app/components/modals/sentryAppDetailsModal.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import Access from 'sentry/components/acl/access';
@@ -98,7 +98,7 @@ export default class SentryAppDetailsModal extends AsyncComponent<Props, State>
}
return (
- <React.Fragment>
+ <Fragment>
<Title>Permissions</Title>
{permissions.read.length > 0 && (
<Permission>
@@ -134,7 +134,7 @@ export default class SentryAppDetailsModal extends AsyncComponent<Props, State>
</Text>
</Permission>
)}
- </React.Fragment>
+ </Fragment>
);
}
@@ -155,7 +155,7 @@ export default class SentryAppDetailsModal extends AsyncComponent<Props, State>
const featureProps = {organization, features};
return (
- <React.Fragment>
+ <Fragment>
<Heading>
<SentryAppIcon sentryApp={sentryApp} size={50} />
<HeadingInfo>
@@ -167,7 +167,7 @@ export default class SentryAppDetailsModal extends AsyncComponent<Props, State>
<FeatureList {...featureProps} provider={{...sentryApp, key: sentryApp.slug}} />
<IntegrationFeatures {...featureProps}>
{({disabled, disabledReason}) => (
- <React.Fragment>
+ <Fragment>
{!disabled && this.renderPermissions()}
<Footer>
<Author>{t('Authored By %s', sentryApp.author)}</Author>
@@ -195,10 +195,10 @@ export default class SentryAppDetailsModal extends AsyncComponent<Props, State>
</Access>
</div>
</Footer>
- </React.Fragment>
+ </Fragment>
)}
</IntegrationFeatures>
- </React.Fragment>
+ </Fragment>
);
}
}
diff --git a/static/app/components/modals/widgetViewerModal/widgetViewerTableCell.tsx b/static/app/components/modals/widgetViewerModal/widgetViewerTableCell.tsx
index 945904f9527959..c959626c0dedc8 100644
--- a/static/app/components/modals/widgetViewerModal/widgetViewerTableCell.tsx
+++ b/static/app/components/modals/widgetViewerModal/widgetViewerTableCell.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import {Location, LocationDescriptorObject} from 'history';
@@ -191,7 +191,7 @@ export const renderGridBodyCell =
}
return (
- <React.Fragment>
+ <Fragment>
{isTopEvents &&
isFirstPage &&
rowIndex < DEFAULT_NUM_TOP_EVENTS &&
@@ -199,7 +199,7 @@ export const renderGridBodyCell =
<TopResultsIndicator count={DEFAULT_NUM_TOP_EVENTS} index={rowIndex} />
) : null}
{cell}
- </React.Fragment>
+ </Fragment>
);
};
diff --git a/static/app/components/organizations/timeRangeSelector/dateRange/relativeSelector.tsx b/static/app/components/organizations/timeRangeSelector/dateRange/relativeSelector.tsx
index d06ccd000704ca..d5d114e3bc7e58 100644
--- a/static/app/components/organizations/timeRangeSelector/dateRange/relativeSelector.tsx
+++ b/static/app/components/organizations/timeRangeSelector/dateRange/relativeSelector.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {DEFAULT_RELATIVE_PERIODS} from 'sentry/constants';
@@ -11,7 +11,7 @@ type Props = {
};
const RelativeSelector = ({onClick, selected, relativePeriods}: Props) => (
- <React.Fragment>
+ <Fragment>
{Object.entries(relativePeriods || DEFAULT_RELATIVE_PERIODS).map(([value, label]) => (
<SelectorItem
key={value}
@@ -21,7 +21,7 @@ const RelativeSelector = ({onClick, selected, relativePeriods}: Props) => (
selected={selected === value}
/>
))}
- </React.Fragment>
+ </Fragment>
);
export default RelativeSelector;
diff --git a/static/app/components/replays/keyMetrics.tsx b/static/app/components/replays/keyMetrics.tsx
index da2e8544e5f669..b7f7aaa48cba13 100644
--- a/static/app/components/replays/keyMetrics.tsx
+++ b/static/app/components/replays/keyMetrics.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import space from 'sentry/styles/space';
@@ -27,10 +27,10 @@ export const KeyMetrics = styled('dl')`
export const KeyMetricData = ({keyName, value}: Props) => {
return (
- <React.Fragment>
+ <Fragment>
<Key>{keyName}</Key>
<Value>{value}</Value>
- </React.Fragment>
+ </Fragment>
);
};
diff --git a/static/app/components/stream/processingIssueHint.tsx b/static/app/components/stream/processingIssueHint.tsx
index 87899190f83f87..5a98df4676649a 100644
--- a/static/app/components/stream/processingIssueHint.tsx
+++ b/static/app/components/stream/processingIssueHint.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import Alert from 'sentry/components/alert';
@@ -25,9 +25,9 @@ function ProcessingIssueHint({orgId, projectId, issue, showProject}: Props) {
let project: React.ReactNode = null;
if (showProject) {
project = (
- <React.Fragment>
+ <Fragment>
<strong>{projectId}</strong> —{' '}
- </React.Fragment>
+ </Fragment>
);
}
@@ -38,13 +38,13 @@ function ProcessingIssueHint({orgId, projectId, issue, showProject}: Props) {
issue.numIssues
);
lastEvent = (
- <React.Fragment>
+ <Fragment>
(
{tct('last event from [ago]', {
ago: <TimeSince date={issue.lastSeen} />,
})}
)
- </React.Fragment>
+ </Fragment>
);
alertType = 'error';
showButton = true;
diff --git a/static/app/utils/dashboards/issueFieldRenderers.tsx b/static/app/utils/dashboards/issueFieldRenderers.tsx
index 838b2b33c81d21..288c55dd295dfa 100644
--- a/static/app/utils/dashboards/issueFieldRenderers.tsx
+++ b/static/app/utils/dashboards/issueFieldRenderers.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {css} from '@emotion/react';
import styled from '@emotion/styled';
import {Location} from 'history';
@@ -170,13 +170,13 @@ const issuesCountRenderer = (
title={
<div>
{filteredCount ? (
- <React.Fragment>
+ <Fragment>
<StyledLink to={filteredDiscoverLink}>
{t('Matching search filters')}
<WrappedCount value={filteredCount} />
</StyledLink>
<Divider />
- </React.Fragment>
+ </Fragment>
) : null}
<StyledLink to={discoverLink}>
{t(`Total in ${selectionDateString}`)}
@@ -192,10 +192,10 @@ const issuesCountRenderer = (
>
<span>
{['events', 'users'].includes(field) && filteredCount ? (
- <React.Fragment>
+ <Fragment>
<Count value={filteredCount} />
<SecondaryCount value={primaryCount} />
- </React.Fragment>
+ </Fragment>
) : (
<Count value={primaryCount} />
)}
diff --git a/static/app/utils/measurements/measurements.tsx b/static/app/utils/measurements/measurements.tsx
index 75633fc3017f82..c79080702b19ee 100644
--- a/static/app/utils/measurements/measurements.tsx
+++ b/static/app/utils/measurements/measurements.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {MobileVital, WebVital} from 'sentry/utils/discover/fields';
import {
@@ -43,7 +43,7 @@ type Props = {
function Measurements({children}: Props) {
const measurements = {...WEB_MEASUREMENTS, ...MOBILE_MEASUREMENTS};
- return <React.Fragment>{children({measurements})}</React.Fragment>;
+ return <Fragment>{children({measurements})}</Fragment>;
}
export default Measurements;
diff --git a/static/app/utils/performance/histogram/histogramQuery.tsx b/static/app/utils/performance/histogram/histogramQuery.tsx
index 110f0970bd9d6d..288014db44e032 100644
--- a/static/app/utils/performance/histogram/histogramQuery.tsx
+++ b/static/app/utils/performance/histogram/histogramQuery.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import omit from 'lodash/omit';
import GenericDiscoverQuery, {
@@ -71,14 +71,14 @@ function HistogramQuery(props: Props) {
if (fields.length === 0) {
return (
- <React.Fragment>
+ <Fragment>
{children({
isLoading: false,
error: null,
pageLinks: null,
histograms: {},
})}
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/utils/performance/quickTrace/quickTraceQuery.tsx b/static/app/utils/performance/quickTrace/quickTraceQuery.tsx
index 0efdf88a6e7d77..0eb453e2529438 100644
--- a/static/app/utils/performance/quickTrace/quickTraceQuery.tsx
+++ b/static/app/utils/performance/quickTrace/quickTraceQuery.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {Event} from 'sentry/types/event';
import {DiscoverQueryProps} from 'sentry/utils/discover/genericDiscoverQuery';
@@ -21,7 +21,7 @@ export default function QuickTraceQuery({children, event, ...props}: QueryProps)
if (!traceId) {
return (
- <React.Fragment>
+ <Fragment>
{children({
isLoading: false,
error: null,
@@ -29,7 +29,7 @@ export default function QuickTraceQuery({children, event, ...props}: QueryProps)
type: 'empty',
currentEvent: null,
})}
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/utils/performance/quickTrace/traceFullQuery.tsx b/static/app/utils/performance/quickTrace/traceFullQuery.tsx
index 44a89d551c0900..ba04972ce700b4 100644
--- a/static/app/utils/performance/quickTrace/traceFullQuery.tsx
+++ b/static/app/utils/performance/quickTrace/traceFullQuery.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import GenericDiscoverQuery, {
DiscoverQueryProps,
@@ -50,14 +50,14 @@ function getTraceFullRequestPayload({
function EmptyTrace<T>({children}: Pick<QueryProps<T>, 'children'>) {
return (
- <React.Fragment>
+ <Fragment>
{children({
isLoading: false,
error: null,
traces: null,
type: 'full',
})}
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/utils/performance/quickTrace/traceLiteQuery.tsx b/static/app/utils/performance/quickTrace/traceLiteQuery.tsx
index ec9443a5569140..c5cc3327d8fa12 100644
--- a/static/app/utils/performance/quickTrace/traceLiteQuery.tsx
+++ b/static/app/utils/performance/quickTrace/traceLiteQuery.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import GenericDiscoverQuery, {
DiscoverQueryProps,
@@ -39,14 +39,14 @@ function getTraceLiteRequestPayload({
function EmptyTrace({children}: Pick<QueryProps, 'children'>) {
return (
- <React.Fragment>
+ <Fragment>
{children({
isLoading: false,
error: null,
trace: null,
type: 'partial',
})}
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/utils/performance/quickTrace/traceMetaQuery.tsx b/static/app/utils/performance/quickTrace/traceMetaQuery.tsx
index 45c12154a32bee..1a86f10406f5b3 100644
--- a/static/app/utils/performance/quickTrace/traceMetaQuery.tsx
+++ b/static/app/utils/performance/quickTrace/traceMetaQuery.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import GenericDiscoverQuery from 'sentry/utils/discover/genericDiscoverQuery';
import {
@@ -30,13 +30,13 @@ function TraceMetaQuery({
}: QueryProps) {
if (!traceId) {
return (
- <React.Fragment>
+ <Fragment>
{children({
isLoading: false,
error: null,
meta: null,
})}
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/views/alerts/incidentRules/ruleConditionsForm.tsx b/static/app/views/alerts/incidentRules/ruleConditionsForm.tsx
index eebc9d4de1739a..a6b56e9de2c75d 100644
--- a/static/app/views/alerts/incidentRules/ruleConditionsForm.tsx
+++ b/static/app/views/alerts/incidentRules/ruleConditionsForm.tsx
@@ -1,5 +1,4 @@
-import * as React from 'react';
-import {Fragment} from 'react';
+import {Fragment, PureComponent} from 'react';
import {InjectedRouter} from 'react-router';
import {components} from 'react-select';
import {css} from '@emotion/react';
@@ -78,7 +77,7 @@ type State = {
environments: Environment[] | null;
};
-class RuleConditionsForm extends React.PureComponent<Props, State> {
+class RuleConditionsForm extends PureComponent<Props, State> {
state: State = {
environments: null,
};
@@ -480,7 +479,7 @@ class RuleConditionsForm extends React.PureComponent<Props, State> {
dataset === 'events' ? [...measurementTags, ...transactionTags] : [];
return (
- <React.Fragment>
+ <Fragment>
<ChartPanel>
<StyledPanelBody>{this.props.thresholdChart}</StyledPanelBody>
</ChartPanel>
@@ -575,7 +574,7 @@ class RuleConditionsForm extends React.PureComponent<Props, State> {
</FormField>
</FormRow>
{!hasAlertWizardV3 && this.renderInterval()}
- </React.Fragment>
+ </Fragment>
);
}
}
diff --git a/static/app/views/dashboardsV2/controls.tsx b/static/app/views/dashboardsV2/controls.tsx
index d2835f5d026fa1..38892fb87bc605 100644
--- a/static/app/views/dashboardsV2/controls.tsx
+++ b/static/app/views/dashboardsV2/controls.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import Feature from 'sentry/components/acl/feature';
@@ -121,7 +121,7 @@ function Controls({
<StyledButtonBar gap={1} key="controls">
<DashboardEditFeature>
{hasFeature => (
- <React.Fragment>
+ <Fragment>
<Button
data-test-id="dashboard-edit"
onClick={e => {
@@ -160,7 +160,7 @@ function Controls({
</Button>
</Tooltip>
) : null}
- </React.Fragment>
+ </Fragment>
)}
</DashboardEditFeature>
</StyledButtonBar>
diff --git a/static/app/views/dashboardsV2/widgetBuilder/buildSteps/groupByStep/queryField.tsx b/static/app/views/dashboardsV2/widgetBuilder/buildSteps/groupByStep/queryField.tsx
index 4a2a414f373d3a..da1aff6b3b99db 100644
--- a/static/app/views/dashboardsV2/widgetBuilder/buildSteps/groupByStep/queryField.tsx
+++ b/static/app/views/dashboardsV2/widgetBuilder/buildSteps/groupByStep/queryField.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {DraggableSyntheticListeners, UseDraggableArguments} from '@dnd-kit/core';
import styled from '@emotion/styled';
@@ -40,7 +40,7 @@ export function QueryField({
return (
<QueryFieldWrapper ref={forwardRef} style={style}>
{isDragging ? null : (
- <React.Fragment>
+ <Fragment>
{canDrag && (
<DragAndReorderButton
{...listeners}
@@ -68,7 +68,7 @@ export function QueryField({
aria-label={t('Remove group')}
/>
)}
- </React.Fragment>
+ </Fragment>
)}
</QueryFieldWrapper>
);
diff --git a/static/app/views/dataExport/dataDownload.tsx b/static/app/views/dataExport/dataDownload.tsx
index 1d5a818c7040d3..15950b32e9687e 100644
--- a/static/app/views/dataExport/dataDownload.tsx
+++ b/static/app/views/dataExport/dataDownload.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {browserHistory, RouteComponentProps} from 'react-router';
import styled from '@emotion/styled';
@@ -93,7 +93,7 @@ class DataDownload extends AsyncView<Props, State> {
renderEarly(): React.ReactNode {
return (
- <React.Fragment>
+ <Fragment>
<Header>
<h3>
{t('What are')}
@@ -109,7 +109,7 @@ class DataDownload extends AsyncView<Props, State> {
</p>
<p>{t("Close this window and we'll email you when your download is ready.")}</p>
</Body>
- </React.Fragment>
+ </Fragment>
);
}
@@ -117,7 +117,7 @@ class DataDownload extends AsyncView<Props, State> {
const {query} = this.state.download;
const actionLink = this.getActionLink(query.type);
return (
- <React.Fragment>
+ <Fragment>
<Header>
<h3>{t('This is awkward.')}</h3>
</Header>
@@ -136,7 +136,7 @@ class DataDownload extends AsyncView<Props, State> {
{t('Start a New Download')}
</DownloadButton>
</Body>
- </React.Fragment>
+ </Fragment>
);
}
@@ -171,13 +171,13 @@ class DataDownload extends AsyncView<Props, State> {
const {type = ExportQueryType.IssuesByTag} = query;
return type === 'Discover' ? (
- <React.Fragment>
+ <Fragment>
<p>{t('Need to make changes?')}</p>
<Button priority="primary" onClick={() => this.openInDiscover()}>
{t('Open in Discover')}
</Button>
<br />
- </React.Fragment>
+ </Fragment>
) : null;
}
@@ -188,7 +188,7 @@ class DataDownload extends AsyncView<Props, State> {
const {orgId, dataExportId} = this.props.params;
return (
- <React.Fragment>
+ <Fragment>
<Header>
<h3>{t('All done.')}</h3>
</Header>
@@ -225,7 +225,7 @@ class DataDownload extends AsyncView<Props, State> {
})}
</p>
</Body>
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/views/eventsV2/table/tableActions.tsx b/static/app/views/eventsV2/table/tableActions.tsx
index 443d0f9d2fe789..10fb8d021c2182 100644
--- a/static/app/views/eventsV2/table/tableActions.tsx
+++ b/static/app/views/eventsV2/table/tableActions.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {Location} from 'history';
import Feature from 'sentry/components/acl/feature';
@@ -151,7 +151,7 @@ function FeatureWrapper(props: FeatureWrapperProps) {
function HeaderActions(props: Props) {
return (
- <React.Fragment>
+ <Fragment>
<FeatureWrapper {...props} key="edit">
{renderEditButton}
</FeatureWrapper>
@@ -159,7 +159,7 @@ function HeaderActions(props: Props) {
{renderDownloadButton}
</FeatureWrapper>
{renderSummaryButton(props)}
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/views/onboarding/components/fullIntroduction.tsx b/static/app/views/onboarding/components/fullIntroduction.tsx
index 1713bc7e245d25..567da7f4231d2c 100644
--- a/static/app/views/onboarding/components/fullIntroduction.tsx
+++ b/static/app/views/onboarding/components/fullIntroduction.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {motion} from 'framer-motion';
import {openInviteMembersModal} from 'sentry/actionCreators/modal';
@@ -15,7 +15,7 @@ type Props = {
export default function FullIntroduction({currentPlatform}: Props) {
return (
- <React.Fragment>
+ <Fragment>
<SetupIntroduction
stepHeaderText={t(
'Prepare the %s SDK',
@@ -46,6 +46,6 @@ export default function FullIntroduction({currentPlatform}: Props) {
}
)}
</motion.p>
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/views/onboarding/otherSetup.tsx b/static/app/views/onboarding/otherSetup.tsx
index 42c451c1462711..c2d49832e7f3c0 100644
--- a/static/app/views/onboarding/otherSetup.tsx
+++ b/static/app/views/onboarding/otherSetup.tsx
@@ -1,6 +1,6 @@
import 'prism-sentry/index.css';
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import {motion} from 'framer-motion';
@@ -54,7 +54,7 @@ class OtherSetup extends AsyncComponent<Props, State> {
const currentPlatform = 'other';
const blurb = (
- <React.Fragment>
+ <Fragment>
<p>
{tct(`Prepare the SDK for your language following this [docsLink:guide].`, {
docsLink: <ExternalLink href="https://develop.sentry.dev/sdk/overview/" />,
@@ -66,7 +66,7 @@ class OtherSetup extends AsyncComponent<Props, State> {
</p>
<p>{tct('Here is the DSN: [DSN]', {DSN: <b> {keyList?.[0].dsn.public}</b>})}</p>
- </React.Fragment>
+ </Fragment>
);
const docs = (
@@ -90,13 +90,13 @@ class OtherSetup extends AsyncComponent<Props, State> {
);
return (
- <React.Fragment>
+ <Fragment>
<FullIntroduction currentPlatform={currentPlatform} />
{getDynamicText({
value: docs,
fixed: testOnlyAlert,
})}
- </React.Fragment>
+ </Fragment>
);
}
}
diff --git a/static/app/views/onboarding/targetedOnboarding/components/fullIntroduction.tsx b/static/app/views/onboarding/targetedOnboarding/components/fullIntroduction.tsx
index 5a1db146dfe89d..f12e4fd6f82d85 100644
--- a/static/app/views/onboarding/targetedOnboarding/components/fullIntroduction.tsx
+++ b/static/app/views/onboarding/targetedOnboarding/components/fullIntroduction.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {motion} from 'framer-motion';
import {PlatformKey} from 'sentry/data/platformCategories';
@@ -19,7 +19,7 @@ export default function FullIntroduction({currentPlatform, organization}: Props)
isMobile() &&
organization.experiments.TargetedOnboardingMobileRedirectExperiment === 'email-cta';
return (
- <React.Fragment>
+ <Fragment>
<SetupIntroduction
stepHeaderText={t(
'Prepare the %s SDK',
@@ -40,6 +40,6 @@ export default function FullIntroduction({currentPlatform, organization}: Props)
)}
</motion.p>
)}
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/views/organizationGroupDetails/groupActivityItem.tsx b/static/app/views/organizationGroupDetails/groupActivityItem.tsx
index e2f9a8fbd1e399..1fa61cbc54c2d9 100644
--- a/static/app/views/organizationGroupDetails/groupActivityItem.tsx
+++ b/static/app/views/organizationGroupDetails/groupActivityItem.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import CommitLink from 'sentry/components/commitLink';
import Duration from 'sentry/components/duration';
@@ -266,7 +266,7 @@ function GroupActivityItem({activity, orgSlug, projectId, author}: Props) {
}
}
- return <React.Fragment>{renderContent()}</React.Fragment>;
+ return <Fragment>{renderContent()}</Fragment>;
}
export default GroupActivityItem;
diff --git a/static/app/views/organizationIntegrations/abstractIntegrationDetailedView.tsx b/static/app/views/organizationIntegrations/abstractIntegrationDetailedView.tsx
index 0d539ce804d2bc..f460ed7ba79987 100644
--- a/static/app/views/organizationIntegrations/abstractIntegrationDetailedView.tsx
+++ b/static/app/views/organizationIntegrations/abstractIntegrationDetailedView.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {RouteComponentProps} from 'react-router';
import styled from '@emotion/styled';
import startCase from 'lodash/startCase';
@@ -337,7 +337,7 @@ class AbstractIntegrationDetailedView<
const {FeatureList} = getIntegrationFeatureGate();
return (
- <React.Fragment>
+ <Fragment>
<Flex>
<FlexContainer>
<Description dangerouslySetInnerHTML={{__html: marked(this.description)}} />
@@ -369,20 +369,20 @@ class AbstractIntegrationDetailedView<
))}
</Metadata>
</Flex>
- </React.Fragment>
+ </Fragment>
);
}
renderBody() {
return (
- <React.Fragment>
+ <Fragment>
{this.renderAlert()}
{this.renderTopSection()}
{this.renderTabs()}
{this.state.tab === 'overview'
? this.renderInformationCard()
: this.renderConfigurations()}
- </React.Fragment>
+ </Fragment>
);
}
}
diff --git a/static/app/views/organizationIntegrations/integrationRepos.tsx b/static/app/views/organizationIntegrations/integrationRepos.tsx
index 72ed47bb97e78a..8a23aa03e73503 100644
--- a/static/app/views/organizationIntegrations/integrationRepos.tsx
+++ b/static/app/views/organizationIntegrations/integrationRepos.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import debounce from 'lodash/debounce';
@@ -219,7 +219,7 @@ class IntegrationRepos extends AsyncComponent<Props, State> {
);
return (
- <React.Fragment>
+ <Fragment>
<Panel>
{header}
<PanelBody>
@@ -251,7 +251,7 @@ class IntegrationRepos extends AsyncComponent<Props, State> {
{itemListPageLinks && (
<Pagination pageLinks={itemListPageLinks} {...this.props} />
)}
- </React.Fragment>
+ </Fragment>
);
}
}
diff --git a/static/app/views/performance/landing/vitalsCards.tsx b/static/app/views/performance/landing/vitalsCards.tsx
index a720d896e3db45..07e2eed870ef56 100644
--- a/static/app/views/performance/landing/vitalsCards.tsx
+++ b/static/app/views/performance/landing/vitalsCards.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import * as Sentry from '@sentry/react';
import {Location} from 'history';
@@ -408,7 +408,7 @@ export function VitalBar(props: VitalBarProps) {
const colorStops = getColorStopsFromPercents(percents);
return (
- <React.Fragment>
+ <Fragment>
{showBar && (
<StyledTooltip
title={
@@ -443,7 +443,7 @@ export function VitalBar(props: VitalBarProps) {
/>
</BarDetail>
)}
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/views/performance/transactionSummary/filter.tsx b/static/app/views/performance/transactionSummary/filter.tsx
index 24a190ffb69ba4..5f7148ac52a0c5 100644
--- a/static/app/views/performance/transactionSummary/filter.tsx
+++ b/static/app/views/performance/transactionSummary/filter.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import {Location} from 'history';
@@ -62,7 +62,7 @@ function Filter(props: Props) {
hasDarkBorderBottomColor: boolean;
} = {
children: (
- <React.Fragment>
+ <Fragment>
<IconFilter />
<FilterLabel>
{currentFilter === SpanOperationBreakdownFilter.None
@@ -71,7 +71,7 @@ function Filter(props: Props) {
operationName: currentFilter,
})}
</FilterLabel>
- </React.Fragment>
+ </Fragment>
),
priority: 'default',
hasDarkBorderBottomColor: false,
diff --git a/static/app/views/performance/transactionSummary/transactionOverview/content.tsx b/static/app/views/performance/transactionSummary/transactionOverview/content.tsx
index 1a80b021fbd7a8..1fc20fa5bc6218 100644
--- a/static/app/views/performance/transactionSummary/transactionOverview/content.tsx
+++ b/static/app/views/performance/transactionSummary/transactionOverview/content.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {browserHistory} from 'react-router';
import styled from '@emotion/styled';
import {Location} from 'history';
@@ -264,7 +264,7 @@ function SummaryContent({
};
return (
- <React.Fragment>
+ <Fragment>
<Layout.Main>
<FilterActions>
<Filter
@@ -386,7 +386,7 @@ function SummaryContent({
location={location}
/>
</Layout.Side>
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/views/projectDetail/projectScoreCards/projectApdexScoreCard.tsx b/static/app/views/projectDetail/projectScoreCards/projectApdexScoreCard.tsx
index b9d13dbc58d8d2..c27588779a6276 100644
--- a/static/app/views/projectDetail/projectScoreCards/projectApdexScoreCard.tsx
+++ b/static/app/views/projectDetail/projectScoreCards/projectApdexScoreCard.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import round from 'lodash/round';
import AsyncComponent from 'sentry/components/asyncComponent';
@@ -179,14 +179,14 @@ class ProjectApdexScoreCard extends AsyncComponent<Props, State> {
renderTrend() {
// we want to show trend only after currentApdex has loaded to prevent jumping
return defined(this.currentApdex) && defined(this.trend) ? (
- <React.Fragment>
+ <Fragment>
{this.trend >= 0 ? (
<IconArrow direction="up" size="xs" />
) : (
<IconArrow direction="down" size="xs" />
)}
<Count value={Math.abs(this.trend)} />
- </React.Fragment>
+ </Fragment>
) : null;
}
diff --git a/static/app/views/projectDetail/projectScoreCards/projectVelocityScoreCard.tsx b/static/app/views/projectDetail/projectScoreCards/projectVelocityScoreCard.tsx
index 87d2090167a5b0..2178193ebf9b21 100644
--- a/static/app/views/projectDetail/projectScoreCards/projectVelocityScoreCard.tsx
+++ b/static/app/views/projectDetail/projectScoreCards/projectVelocityScoreCard.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {fetchAnyReleaseExistence} from 'sentry/actionCreators/projects';
import AsyncComponent from 'sentry/components/asyncComponent';
@@ -209,14 +209,14 @@ class ProjectVelocityScoreCard extends AsyncComponent<Props, State> {
}
return (
- <React.Fragment>
+ <Fragment>
{this.trend >= 0 ? (
<IconArrow direction="up" size="xs" />
) : (
<IconArrow direction="down" size="xs" />
)}
{Math.abs(this.trend)}
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/views/projectInstall/issueAlertOptions.tsx b/static/app/views/projectInstall/issueAlertOptions.tsx
index c9b65133b90b94..0ae04de155ee4b 100644
--- a/static/app/views/projectInstall/issueAlertOptions.tsx
+++ b/static/app/views/projectInstall/issueAlertOptions.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import * as Sentry from '@sentry/react';
import isEqual from 'lodash/isEqual';
@@ -287,7 +287,7 @@ class IssueAlertOptions extends AsyncComponent<Props, State> {
this.state.conditions?.length > 0
);
return (
- <React.Fragment>
+ <Fragment>
<PageHeadingWithTopMargins withMargins>
{t('Set your default alert settings')}
</PageHeadingWithTopMargins>
@@ -297,7 +297,7 @@ class IssueAlertOptions extends AsyncComponent<Props, State> {
onChange={alertSetting => this.setStateAndUpdateParents({alertSetting})}
value={this.state.alertSetting}
/>
- </React.Fragment>
+ </Fragment>
);
}
}
diff --git a/static/app/views/projectsDashboard/chart.tsx b/static/app/views/projectsDashboard/chart.tsx
index d7e4ec68c8f2e2..494e5e990987af 100644
--- a/static/app/views/projectsDashboard/chart.tsx
+++ b/static/app/views/projectsDashboard/chart.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {useTheme} from '@emotion/react';
import BaseChart from 'sentry/components/charts/baseChart';
@@ -161,10 +161,10 @@ const Chart = ({firstEvent, stats, transactionStats}: Props) => {
};
return (
- <React.Fragment>
+ <Fragment>
<BaseChart {...chartOptions} />
{!firstEvent && <NoEvents seriesCount={series.length} />}
- </React.Fragment>
+ </Fragment>
);
};
diff --git a/static/app/views/releases/detail/header/releaseActions.tsx b/static/app/views/releases/detail/header/releaseActions.tsx
index 124d7493db255e..7044afd8b38eb8 100644
--- a/static/app/views/releases/detail/header/releaseActions.tsx
+++ b/static/app/views/releases/detail/header/releaseActions.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {browserHistory} from 'react-router';
import styled from '@emotion/styled';
import {Location} from 'history';
@@ -73,7 +73,7 @@ function ReleaseActions({
releaseMeta.projects.length - visibleProjects.length;
return (
- <React.Fragment>
+ <Fragment>
{visibleProjects.map(project => (
<ProjectBadge key={project.slug} project={project} avatarSize={18} />
))}
@@ -89,7 +89,7 @@ function ReleaseActions({
</Tooltip>
</span>
)}
- </React.Fragment>
+ </Fragment>
);
}
@@ -103,13 +103,13 @@ function ReleaseActions({
function getModalMessage(message: React.ReactNode) {
return (
- <React.Fragment>
+ <Fragment>
{message}
<ProjectsWrapper>{getProjectList()}</ProjectsWrapper>
{t('Are you sure you want to do this?')}
- </React.Fragment>
+ </Fragment>
);
}
diff --git a/static/app/views/settings/account/accountEmails.tsx b/static/app/views/settings/account/accountEmails.tsx
index 56875304d6539a..efc523827a47d9 100644
--- a/static/app/views/settings/account/accountEmails.tsx
+++ b/static/app/views/settings/account/accountEmails.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import {addErrorMessage} from 'sentry/actionCreators/indicator';
@@ -47,7 +47,7 @@ class AccountEmails extends AsyncView<Props, State> {
renderBody() {
return (
- <React.Fragment>
+ <Fragment>
<SettingsPageHeader title={t('Email Addresses')} />
<EmailAddresses />
<Form
@@ -63,7 +63,7 @@ class AccountEmails extends AsyncView<Props, State> {
<AlertLink to="/settings/account/notifications" icon={<IconStack />}>
{t('Want to change how many emails you get? Use the notifications panel.')}
</AlertLink>
- </React.Fragment>
+ </Fragment>
);
}
}
diff --git a/static/app/views/settings/account/accountSecurity/components/removeConfirm.tsx b/static/app/views/settings/account/accountSecurity/components/removeConfirm.tsx
index ce57907aecffd9..1bdb1be5e9cf3b 100644
--- a/static/app/views/settings/account/accountSecurity/components/removeConfirm.tsx
+++ b/static/app/views/settings/account/accountSecurity/components/removeConfirm.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import Confirm from 'sentry/components/confirm';
import {t} from 'sentry/locale';
@@ -8,14 +8,14 @@ import TextBlock from 'sentry/views/settings/components/text/textBlock';
type Props = React.ComponentProps<typeof Confirm>;
const message = (
- <React.Fragment>
+ <Fragment>
<ConfirmHeader>{t('Do you want to remove this method?')}</ConfirmHeader>
<TextBlock>
{t(
'Removing the last authentication method will disable two-factor authentication completely.'
)}
</TextBlock>
- </React.Fragment>
+ </Fragment>
);
const RemoveConfirm = (props: Props) => <Confirm {...props} message={message} />;
diff --git a/static/app/views/settings/account/accountSubscriptions.tsx b/static/app/views/settings/account/accountSubscriptions.tsx
index 28775f24a1c76b..7d7cd076142a31 100644
--- a/static/app/views/settings/account/accountSubscriptions.tsx
+++ b/static/app/views/settings/account/accountSubscriptions.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import groupBy from 'lodash/groupBy';
import moment from 'moment';
@@ -102,7 +102,7 @@ class AccountSubscriptions extends AsyncView<AsyncView['props'], State> {
<PanelHeader>{t('Subscription')}</PanelHeader>
<PanelBody>
{subGroups.map(([email, subscriptions]) => (
- <React.Fragment key={email}>
+ <Fragment key={email}>
{subGroups.length > 1 && (
<Heading>
<IconToggle /> {t('Subscriptions for %s', email)}
@@ -145,7 +145,7 @@ class AccountSubscriptions extends AsyncView<AsyncView['props'], State> {
</div>
</PanelItem>
))}
- </React.Fragment>
+ </Fragment>
))}
</PanelBody>
</div>
diff --git a/static/app/views/settings/components/dataScrubbing/modals/modal.tsx b/static/app/views/settings/components/dataScrubbing/modals/modal.tsx
index f6791cb197021c..f4d063beb6d99f 100644
--- a/static/app/views/settings/components/dataScrubbing/modals/modal.tsx
+++ b/static/app/views/settings/components/dataScrubbing/modals/modal.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {ModalRenderProps} from 'sentry/actionCreators/modal';
import Button from 'sentry/components/button';
@@ -22,7 +22,7 @@ const Modal = ({
Footer,
closeModal,
}: Props) => (
- <React.Fragment>
+ <Fragment>
<Header closeButton>{title}</Header>
<Body>{content}</Body>
<Footer>
@@ -33,7 +33,7 @@ const Modal = ({
</Button>
</ButtonBar>
</Footer>
- </React.Fragment>
+ </Fragment>
);
export default Modal;
diff --git a/static/app/views/settings/components/settingsNavItem.tsx b/static/app/views/settings/components/settingsNavItem.tsx
index 98cafcc95936c5..9761b75959720d 100644
--- a/static/app/views/settings/components/settingsNavItem.tsx
+++ b/static/app/views/settings/components/settingsNavItem.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {Link as RouterLink} from 'react-router';
import styled from '@emotion/styled';
@@ -21,7 +21,7 @@ type Props = {
const SettingsNavItem = ({badge, label, index, id, ...props}: Props) => {
const LabelHook = HookOrDefault({
hookName: 'sidebar:item-label',
- defaultComponent: ({children}) => <React.Fragment>{children}</React.Fragment>,
+ defaultComponent: ({children}) => <Fragment>{children}</Fragment>,
});
let renderedBadge: React.ReactNode;
diff --git a/static/app/views/settings/organizationDeveloperSettings/sentryApplicationDashboard/requestLog.tsx b/static/app/views/settings/organizationDeveloperSettings/sentryApplicationDashboard/requestLog.tsx
index 81ddafa4d3a717..b490bc04793aed 100644
--- a/static/app/views/settings/organizationDeveloperSettings/sentryApplicationDashboard/requestLog.tsx
+++ b/static/app/views/settings/organizationDeveloperSettings/sentryApplicationDashboard/requestLog.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import memoize from 'lodash/memoize';
import moment from 'moment-timezone';
@@ -197,7 +197,7 @@ export default class RequestLog extends AsyncComponent<Props, State> {
);
return (
- <React.Fragment>
+ <Fragment>
<h5>{t('Request Log')}</h5>
<div>
@@ -292,7 +292,7 @@ export default class RequestLog extends AsyncComponent<Props, State> {
aria-label={t('Next page')}
/>
</PaginationButtons>
- </React.Fragment>
+ </Fragment>
);
}
}
diff --git a/static/app/views/settings/organizationDeveloperSettings/sentryApplicationDetails.tsx b/static/app/views/settings/organizationDeveloperSettings/sentryApplicationDetails.tsx
index f97a456f499ae1..6898481e126225 100644
--- a/static/app/views/settings/organizationDeveloperSettings/sentryApplicationDetails.tsx
+++ b/static/app/views/settings/organizationDeveloperSettings/sentryApplicationDetails.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {browserHistory, RouteComponentProps} from 'react-router';
import styled from '@emotion/styled';
import omit from 'lodash/omit';
@@ -421,7 +421,7 @@ export default class SentryApplicationDetails extends AsyncView<Props, State> {
const webhookDisabled =
this.isInternal && !this.form.getValue('webhookUrl');
return (
- <React.Fragment>
+ <Fragment>
<JsonForm additionalFieldProps={{webhookDisabled}} forms={forms} />
{this.getAvatarChooser(true)}
{this.getAvatarChooser(false)}
@@ -431,7 +431,7 @@ export default class SentryApplicationDetails extends AsyncView<Props, State> {
scopes={scopes}
events={events}
/>
- </React.Fragment>
+ </Fragment>
);
}}
</Observer>
diff --git a/static/app/views/settings/organizationMembers/inviteRequestRow.tsx b/static/app/views/settings/organizationMembers/inviteRequestRow.tsx
index 9b95c08f033132..c48dee14206ff0 100644
--- a/static/app/views/settings/organizationMembers/inviteRequestRow.tsx
+++ b/static/app/views/settings/organizationMembers/inviteRequestRow.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import Button from 'sentry/components/button';
@@ -124,12 +124,12 @@ const InviteRequestRow = ({
disableConfirmButton={!canSend}
disabled={!canApprove || roleDisallowed}
message={
- <React.Fragment>
+ <Fragment>
{tct('Are you sure you want to invite [email] to your organization?', {
email: inviteRequest.email,
})}
{headerInfo}
- </React.Fragment>
+ </Fragment>
}
>
<Button
diff --git a/static/app/views/settings/organizationMembers/organizationMembersList.tsx b/static/app/views/settings/organizationMembers/organizationMembersList.tsx
index a273476f95f20c..8b85b02f5c0bbf 100644
--- a/static/app/views/settings/organizationMembers/organizationMembersList.tsx
+++ b/static/app/views/settings/organizationMembers/organizationMembersList.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {RouteComponentProps} from 'react-router';
import {ClassNames} from '@emotion/react';
import styled from '@emotion/styled';
@@ -282,7 +282,7 @@ class OrganizationMembersList extends AsyncView<Props, State> {
);
return (
- <React.Fragment>
+ <Fragment>
<ClassNames>
{({css}) =>
this.renderSearchInput({
@@ -348,7 +348,7 @@ class OrganizationMembersList extends AsyncView<Props, State> {
</Panel>
<Pagination pageLinks={membersPageLinks} />
- </React.Fragment>
+ </Fragment>
);
}
}
diff --git a/static/app/views/settings/organizationProjects/index.tsx b/static/app/views/settings/organizationProjects/index.tsx
index 175acb1bdc67d1..8c3560171925f0 100644
--- a/static/app/views/settings/organizationProjects/index.tsx
+++ b/static/app/views/settings/organizationProjects/index.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {RouteComponentProps} from 'react-router';
import styled from '@emotion/styled';
import {Location} from 'history';
@@ -101,7 +101,7 @@ class OrganizationProjects extends AsyncView<Props, State> {
);
return (
- <React.Fragment>
+ <Fragment>
<SettingsPageHeader title="Projects" action={action} />
<SearchWrapper>
{this.renderSearchInput({
@@ -143,7 +143,7 @@ class OrganizationProjects extends AsyncView<Props, State> {
{projectListPageLinks && (
<Pagination pageLinks={projectListPageLinks} {...this.props} />
)}
- </React.Fragment>
+ </Fragment>
);
}
}
diff --git a/static/app/views/settings/organizationRelay/modals/modal.tsx b/static/app/views/settings/organizationRelay/modals/modal.tsx
index 3752d7ce99cb5b..f8374695fe7392 100644
--- a/static/app/views/settings/organizationRelay/modals/modal.tsx
+++ b/static/app/views/settings/organizationRelay/modals/modal.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {ModalRenderProps} from 'sentry/actionCreators/modal';
import Button from 'sentry/components/button';
@@ -24,7 +24,7 @@ const Modal = ({
closeModal,
btnSaveLabel = t('Save'),
}: Props) => (
- <React.Fragment>
+ <Fragment>
<Header closeButton>{title}</Header>
<Body>{content}</Body>
<Footer>
@@ -44,7 +44,7 @@ const Modal = ({
</Button>
</ButtonBar>
</Footer>
- </React.Fragment>
+ </Fragment>
);
export default Modal;
diff --git a/static/app/views/settings/project/filtersAndSampling/filtersAndSampling.tsx b/static/app/views/settings/project/filtersAndSampling/filtersAndSampling.tsx
index 6b49d07908fe07..3c29af818ef2c9 100644
--- a/static/app/views/settings/project/filtersAndSampling/filtersAndSampling.tsx
+++ b/static/app/views/settings/project/filtersAndSampling/filtersAndSampling.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import partition from 'lodash/partition';
import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
@@ -210,7 +210,7 @@ class FiltersAndSampling extends AsyncView<Props, State> {
}
return (
- <React.Fragment>
+ <Fragment>
<SettingsPageHeader title={this.getTitle()} />
<PermissionAlert />
<TextBlock>
@@ -243,7 +243,7 @@ class FiltersAndSampling extends AsyncView<Props, State> {
onDeleteRule={this.handleDeleteRule}
onUpdateRules={this.handleUpdateRules}
/>
- </React.Fragment>
+ </Fragment>
);
}
}
diff --git a/tests/js/spec/components/hovercard.spec.tsx b/tests/js/spec/components/hovercard.spec.tsx
index f5909742505079..56bd070b7cddd0 100644
--- a/tests/js/spec/components/hovercard.spec.tsx
+++ b/tests/js/spec/components/hovercard.spec.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react';
+import {Fragment} from 'react';
import {act, render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
@@ -15,7 +15,7 @@ describe('Hovercard', () => {
it('reuses portal', () => {
render(
- <React.Fragment>
+ <Fragment>
<Hovercard
position="top"
body="Hovercard Body"
@@ -32,7 +32,7 @@ describe('Hovercard', () => {
>
Hovercard Trigger
</Hovercard>
- </React.Fragment>
+ </Fragment>
);
// eslint-disable-next-line
|
81388224ed173f2605ef069616c9e540801a7bef
|
2022-07-26 20:57:20
|
Priscila Oliveira
|
ref(sampling): Attempt to fix e2e flaky test (#36790)
| false
|
Attempt to fix e2e flaky test (#36790)
|
ref
|
diff --git a/static/app/actionCreators/serverSideSampling.tsx b/static/app/actionCreators/serverSideSampling.tsx
index 7b0e73c5bca385..13ea912db3a3be 100644
--- a/static/app/actionCreators/serverSideSampling.tsx
+++ b/static/app/actionCreators/serverSideSampling.tsx
@@ -28,10 +28,17 @@ export function fetchSamplingSdkVersions({
}
);
- promise.then(ServerSideSamplingStore.loadSamplingSdkVersionsSuccess).catch(response => {
- const errorMessage = t('Unable to fetch sampling sdk versions');
- handleXhrErrorResponse(errorMessage)(response);
- });
+ ServerSideSamplingStore.setFetching(true);
+
+ promise
+ .then(ServerSideSamplingStore.loadSamplingSdkVersionsSuccess)
+ .catch(response => {
+ const errorMessage = t('Unable to fetch sampling sdk versions');
+ handleXhrErrorResponse(errorMessage)(response);
+ })
+ .finally(() => {
+ ServerSideSamplingStore.setFetching(false);
+ });
return promise;
}
@@ -47,6 +54,8 @@ export function fetchSamplingDistribution({
}): Promise<SamplingDistribution> {
ServerSideSamplingStore.reset();
+ ServerSideSamplingStore.setFetching(true);
+
const promise = api.requestPromise(
`/projects/${orgSlug}/${projSlug}/dynamic-sampling/distribution/`,
{
@@ -61,6 +70,9 @@ export function fetchSamplingDistribution({
.catch(response => {
const errorMessage = t('Unable to fetch sampling distribution');
handleXhrErrorResponse(errorMessage)(response);
+ })
+ .finally(() => {
+ ServerSideSamplingStore.setFetching(false);
});
return promise;
diff --git a/static/app/stores/serverSideSamplingStore.tsx b/static/app/stores/serverSideSamplingStore.tsx
index 50fac59107b8b7..d14e64c0a3c45a 100644
--- a/static/app/stores/serverSideSamplingStore.tsx
+++ b/static/app/stores/serverSideSamplingStore.tsx
@@ -6,6 +6,7 @@ import {makeSafeRefluxStore} from 'sentry/utils/makeSafeRefluxStore';
import {CommonStoreDefinition} from './types';
type State = {
+ fetching: boolean;
samplingDistribution: SamplingDistribution;
samplingSdkVersions: SamplingSdkVersion[];
};
@@ -14,12 +15,14 @@ interface ServerSideSamplingStoreDefinition extends CommonStoreDefinition<State>
loadSamplingDistributionSuccess(data: SamplingDistribution): void;
loadSamplingSdkVersionsSuccess(data: SamplingSdkVersion[]): void;
reset(): void;
+ setFetching(fetching: boolean): void;
}
const storeConfig: ServerSideSamplingStoreDefinition = {
state: {
samplingDistribution: {},
samplingSdkVersions: [],
+ fetching: false,
},
reset() {
@@ -34,6 +37,11 @@ const storeConfig: ServerSideSamplingStoreDefinition = {
return this.state;
},
+ setFetching(fetching: boolean) {
+ this.state.fetching = fetching;
+ this.trigger(this.state);
+ },
+
loadSamplingSdkVersionsSuccess(data: SamplingSdkVersion[]) {
this.state = {
...this.state,
diff --git a/static/app/views/settings/project/server-side-sampling/modals/uniformRateModal.tsx b/static/app/views/settings/project/server-side-sampling/modals/uniformRateModal.tsx
index d17706a40fcf72..c89663818e8d1b 100644
--- a/static/app/views/settings/project/server-side-sampling/modals/uniformRateModal.tsx
+++ b/static/app/views/settings/project/server-side-sampling/modals/uniformRateModal.tsx
@@ -86,11 +86,12 @@ function UniformRateModal({
statsPeriod: '30d',
});
- const {recommendedSdkUpgrades} = useRecommendedSdkUpgrades({
- orgSlug: organization.slug,
- });
+ const {recommendedSdkUpgrades, fetching: fetchingRecommendedSdkUpgrades} =
+ useRecommendedSdkUpgrades({
+ orgSlug: organization.slug,
+ });
- const loading = loading30d || !projectStats;
+ const loading = loading30d || !projectStats || fetchingRecommendedSdkUpgrades;
const [activeStep, setActiveStep] = useState<Step>(Step.SET_UNIFORM_SAMPLE_RATE);
diff --git a/static/app/views/settings/project/server-side-sampling/serverSideSampling.tsx b/static/app/views/settings/project/server-side-sampling/serverSideSampling.tsx
index 18570268dac6d1..d6178380cb82d2 100644
--- a/static/app/views/settings/project/server-side-sampling/serverSideSampling.tsx
+++ b/static/app/views/settings/project/server-side-sampling/serverSideSampling.tsx
@@ -113,9 +113,10 @@ export function ServerSideSampling({project}: Props) {
statsPeriod: '48h',
});
- const {recommendedSdkUpgrades} = useRecommendedSdkUpgrades({
- orgSlug: organization.slug,
- });
+ const {recommendedSdkUpgrades, fetching: fetchingRecommendedSdkUpgrades} =
+ useRecommendedSdkUpgrades({
+ orgSlug: organization.slug,
+ });
async function handleActivateToggle(rule: SamplingRule) {
const newRules = rules.map(r => {
@@ -410,7 +411,7 @@ export function ServerSideSampling({project}: Props) {
'These settings can only be edited by users with the organization owner, manager, or admin role.'
)}
/>
- {!!rules.length && (
+ {!!rules.length && !fetchingRecommendedSdkUpgrades && (
<SamplingSDKAlert
organization={organization}
projectId={project.id}
diff --git a/static/app/views/settings/project/server-side-sampling/utils/useRecommendedSdkUpgrades.tsx b/static/app/views/settings/project/server-side-sampling/utils/useRecommendedSdkUpgrades.tsx
index 1640bec4b6e245..33a090dee3bb49 100644
--- a/static/app/views/settings/project/server-side-sampling/utils/useRecommendedSdkUpgrades.tsx
+++ b/static/app/views/settings/project/server-side-sampling/utils/useRecommendedSdkUpgrades.tsx
@@ -9,7 +9,7 @@ type Props = {
};
export function useRecommendedSdkUpgrades({orgSlug}: Props) {
- const {samplingSdkVersions} = useLegacyStore(ServerSideSamplingStore);
+ const {samplingSdkVersions, fetching} = useLegacyStore(ServerSideSamplingStore);
const notSendingSampleRateSdkUpgrades = samplingSdkVersions.filter(
samplingSdkVersion => !samplingSdkVersion.isSendingSampleRate
@@ -39,5 +39,5 @@ export function useRecommendedSdkUpgrades({orgSlug}: Props) {
})
.filter(defined);
- return {recommendedSdkUpgrades};
+ return {recommendedSdkUpgrades, fetching};
}
diff --git a/tests/js/spec/views/settings/project/server-side-sampling/utils.tsx b/tests/js/spec/views/settings/project/server-side-sampling/utils.tsx
index aa020ae20e4e06..e8b858af6a1003 100644
--- a/tests/js/spec/views/settings/project/server-side-sampling/utils.tsx
+++ b/tests/js/spec/views/settings/project/server-side-sampling/utils.tsx
@@ -153,6 +153,7 @@ useRecommendedSdkUpgrades.mockImplementation(() => ({
latestSDKVersion: mockedSamplingSdkVersions[1].latestSDKVersion,
},
],
+ fetching: false,
}));
export function getMockData({
|
54e1b0ed820ef8b4bdea0c61d42330557e758590
|
2022-08-18 05:15:31
|
Evan Purkhiser
|
ref(js): Remove CommitterActions (#37964)
| false
|
Remove CommitterActions (#37964)
|
ref
|
diff --git a/static/app/actionCreators/committers.tsx b/static/app/actionCreators/committers.tsx
index 2728355e102053..d7692ec52bf1e8 100644
--- a/static/app/actionCreators/committers.tsx
+++ b/static/app/actionCreators/committers.tsx
@@ -1,4 +1,3 @@
-import CommitterActions from 'sentry/actions/committerActions';
import {Client} from 'sentry/api';
import CommitterStore, {getCommitterStoreKey} from 'sentry/stores/committerStore';
import {Committer} from 'sentry/types';
@@ -22,18 +21,18 @@ export function getCommitters(api: Client, params: ParamsGet) {
...CommitterStore.state[storeKey],
committersLoading: true,
};
- CommitterActions.load(orgSlug, projectSlug, eventId);
+ CommitterStore.load(orgSlug, projectSlug, eventId);
return api
.requestPromise(path, {
method: 'GET',
})
.then((res: {committers: Committer[]}) => {
- CommitterActions.loadSuccess(orgSlug, projectSlug, eventId, res.committers);
+ CommitterStore.loadSuccess(orgSlug, projectSlug, eventId, res.committers);
})
.catch(err => {
// NOTE: Do not captureException here as EventFileCommittersEndpoint returns
// 404 Not Found if the project did not setup Releases or Commits
- CommitterActions.loadError(orgSlug, projectSlug, eventId, err);
+ CommitterStore.loadError(orgSlug, projectSlug, eventId, err);
});
}
diff --git a/static/app/actions/committerActions.tsx b/static/app/actions/committerActions.tsx
deleted file mode 100644
index 85ca467829de99..00000000000000
--- a/static/app/actions/committerActions.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import {createActions} from 'reflux';
-
-const ComitterActions = createActions(['reset', 'load', 'loadError', 'loadSuccess']);
-
-export default ComitterActions;
diff --git a/static/app/stores/committerStore.tsx b/static/app/stores/committerStore.tsx
index 90d7c5b0cb0020..d17b5ea60c2ed3 100644
--- a/static/app/stores/committerStore.tsx
+++ b/static/app/stores/committerStore.tsx
@@ -1,6 +1,5 @@
import {createStore} from 'reflux';
-import CommitterActions from 'sentry/actions/committerActions';
import {Committer} from 'sentry/types';
import {makeSafeRefluxStore} from 'sentry/utils/makeSafeRefluxStore';
@@ -40,7 +39,6 @@ interface CommitterStoreDefinition extends Reflux.StoreDefinition {
}
export const storeConfig: CommitterStoreDefinition = {
- listenables: CommitterActions,
state: {},
init() {
diff --git a/tests/js/spec/actionCreators/committers.spec.jsx b/tests/js/spec/actionCreators/committers.spec.jsx
index 67c6735ced4608..799123f1bf7df3 100644
--- a/tests/js/spec/actionCreators/committers.spec.jsx
+++ b/tests/js/spec/actionCreators/committers.spec.jsx
@@ -1,5 +1,4 @@
import {getCommitters} from 'sentry/actionCreators/committers';
-import CommitterActions from 'sentry/actions/committerActions';
import CommitterStore, {getCommitterStoreKey} from 'sentry/stores/committerStore';
describe('CommitterActionCreator', function () {
@@ -31,8 +30,8 @@ describe('CommitterActionCreator', function () {
CommitterStore.init();
jest.restoreAllMocks();
- jest.spyOn(CommitterActions, 'load');
- jest.spyOn(CommitterActions, 'loadSuccess');
+ jest.spyOn(CommitterStore, 'load');
+ jest.spyOn(CommitterStore, 'loadSuccess');
/**
* XXX(leedongwei): We would want to ensure that Store methods are not
@@ -55,18 +54,18 @@ describe('CommitterActionCreator', function () {
projectSlug: project.slug,
eventId: event.id,
}); // Fire Action.load
- expect(CommitterActions.load).toHaveBeenCalledWith(
+ expect(CommitterStore.load).toHaveBeenCalledWith(
organization.slug,
project.slug,
event.id
);
- expect(CommitterActions.loadSuccess).not.toHaveBeenCalled();
+ expect(CommitterStore.loadSuccess).not.toHaveBeenCalled();
await tick(); // Run Store.load and fire Action.loadSuccess
await tick(); // Run Store.loadSuccess
expect(mockResponse).toHaveBeenCalledWith(endpoint, expect.anything());
- expect(CommitterActions.loadSuccess).toHaveBeenCalledWith(
+ expect(CommitterStore.loadSuccess).toHaveBeenCalledWith(
organization.slug,
project.slug,
event.id,
@@ -91,7 +90,7 @@ describe('CommitterActionCreator', function () {
eventId: event.id,
}); // Fire Action.load
- expect(CommitterActions.load).toHaveBeenCalled();
+ expect(CommitterStore.load).toHaveBeenCalled();
// expect(CommitterStore.load).not.toHaveBeenCalled();
expect(CommitterStore.state[storeKey].committersLoading).toEqual(true); // Short-circuit
});
|
6e60859e6f9123387f86f9dfe358ed6f3c10c66b
|
2024-12-10 00:27:36
|
Harshitha Durai
|
fix(dashboards): fix teams API request condition for Edit Access feature (#81867)
| false
|
fix teams API request condition for Edit Access feature (#81867)
|
fix
|
diff --git a/static/app/views/dashboards/editAccessSelector.tsx b/static/app/views/dashboards/editAccessSelector.tsx
index a0af8e8a8c799a..2ac341d5a877df 100644
--- a/static/app/views/dashboards/editAccessSelector.tsx
+++ b/static/app/views/dashboards/editAccessSelector.tsx
@@ -65,7 +65,9 @@ function EditAccessSelector({
const [isMenuOpen, setMenuOpen] = useState<boolean>(false);
const {teams: selectedTeam} = useTeamsById({
ids:
- selectedOptions[1] && selectedOptions[1] !== 'allUsers' ? [selectedOptions[1]] : [],
+ selectedOptions[1] && selectedOptions[1] !== '_allUsers'
+ ? [selectedOptions[1]]
+ : [],
});
// Gets selected options for the dropdown from dashboard object
|
7823ff0887f040c3a921240c7c0c3b7c65bc8fee
|
2020-10-31 02:04:20
|
aishchenko
|
fix(accounts): Prevent Referer leak on password reset page (#14913)
| false
|
Prevent Referer leak on password reset page (#14913)
|
fix
|
diff --git a/src/sentry/web/decorators.py b/src/sentry/web/decorators.py
index 04a79c17f64171..b1be87de8f58a1 100644
--- a/src/sentry/web/decorators.py
+++ b/src/sentry/web/decorators.py
@@ -40,6 +40,19 @@ def wrapped(request, *args, **kwargs):
return wrapped
+def set_referrer_policy(policy):
+ def real_decorator(func):
+ @wraps(func)
+ def wrapped(request, *args, **kwargs):
+ response = func(request, *args, **kwargs)
+ response["Referrer-Policy"] = policy
+ return response
+
+ return wrapped
+
+ return real_decorator
+
+
def transaction_start(endpoint):
def decorator(func):
@wraps(func)
diff --git a/src/sentry/web/frontend/accounts.py b/src/sentry/web/frontend/accounts.py
index 6f54f46a5fc12a..759b9468de42c0 100644
--- a/src/sentry/web/frontend/accounts.py
+++ b/src/sentry/web/frontend/accounts.py
@@ -17,7 +17,7 @@
from sentry.models import UserEmail, LostPasswordHash, Project, UserOption, Authenticator
from sentry.security import capture_security_activity
from sentry.signals import email_verified
-from sentry.web.decorators import login_required, signed_auth_required
+from sentry.web.decorators import login_required, signed_auth_required, set_referrer_policy
from sentry.web.forms.accounts import RecoverPasswordForm, ChangePasswordRecoverForm
from sentry.web.helpers import render_to_response
from sentry.utils import auth
@@ -25,6 +25,10 @@
logger = logging.getLogger("sentry.accounts")
+def get_template(mode, name):
+ return u"sentry/account/{}/{}.html".format(mode, name)
+
+
@login_required
def login_redirect(request):
login_url = auth.get_login_redirect(request)
@@ -36,7 +40,7 @@ def expired(request, user):
password_hash.send_email(request)
context = {"email": password_hash.user.email}
- return render_to_response("sentry/account/recover/expired.html", context, request)
+ return render_to_response(get_template("recover", "expired"), context, request)
def recover(request):
@@ -76,20 +80,19 @@ def recover(request):
logger.info("recover.sent", extra=extra)
- tpl = "sentry/account/recover/sent.html"
context = {"email": email}
- return render_to_response(tpl, context, request)
+ return render_to_response(get_template("recover", "sent"), context, request)
if form._errors:
logger.warning("recover.error", extra=extra)
- tpl = "sentry/account/recover/index.html"
context = {"form": form}
- return render_to_response(tpl, context, request)
+ return render_to_response(get_template("recover", "index"), context, request)
+@set_referrer_policy("strict-origin-when-cross-origin")
def recover_confirm(request, user_id, hash, mode="recover"):
try:
password_hash = LostPasswordHash.objects.get(user=user_id, hash=hash)
@@ -99,7 +102,7 @@ def recover_confirm(request, user_id, hash, mode="recover"):
user = password_hash.user
except LostPasswordHash.DoesNotExist:
- return render_to_response(u"sentry/account/{}/{}.html".format(mode, "failure"), {}, request)
+ return render_to_response(get_template(mode, "failure"), {}, request)
if request.method == "POST":
form = ChangePasswordRecoverForm(request.POST)
@@ -131,9 +134,7 @@ def recover_confirm(request, user_id, hash, mode="recover"):
else:
form = ChangePasswordRecoverForm()
- return render_to_response(
- u"sentry/account/{}/{}.html".format(mode, "confirm"), {"form": form}, request
- )
+ return render_to_response(get_template(mode, "confirm"), {"form": form}, request)
# Set password variation of password recovery
@@ -189,6 +190,7 @@ def start_confirm_email(request):
return HttpResponseRedirect(reverse("sentry-account-settings-emails"))
+@set_referrer_policy("strict-origin-when-cross-origin")
def confirm_email(request, user_id, hash):
msg = _("Thanks for confirming your email")
level = messages.SUCCESS
diff --git a/tests/sentry/web/frontend/test_accounts.py b/tests/sentry/web/frontend/test_accounts.py
index 73b053e01394a1..2d7e4e07ad4ed7 100644
--- a/tests/sentry/web/frontend/test_accounts.py
+++ b/tests/sentry/web/frontend/test_accounts.py
@@ -12,6 +12,9 @@ class TestAccounts(TestCase):
def path(self):
return reverse("sentry-account-recover")
+ def password_recover_path(self, user_id, hash_):
+ return reverse("sentry-account-recover-confirm", kwargs={"user_id": user_id, "hash": hash_})
+
def test_get_renders_form(self):
resp = self.client.get(self.path)
assert resp.status_code == 200
@@ -55,3 +58,21 @@ def test_post_multiple_users(self):
assert resp.status_code == 200
self.assertTemplateUsed("sentry/account/recover/index.html")
assert 0 == len(LostPasswordHash.objects.all())
+
+ def test_leaking_recovery_hash(self):
+ user = self.create_user()
+
+ resp = self.client.post(self.path, {"user": user.email})
+ assert resp.status_code == 200
+
+ lost_password = LostPasswordHash.objects.get(user=user)
+
+ resp = self.client.post(
+ self.password_recover_path(lost_password.user_id, lost_password.hash),
+ {"password": "test_password"},
+ )
+
+ header_name = "Referrer-Policy"
+
+ assert resp.has_header(header_name)
+ assert resp[header_name] == "strict-origin-when-cross-origin"
|
e7884fa9c5c79e02e52ab2b62770eece3c77b37f
|
2024-09-30 23:32:55
|
Evan Purkhiser
|
feat(uptime): Add environmnet column (#78332)
| false
|
Add environmnet column (#78332)
|
feat
|
diff --git a/fixtures/backup/model_dependencies/detailed.json b/fixtures/backup/model_dependencies/detailed.json
index 89a693a0004245..ef6c4f4b6af0e9 100644
--- a/fixtures/backup/model_dependencies/detailed.json
+++ b/fixtures/backup/model_dependencies/detailed.json
@@ -6171,6 +6171,11 @@
"uptime.projectuptimesubscription": {
"dangling": false,
"foreign_keys": {
+ "environment": {
+ "kind": "FlexibleForeignKey",
+ "model": "sentry.environment",
+ "nullable": true
+ },
"owner_team": {
"kind": "FlexibleForeignKey",
"model": "sentry.team",
diff --git a/fixtures/backup/model_dependencies/flat.json b/fixtures/backup/model_dependencies/flat.json
index d54304bb0797ca..79f148f8dfe22c 100644
--- a/fixtures/backup/model_dependencies/flat.json
+++ b/fixtures/backup/model_dependencies/flat.json
@@ -850,6 +850,7 @@
"sentry.user"
],
"uptime.projectuptimesubscription": [
+ "sentry.environment",
"sentry.project",
"sentry.team",
"sentry.user",
diff --git a/migrations_lockfile.txt b/migrations_lockfile.txt
index eae9894cf5a441..77523d6ec01735 100644
--- a/migrations_lockfile.txt
+++ b/migrations_lockfile.txt
@@ -12,5 +12,5 @@ remote_subscriptions: 0003_drop_remote_subscription
replays: 0004_index_together
sentry: 0769_add_seer_fields_to_grouphash_metadata
social_auth: 0002_default_auto_field
-uptime: 0013_uptime_subscription_new_unique
+uptime: 0014_add_uptime_enviromnet
workflow_engine: 0007_loosen_workflow_action_relationship
diff --git a/src/sentry/uptime/migrations/0014_add_uptime_enviromnet.py b/src/sentry/uptime/migrations/0014_add_uptime_enviromnet.py
new file mode 100644
index 00000000000000..a4d8ba9f26f786
--- /dev/null
+++ b/src/sentry/uptime/migrations/0014_add_uptime_enviromnet.py
@@ -0,0 +1,41 @@
+# Generated by Django 5.1.1 on 2024-09-30 16:23
+
+import django.db.models.deletion
+from django.db import migrations
+
+import sentry.db.models.fields.foreignkey
+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 = False
+
+ dependencies = [
+ ("sentry", "0768_fix_old_group_first_seen_dates"),
+ ("uptime", "0013_uptime_subscription_new_unique"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="projectuptimesubscription",
+ name="environment",
+ field=sentry.db.models.fields.foreignkey.FlexibleForeignKey(
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="sentry.environment",
+ ),
+ ),
+ ]
diff --git a/src/sentry/uptime/models.py b/src/sentry/uptime/models.py
index 20a34e666c3709..42b0a6a9c12d5c 100644
--- a/src/sentry/uptime/models.py
+++ b/src/sentry/uptime/models.py
@@ -100,6 +100,9 @@ class ProjectUptimeSubscription(DefaultFieldsModelExisting):
__relocation_scope__ = RelocationScope.Excluded
project = FlexibleForeignKey("sentry.Project")
+ environment = FlexibleForeignKey(
+ "sentry.Environment", db_index=True, db_constraint=False, null=True
+ )
uptime_subscription = FlexibleForeignKey("uptime.UptimeSubscription", on_delete=models.PROTECT)
mode = models.SmallIntegerField(default=ProjectUptimeSubscriptionMode.MANUAL.value)
uptime_status = models.PositiveSmallIntegerField(default=UptimeStatus.OK.value)
diff --git a/tests/sentry/backup/snapshots/test_comparators/test_default_comparators.pysnap b/tests/sentry/backup/snapshots/test_comparators/test_default_comparators.pysnap
index 31b2d169a6b0eb..4f7e804c47dd48 100644
--- a/tests/sentry/backup/snapshots/test_comparators/test_default_comparators.pysnap
+++ b/tests/sentry/backup/snapshots/test_comparators/test_default_comparators.pysnap
@@ -1,5 +1,5 @@
---
-created: '2024-09-27T21:32:53.399200+00:00'
+created: '2024-09-30T17:27:03.064802+00:00'
creator: sentry
source: tests/sentry/backup/test_comparators.py
---
@@ -1603,6 +1603,7 @@ source: tests/sentry/backup/test_comparators.py
- comparators:
- class: ForeignKeyComparator
fields:
+ - environment
- owner_team
- owner_user_id
- project
|
5b462a80a9f06563a77bd4b86c6cf080d090b615
|
2020-01-22 23:50:46
|
Chris Fuller
|
feat(workflow): Quick and dirty alert rule trigger action descriptions (#16461)
| false
|
Quick and dirty alert rule trigger action descriptions (#16461)
|
feat
|
diff --git a/src/sentry/api/serializers/models/alert_rule_trigger_action.py b/src/sentry/api/serializers/models/alert_rule_trigger_action.py
index 5c3e6178bd4399..6c69324e6f80e7 100644
--- a/src/sentry/api/serializers/models/alert_rule_trigger_action.py
+++ b/src/sentry/api/serializers/models/alert_rule_trigger_action.py
@@ -8,6 +8,19 @@
@register(AlertRuleTriggerAction)
class AlertRuleTriggerActionSerializer(Serializer):
+ def human_desc(self, action):
+ # Returns a human readable description to display in the UI
+ if action.type == action.Type.EMAIL.value:
+ if action.target:
+ if action.target_type == action.TargetType.USER.value:
+ return "Send an email to " + action.target.email
+ elif action.target_type == action.TargetType.TEAM.value:
+ return "Send an email to members of #" + action.target.slug
+ elif action.type == action.Type.PAGERDUTY.value:
+ return "Send a PagerDuty notification to " + action.target_display
+ elif action.type == action.Type.SLACK.value:
+ return "Send a Slack notificaiton to " + action.target_display
+
def serialize(self, obj, attrs, user):
from sentry.incidents.endpoints.serializers import action_target_type_to_string
@@ -25,4 +38,5 @@ def serialize(self, obj, attrs, user):
else obj.target_identifier,
"integrationId": obj.integration_id,
"dateCreated": obj.date_added,
+ "desc": self.human_desc(obj),
}
diff --git a/src/sentry/static/sentry/app/views/settings/incidentRules/types.tsx b/src/sentry/static/sentry/app/views/settings/incidentRules/types.tsx
index bd18faf90a3dff..39767603076c34 100644
--- a/src/sentry/static/sentry/app/views/settings/incidentRules/types.tsx
+++ b/src/sentry/static/sentry/app/views/settings/incidentRules/types.tsx
@@ -96,4 +96,7 @@ export type Action = {
// How to identify the target. Can be email, slack channel, pagerduty service, user_id, team_id, etc
targetIdentifier: string | null;
+
+ // Human readable string describing what the action does.
+ desc: string | null;
};
diff --git a/src/sentry/static/sentry/app/views/settings/projectAlerts/ruleRowNew.tsx b/src/sentry/static/sentry/app/views/settings/projectAlerts/ruleRowNew.tsx
index cd1958e10b2b94..c7912b46afa037 100644
--- a/src/sentry/static/sentry/app/views/settings/projectAlerts/ruleRowNew.tsx
+++ b/src/sentry/static/sentry/app/views/settings/projectAlerts/ruleRowNew.tsx
@@ -120,7 +120,7 @@ class RuleRow extends React.Component<Props, State> {
<div>
{trigger.actions &&
trigger.actions.map((action, j) => (
- <div key={j}>{action.type}</div>
+ <div key={j}>{action.desc}</div>
))}
</div>
</TriggerAndActions>
|
e1d1b23ef4a856062d7ae424c7ff9c4303a9fa04
|
2023-06-08 01:21:34
|
anthony sottile
|
ref: fix linting errors after moving cloudbuild files (#50511)
| false
|
fix linting errors after moving cloudbuild files (#50511)
|
ref
|
diff --git a/src/sentry/runner/commands/devservices.py b/src/sentry/runner/commands/devservices.py
index 94be37c192bf75..b29209858402aa 100644
--- a/src/sentry/runner/commands/devservices.py
+++ b/src/sentry/runner/commands/devservices.py
@@ -491,6 +491,7 @@ def rm(project: str, services: list[str]) -> None:
an explicit list of services to remove.
"""
from docker.errors import NotFound
+
from sentry.runner import configure
configure()
|
294de6ffee463c212f2388ec63bd7b542e14a95a
|
2023-06-12 22:17:50
|
Shruthi
|
feat(starfish): Add the delta columns to WSV (#50739)
| false
|
Add the delta columns to WSV (#50739)
|
feat
|
diff --git a/static/app/views/starfish/utils/generatePerformanceEventView.tsx b/static/app/views/starfish/utils/generatePerformanceEventView.tsx
index 4b096598672ad8..3970852fceb641 100644
--- a/static/app/views/starfish/utils/generatePerformanceEventView.tsx
+++ b/static/app/views/starfish/utils/generatePerformanceEventView.tsx
@@ -125,8 +125,11 @@ export function generateWebServiceEventView(
'transaction',
'http.method',
'tps()',
+ 'tps_percent_change()',
'p95(transaction.duration)',
+ 'percentile_percent_change(transaction.duration,0.95)',
'http_error_count()',
+ 'http_error_count_percent_change()',
'time_spent_percentage()',
'sum(transaction.duration)',
];
diff --git a/static/app/views/starfish/views/webServiceView/endpointList.tsx b/static/app/views/starfish/views/webServiceView/endpointList.tsx
index 71854f22962442..ffb9e0cd1e97e6 100644
--- a/static/app/views/starfish/views/webServiceView/endpointList.tsx
+++ b/static/app/views/starfish/views/webServiceView/endpointList.tsx
@@ -33,10 +33,13 @@ import {DataTitles} from 'sentry/views/starfish/views/spans/types';
import {EndpointDataRow} from 'sentry/views/starfish/views/webServiceView/endpointDetails';
const COLUMN_TITLES = [
- 'Endpoint',
+ t('Endpoint'),
DataTitles.throughput,
+ t('Change'),
DataTitles.p95,
+ t('Change'),
DataTitles.errorCount,
+ t('Change'),
DataTitles.timeSpent,
];
@@ -131,21 +134,38 @@ function EndpointList({eventView, location, organization, setError}: Props) {
}
if (
- field.startsWith(
- 'equation|(percentile_range(transaction.duration,0.95,lessOrEquals,'
- )
+ [
+ 'percentile_percent_change(transaction.duration,0.95)',
+ 'http_error_count_percent_change()',
+ ].includes(field)
) {
const deltaValue = dataRow[field] as number;
const trendDirection = deltaValue < 0 ? 'good' : deltaValue > 0 ? 'bad' : 'neutral';
return (
<NumberContainer>
- <TrendingDuration trendDirection={trendDirection}>
+ <PercentChangeCell trendDirection={trendDirection}>
+ {tct('[sign][delta]', {
+ sign: deltaValue >= 0 ? '+' : '-',
+ delta: formatPercentage(Math.abs(deltaValue), 2),
+ })}
+ </PercentChangeCell>
+ </NumberContainer>
+ );
+ }
+
+ if (field === 'tps_percent_change()') {
+ const deltaValue = dataRow[field] as number;
+ const trendDirection = deltaValue > 0 ? 'good' : deltaValue < 0 ? 'bad' : 'neutral';
+
+ return (
+ <NumberContainer>
+ <PercentChangeCell trendDirection={trendDirection}>
{tct('[sign][delta]', {
sign: deltaValue >= 0 ? '+' : '-',
delta: formatPercentage(Math.abs(deltaValue), 2),
})}
- </TrendingDuration>
+ </PercentChangeCell>
</NumberContainer>
);
}
@@ -319,7 +339,9 @@ function EndpointList({eventView, location, organization, setError}: Props) {
export default EndpointList;
-const TrendingDuration = styled('div')<{trendDirection: 'good' | 'bad' | 'neutral'}>`
+export const PercentChangeCell = styled('div')<{
+ trendDirection: 'good' | 'bad' | 'neutral';
+}>`
color: ${p =>
p.trendDirection === 'good'
? p.theme.successText
diff --git a/static/app/views/starfish/views/webServiceView/failureDetailPanel/failureDetailTable.tsx b/static/app/views/starfish/views/webServiceView/failureDetailPanel/failureDetailTable.tsx
index 58cdca9558c3c6..401f83b37eaa8a 100644
--- a/static/app/views/starfish/views/webServiceView/failureDetailPanel/failureDetailTable.tsx
+++ b/static/app/views/starfish/views/webServiceView/failureDetailPanel/failureDetailTable.tsx
@@ -7,13 +7,16 @@ import GridEditable, {GridColumnHeader} from 'sentry/components/gridEditable';
import {Alignments} from 'sentry/components/gridEditable/sortLink';
import Link from 'sentry/components/links/link';
import Pagination from 'sentry/components/pagination';
-import {t} from 'sentry/locale';
+import {t, tct} from 'sentry/locale';
import {Organization} from 'sentry/types';
import {TableData, TableDataRow} from 'sentry/utils/discover/discoverQuery';
import EventView from 'sentry/utils/discover/eventView';
import {getFieldRenderer} from 'sentry/utils/discover/fieldRenderers';
+import {NumberContainer} from 'sentry/utils/discover/styles';
+import {formatPercentage} from 'sentry/utils/formatters';
import {TableColumn} from 'sentry/views/discover/table/types';
import {EndpointDataRow} from 'sentry/views/starfish/views/endpointDetails';
+import {PercentChangeCell} from 'sentry/views/starfish/views/webServiceView/endpointList';
import {FailureSpike} from 'sentry/views/starfish/views/webServiceView/types';
type Props = {
@@ -30,12 +33,17 @@ const COLUMN_ORDER = [
{
key: 'transaction',
name: t('Endpoint'),
- width: 400,
+ width: 450,
},
{
key: 'http_error_count()',
name: t('5xx Responses'),
- width: 100,
+ width: 150,
+ },
+ {
+ key: 'http_error_count_percent_change()',
+ name: t('Change'),
+ width: 80,
},
];
@@ -67,7 +75,7 @@ export default function FailureDetailTable({
const fieldRenderer = getFieldRenderer(field, tableData.meta, false);
const rendered = fieldRenderer(dataRow, {organization, location});
- if (column.key === 'transaction') {
+ if (field === 'transaction') {
const prefix = dataRow['http.method'] ? `${dataRow['http.method']} ` : '';
const queryParams = {
start: spike ? new Date(spike.startTimestamp) : undefined,
@@ -82,6 +90,22 @@ export default function FailureDetailTable({
);
}
+ if (field === 'http_error_count_percent_change()') {
+ const deltaValue = dataRow[field] as number;
+ const trendDirection = deltaValue < 0 ? 'good' : deltaValue > 0 ? 'bad' : 'neutral';
+
+ return (
+ <NumberContainer>
+ <PercentChangeCell trendDirection={trendDirection}>
+ {tct('[sign][delta]', {
+ sign: deltaValue >= 0 ? '+' : '-',
+ delta: formatPercentage(Math.abs(deltaValue), 2),
+ })}
+ </PercentChangeCell>
+ </NumberContainer>
+ );
+ }
+
return rendered;
}
|
1c4c2afcc5347b8277b692a33aa0b55314b518ea
|
2023-05-18 03:24:54
|
David Wang
|
ref(crons): Change Recent Check-Ins to Check-Ins (#49365)
| false
|
Change Recent Check-Ins to Check-Ins (#49365)
|
ref
|
diff --git a/static/app/views/monitors/components/monitorStats.tsx b/static/app/views/monitors/components/monitorStats.tsx
index 6c56585a4fd453..a18bc3d2af9739 100644
--- a/static/app/views/monitors/components/monitorStats.tsx
+++ b/static/app/views/monitors/components/monitorStats.tsx
@@ -120,7 +120,7 @@ function MonitorStats({monitor, monitorEnvs, orgId}: Props) {
<React.Fragment>
<Panel>
<PanelBody withPadding>
- <StyledHeaderTitle>{t('Recent Check-Ins')}</StyledHeaderTitle>
+ <StyledHeaderTitle>{t('Check-Ins')}</StyledHeaderTitle>
<BarChart
isGroupedByDate
showTimeInTooltip
|
3b167a556ffc0064753eb5982aaac395be37bd5d
|
2022-12-09 08:56:37
|
Richard Gibert
|
fix(createuser): Fix email prompt return (#42200)
| false
|
Fix email prompt return (#42200)
|
fix
|
diff --git a/src/sentry/runner/commands/createuser.py b/src/sentry/runner/commands/createuser.py
index aef6e9aa1eff40..862590e594fc79 100644
--- a/src/sentry/runner/commands/createuser.py
+++ b/src/sentry/runner/commands/createuser.py
@@ -15,7 +15,7 @@ def _get_email():
rv = click.prompt("Email")
field = _get_field("email")
try:
- return field.clean(rv, None)
+ return [field.clean(rv, None)]
except ValidationError as e:
raise click.ClickException("; ".join(e.messages))
|
732d636d7306dc567c7e251fdba98331c0017ba0
|
2025-01-10 19:42:23
|
Armen Zambrano G.
|
chore(ci): Upgrade to supported actions/cache version (#83226)
| false
|
Upgrade to supported actions/cache version (#83226)
|
chore
|
diff --git a/.github/workflows/acceptance.yml b/.github/workflows/acceptance.yml
index f72739d777cf4e..7e0347f75fa854 100644
--- a/.github/workflows/acceptance.yml
+++ b/.github/workflows/acceptance.yml
@@ -78,13 +78,13 @@ jobs:
echo "WEBPACK_CACHE_PATH=.webpack_cache" >> "$GITHUB_ENV"
- name: webpack cache
- uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0
+ uses: actions/[email protected]
with:
path: ${{ steps.config.outputs.webpack-path }}
key: ${{ runner.os }}-v2-webpack-cache-${{ hashFiles('webpack.config.ts') }}
- name: node_modules cache
- uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0
+ uses: actions/[email protected]
id: nodemodulescache
with:
path: node_modules
diff --git a/.github/workflows/frontend.yml b/.github/workflows/frontend.yml
index fc1a79c0a975f3..4cd7fdd64217d9 100644
--- a/.github/workflows/frontend.yml
+++ b/.github/workflows/frontend.yml
@@ -53,7 +53,7 @@ jobs:
node-version-file: '.volta.json'
- name: node_modules cache
- uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0
+ uses: actions/[email protected]
id: nodemodulescache
with:
path: node_modules
@@ -102,7 +102,7 @@ jobs:
node-version-file: '.volta.json'
- name: node_modules cache
- uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0
+ uses: actions/[email protected]
id: nodemodulescache
with:
path: node_modules
diff --git a/.github/workflows/jest-balance.yml b/.github/workflows/jest-balance.yml
index 99547f016bb96a..6b6f5ad40fbee4 100644
--- a/.github/workflows/jest-balance.yml
+++ b/.github/workflows/jest-balance.yml
@@ -19,7 +19,7 @@ jobs:
node-version-file: '.volta.json'
- name: node_modules cache
- uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0
+ uses: actions/[email protected]
id: nodemodulescache
with:
path: node_modules
diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml
index 8e90f1dc51ca76..bb04fbc502ce4c 100644
--- a/.github/workflows/pre-commit.yml
+++ b/.github/workflows/pre-commit.yml
@@ -59,7 +59,7 @@ jobs:
node-version-file: '.volta.json'
- name: node_modules cache
- uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0
+ uses: actions/[email protected]
id: nodemodulescache
with:
path: node_modules
@@ -76,7 +76,7 @@ jobs:
requirements-dev.txt
requirements-dev-frozen.txt
install-cmd: pip install -r requirements-dev.txt -c requirements-dev-frozen.txt
- - uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0
+ - uses: actions/[email protected]
with:
path: ~/.cache/pre-commit
key: cache-epoch-1|${{ env.pythonLocation }}|${{ hashFiles('.pre-commit-config.yaml') }}
diff --git a/.github/workflows/self-hosted.yml b/.github/workflows/self-hosted.yml
index 730796960b05a2..d218104b912e1c 100644
--- a/.github/workflows/self-hosted.yml
+++ b/.github/workflows/self-hosted.yml
@@ -42,13 +42,13 @@ jobs:
echo "WEBPACK_CACHE_PATH=.webpack_cache" >> "$GITHUB_ENV"
- name: webpack cache
- uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0
+ uses: actions/[email protected]
with:
path: ${{ steps.config.outputs.webpack-path }}
key: ${{ runner.os }}-self-hosted-webpack-cache-${{ hashFiles('webpack.config.ts') }}
- name: node_modules cache
- uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0
+ uses: actions/[email protected]
id: nodemodulescache
with:
path: node_modules
diff --git a/.github/workflows/test_devservices_acceptance.yml b/.github/workflows/test_devservices_acceptance.yml
index 279c41114d277c..03e6f8a9b4c922 100644
--- a/.github/workflows/test_devservices_acceptance.yml
+++ b/.github/workflows/test_devservices_acceptance.yml
@@ -57,13 +57,13 @@ jobs:
echo "WEBPACK_CACHE_PATH=.webpack_cache" >> "$GITHUB_ENV"
- name: webpack cache
- uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0
+ uses: actions/[email protected]
with:
path: ${{ steps.config.outputs.webpack-path }}
key: ${{ runner.os }}-v2-webpack-cache-${{ hashFiles('webpack.config.ts') }}
- name: node_modules cache
- uses: actions/cache@13aacd865c20de90d75de3b17ebe84f7a17d57d2 # v4.0.0
+ uses: actions/[email protected]
id: nodemodulescache
with:
path: node_modules
|
d9ff941b2e8639f5fa1b690068b266d676314fd0
|
2022-10-06 23:44:34
|
Dameli Ushbayeva
|
fix(discover): Handle undefined case for column text (#39764)
| false
|
Handle undefined case for column text (#39764)
|
fix
|
diff --git a/static/app/utils/discover/fields.tsx b/static/app/utils/discover/fields.tsx
index 4a3a9a237debae..87ba687c868096 100644
--- a/static/app/utils/discover/fields.tsx
+++ b/static/app/utils/discover/fields.tsx
@@ -688,7 +688,7 @@ export function parseArguments(functionText: string, columnText: string): string
(functionText !== 'to_other' &&
functionText !== 'count_if' &&
functionText !== 'spans_histogram') ||
- columnText.length === 0
+ columnText?.length === 0
) {
return columnText ? columnText.split(',').map(result => result.trim()) : [];
}
|
461ca768ffdc995843ccd2b593fe4017b6af85ae
|
2020-07-02 00:10:50
|
Stephen Cefali
|
feat(vercel): update Vercel description (#19645)
| false
|
update Vercel description (#19645)
|
feat
|
diff --git a/src/sentry/integrations/vercel/integration.py b/src/sentry/integrations/vercel/integration.py
index e982b57a0d1af1..f1a20bbf465e0f 100644
--- a/src/sentry/integrations/vercel/integration.py
+++ b/src/sentry/integrations/vercel/integration.py
@@ -34,13 +34,13 @@
logger = logging.getLogger("sentry.integrations.vercel")
DESCRIPTION = """
-VERCEL DESC
+Vercel is an all-in-one platform with Global CDN supporting static & JAMstack deployment and Serverless Functions.
"""
FEATURES = [
FeatureDescription(
"""
- DEPLOYMENT DESCRIPTION
+ Connect your Sentry and Vercel projects to automatically upload source maps and notify Sentry of new releases being deployed.
""",
IntegrationFeatures.DEPLOYMENT,
),
|
6da68d18604b26c65ead5573237f7095bac1981d
|
2024-01-24 16:39:49
|
Iker Barriocanal
|
ref(tx-clusterer): Increase soft limit timeout to 0.3s/project (#63738)
| false
|
Increase soft limit timeout to 0.3s/project (#63738)
|
ref
|
diff --git a/src/sentry/ingest/transaction_clusterer/tasks.py b/src/sentry/ingest/transaction_clusterer/tasks.py
index cc973499a98f8e..deac6be19d0536 100644
--- a/src/sentry/ingest/transaction_clusterer/tasks.py
+++ b/src/sentry/ingest/transaction_clusterer/tasks.py
@@ -36,7 +36,7 @@
#: Estimated limit for a clusterer run per project, in seconds.
#: NOTE: using this in a per-project basis may not be enough. Consider using
#: this estimation for project batches instead.
-CLUSTERING_TIMEOUT_PER_PROJECT = 0.15
+CLUSTERING_TIMEOUT_PER_PROJECT = 0.3
@instrumented_task(
|
98c53b2db68fcfbda858105a69bf3a88d3555b9b
|
2018-12-07 23:58:06
|
Billy Vong
|
ref(health): Remove health ☠️ (#10953)
| false
|
Remove health ☠️ (#10953)
|
ref
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index ee459fccfb820c..2a9106fc1bcfe3 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -787,8 +787,6 @@ def create_partitioned_queues(name):
'organizations:global-views': False,
# Enable the interface and functionality for unmerging event groups.
'organizations:group-unmerge': False,
- # Enable the 'health' interface.
- 'organizations:health': False,
# Enable integration functionality to create and link groups to issues on
# external services.
'organizations:integrations-issue-basic': False,
diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py
index 8907f5e4393fc8..5343b98dc6b149 100644
--- a/src/sentry/features/__init__.py
+++ b/src/sentry/features/__init__.py
@@ -56,7 +56,6 @@
default_manager.add('organizations:event-attachments', OrganizationFeature) # NOQA
default_manager.add('organizations:global-views', OrganizationFeature) # NOQA
default_manager.add('organizations:group-unmerge', OrganizationFeature) # NOQA
-default_manager.add('organizations:health', OrganizationFeature) # NOQA
default_manager.add('organizations:integrations-issue-basic', OrganizationFeature) # NOQA
default_manager.add('organizations:integrations-issue-sync', OrganizationFeature) # NOQA
default_manager.add('organizations:internal-catchall', OrganizationFeature) # NOQA
diff --git a/src/sentry/static/sentry/app/routes.jsx b/src/sentry/static/sentry/app/routes.jsx
index f8ed22c5a667dc..6343d295dbbe34 100644
--- a/src/sentry/static/sentry/app/routes.jsx
+++ b/src/sentry/static/sentry/app/routes.jsx
@@ -784,46 +784,6 @@ function routes() {
/>
</Route>
- <Route
- path="/organizations/:orgId/health/"
- componentPromise={() =>
- import(/*webpackChunkName: "OrganizationHealth"*/ './views/organizationHealth')}
- component={errorHandler(LazyLoad)}
- >
- <IndexRoute
- componentPromise={() =>
- import(/*webpackChunkName: "HealthOverview"*/ './views/organizationHealth/overview')}
- component={errorHandler(LazyLoad)}
- />
- <Route
- path="errors"
- componentPromise={() =>
- import(/*webpackChunkName: "HealthErrors"*/ './views/organizationHealth/errors')}
- component={errorHandler(LazyLoad)}
- />
-
- <Route
- path="transactions"
- componentPromise={() =>
- import(/*webpackChunkName: "HealthTransactions"*/ './views/organizationHealth/transactions')}
- component={errorHandler(LazyLoad)}
- />
-
- <Route
- path="browsers"
- componentPromise={() =>
- import(/*webpackChunkName: "HealthBrowsers"*/ './views/organizationHealth/browsers')}
- component={errorHandler(LazyLoad)}
- />
-
- <Route
- path="devices"
- componentPromise={() =>
- import(/*webpackChunkName: "HealthDevices"*/ './views/organizationHealth/devices')}
- component={errorHandler(LazyLoad)}
- />
- </Route>
-
<Route
path="/organizations/:orgId/teams/new/"
componentPromise={() =>
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/loadingPanel.jsx b/src/sentry/static/sentry/app/views/organizationEvents/loadingPanel.jsx
similarity index 76%
rename from src/sentry/static/sentry/app/views/organizationHealth/loadingPanel.jsx
rename to src/sentry/static/sentry/app/views/organizationEvents/loadingPanel.jsx
index a37c6bac1d997c..a269e5677802d1 100644
--- a/src/sentry/static/sentry/app/views/organizationHealth/loadingPanel.jsx
+++ b/src/sentry/static/sentry/app/views/organizationEvents/loadingPanel.jsx
@@ -1,8 +1,6 @@
import React from 'react';
import styled from 'react-emotion';
-import HealthPanelChart from 'app/views/organizationHealth/styles/healthPanelChart';
-
const LoadingMask = styled('div')`
background-color: ${p => p.theme.offWhite};
border-radius: ${p => p.theme.borderRadius};
@@ -14,11 +12,13 @@ const LoadingMask = styled('div')`
`;
const LoadingPanel = styled(props => (
- <HealthPanelChart {...props}>
+ <div {...props}>
<LoadingMask />
- </HealthPanelChart>
+ </div>
))`
flex: 1;
+ flex-shrink: 0;
+ overflow: hidden;
height: 200px;
position: relative;
border-color: transparent;
diff --git a/src/sentry/static/sentry/app/views/organizationEvents/utils/eventsRequest.jsx b/src/sentry/static/sentry/app/views/organizationEvents/utils/eventsRequest.jsx
index 4531bb56296bcd..10769acd5b4b18 100644
--- a/src/sentry/static/sentry/app/views/organizationEvents/utils/eventsRequest.jsx
+++ b/src/sentry/static/sentry/app/views/organizationEvents/utils/eventsRequest.jsx
@@ -5,9 +5,10 @@ import React from 'react';
import {addErrorMessage} from 'app/actionCreators/indicator';
import {doEventsRequest} from 'app/actionCreators/events';
import {t} from 'app/locale';
-import LoadingPanel from 'app/views/organizationHealth/loadingPanel';
import SentryTypes from 'app/sentryTypes';
+import LoadingPanel from '../loadingPanel';
+
const propNamesToIgnore = ['api', 'children', 'organizations', 'project', 'loading'];
const omitIgnoredProps = props =>
omitBy(props, (value, key) => propNamesToIgnore.includes(key));
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/browsers.jsx b/src/sentry/static/sentry/app/views/organizationHealth/browsers.jsx
deleted file mode 100644
index 139ecdd1eb277d..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/browsers.jsx
+++ /dev/null
@@ -1,130 +0,0 @@
-import {Flex} from 'grid-emotion';
-import PropTypes from 'prop-types';
-import React from 'react';
-
-import {t} from 'app/locale';
-import OrganizationHealthDetails from 'app/views/organizationHealth/details';
-import PieChart from 'app/components/charts/pieChart';
-
-import DetailContainer from './detailContainer';
-import EventsTableChart from './eventsTableChart';
-import HealthPanelChart from './styles/healthPanelChart';
-import HealthRequest from './util/healthRequest';
-
-class OrganizationHealthBrowsersOverview extends React.Component {
- static propTypes = {
- tag: PropTypes.string,
- title: PropTypes.string,
- onSetSpecifier: PropTypes.func,
- };
-
- render() {
- const {tag, title, onSetSpecifier} = this.props;
-
- return (
- <React.Fragment>
- <Flex>
- <HealthRequest
- tag={tag}
- showLoading
- includeTimeseries={false}
- includeTop
- limit={5}
- >
- {({tagData}) => {
- return (
- <HealthPanelChart
- showLegend={false}
- height={200}
- series={[
- {
- seriesName: title,
- data: tagData.map(([name, value]) => ({name, value})),
- },
- ]}
- title={title}
- >
- {({series}) => <PieChart height={300} series={series} selectOnRender />}
- </HealthPanelChart>
- );
- }}
- </HealthRequest>
-
- <HealthRequest
- tag="os.name"
- showLegend={false}
- showLoading
- includeTimeseries={false}
- includeTop
- limit={5}
- >
- {({tagData}) => {
- return (
- <HealthPanelChart
- showLegend={false}
- height={200}
- series={[
- {
- seriesName: t('OS'),
- data: tagData.map(([name, value]) => ({name, value})),
- },
- ]}
- title={t('OS')}
- >
- {({series}) => <PieChart height={300} series={series} selectOnRender />}
- </HealthPanelChart>
- );
- }}
- </HealthRequest>
- </Flex>
-
- <Flex>
- <HealthRequest
- tag={tag}
- showLoading
- includeTimeseries={false}
- includeTop
- includePercentages
- limit={5}
- >
- {({tagDataWithPercentages}) => {
- return (
- <EventsTableChart
- headers={[title, t('Events'), t('Percentage'), t('Last event')]}
- data={tagDataWithPercentages}
- onRowClick={onSetSpecifier}
- />
- );
- }}
- </HealthRequest>
- </Flex>
- </React.Fragment>
- );
- }
-}
-class OrganizationHealthBrowsers extends React.Component {
- render() {
- const title = t('Browsers');
-
- return (
- <DetailContainer title={title}>
- {({shouldShowDetails, setSpecifier}) => (
- <React.Fragment>
- {shouldShowDetails ? (
- <OrganizationHealthDetails title={title} />
- ) : (
- <OrganizationHealthBrowsersOverview
- tag="browser.name"
- title={title}
- onSetSpecifier={setSpecifier}
- />
- )}
- </React.Fragment>
- )}
- </DetailContainer>
- );
- }
-}
-
-export default OrganizationHealthBrowsers;
-export {OrganizationHealthBrowsers};
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/detailContainer.jsx b/src/sentry/static/sentry/app/views/organizationHealth/detailContainer.jsx
deleted file mode 100644
index 998ded4649a54e..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/detailContainer.jsx
+++ /dev/null
@@ -1,60 +0,0 @@
-import {Link, withRouter} from 'react-router';
-import PropTypes from 'prop-types';
-import React from 'react';
-import styled from 'react-emotion';
-
-import InlineSvg from 'app/components/inlineSvg';
-import recreateRoute from 'app/utils/recreateRoute';
-import space from 'app/styles/space';
-
-import {HealthContextActions} from './propTypes';
-import Header from './styles/header';
-import withHealth from './util/withHealth';
-
-class DetailContainer extends React.Component {
- static propTypes = {
- title: PropTypes.node,
- router: PropTypes.object,
- actions: HealthContextActions,
- specifiers: PropTypes.arrayOf(PropTypes.string),
- };
-
- render() {
- const {router, actions, specifiers, children, title} = this.props;
- // destructure `location` because we don't want to pass query string to breadcrumb
- // eslint-disable-next-line no-unused-vars
- const {location, ...routerWithoutQueryString} = router;
- const shouldShowDetails = specifiers && !!specifiers.length;
-
- return (
- <React.Fragment>
- <Header>
- {shouldShowDetails ? (
- <React.Fragment>
- <Link to={recreateRoute('', routerWithoutQueryString)}>{title}</Link>
- <Chevron /> {specifiers[0].split(':')[1]}
- </React.Fragment>
- ) : (
- title
- )}
- </Header>
-
- {children({
- shouldShowDetails,
- title,
- specifiers,
- setSpecifier: actions.setSpecifier,
- })}
- </React.Fragment>
- );
- }
-}
-
-export default withRouter(withHealth(DetailContainer));
-export {DetailContainer};
-
-const Chevron = styled(props => <InlineSvg src="icon-chevron-right" {...props} />)`
- height: 14px;
- width: 14px;
- margin: 0 ${space(0.5)};
-`;
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/details.jsx b/src/sentry/static/sentry/app/views/organizationHealth/details.jsx
deleted file mode 100644
index fd8a3e5643c68f..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/details.jsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import {Flex} from 'grid-emotion';
-import React from 'react';
-
-import {t} from 'app/locale';
-import LineChart from 'app/components/charts/lineChart';
-import PieChart from 'app/components/charts/pieChart';
-
-import HealthPanelChart from './styles/healthPanelChart';
-import HealthRequest from './util/healthRequest';
-import withHealth from './util/withHealth';
-
-class OrganizationHealthDetails extends React.Component {
- render() {
- return (
- <React.Fragment>
- <Flex>
- <HealthRequest
- tag="error.handled"
- includePrevious
- showLoading
- interval="1d"
- includeTimeseries
- includeTimeAggregation
- timeAggregationSeriesName={t('Errors')}
- >
- {({timeseriesData, timeAggregatedData, previousTimeseriesData}) => {
- return (
- <HealthPanelChart
- height={200}
- showLegend
- series={[timeAggregatedData]}
- previousPeriod={previousTimeseriesData}
- title={t('Errors')}
- >
- {props => <LineChart isGroupedByDate {...props} />}
- </HealthPanelChart>
- );
- }}
- </HealthRequest>
-
- <HealthRequest
- tag="os.name"
- showLoading
- includeTimeseries={false}
- includeTop
- limit={5}
- >
- {({tagData}) => {
- return (
- <HealthPanelChart
- showLegend={false}
- height={200}
- series={[
- {
- seriesName: t('By Device'),
- data: tagData.map(([name, value]) => ({name, value})),
- },
- ]}
- title={t('By Device')}
- >
- {({series}) => <PieChart height={300} series={series} selectOnRender />}
- </HealthPanelChart>
- );
- }}
- </HealthRequest>
- </Flex>
- </React.Fragment>
- );
- }
-}
-export default withHealth(OrganizationHealthDetails);
-export {OrganizationHealthDetails};
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/devices.jsx b/src/sentry/static/sentry/app/views/organizationHealth/devices.jsx
deleted file mode 100644
index 2cdfec202a2ad3..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/devices.jsx
+++ /dev/null
@@ -1,89 +0,0 @@
-import {Flex} from 'grid-emotion';
-import PropTypes from 'prop-types';
-import React from 'react';
-
-import {t} from 'app/locale';
-import OrganizationHealthDetails from 'app/views/organizationHealth/details';
-import PieChart from 'app/components/charts/pieChart';
-
-import DetailContainer from './detailContainer';
-import EventsTableChart from './eventsTableChart';
-import HealthPanelChart from './styles/healthPanelChart';
-import HealthRequest from './util/healthRequest';
-
-class OrganizationHealthDevicesOverview extends React.Component {
- static propTypes = {
- tag: PropTypes.string,
- title: PropTypes.string,
- onSetSpecifier: PropTypes.func,
- };
-
- render() {
- const {title, tag, onSetSpecifier} = this.props;
- return (
- <HealthRequest
- tag={tag}
- showLoading
- includeTimeseries={false}
- includeTop
- includePercentages
- limit={5}
- >
- {({tagData, tagDataWithPercentages}) => (
- <React.Fragment>
- <Flex>
- <HealthPanelChart
- height={300}
- showLegend={false}
- series={[
- {
- seriesName: title,
- data: tagData.map(([name, value]) => ({name, value})),
- },
- ]}
- title={title}
- >
- {({series}) => <PieChart height={300} selectOnRender series={series} />}
- </HealthPanelChart>
- </Flex>
-
- <Flex>
- <EventsTableChart
- headers={[t('Device'), t('Events'), t('Percentage'), t('Last event')]}
- data={tagDataWithPercentages}
- onRowClick={onSetSpecifier}
- />
- </Flex>
- </React.Fragment>
- )}
- </HealthRequest>
- );
- }
-}
-
-class OrganizationHealthDevices extends React.Component {
- render() {
- const title = t('Devices');
-
- return (
- <DetailContainer title={title}>
- {({shouldShowDetails, setSpecifier}) => (
- <React.Fragment>
- {shouldShowDetails ? (
- <OrganizationHealthDetails title={title} />
- ) : (
- <OrganizationHealthDevicesOverview
- tag="device"
- title={title}
- onSetSpecifier={setSpecifier}
- />
- )}
- </React.Fragment>
- )}
- </DetailContainer>
- );
- }
-}
-
-export default OrganizationHealthDevices;
-export {OrganizationHealthDevices};
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/errors.jsx b/src/sentry/static/sentry/app/views/organizationHealth/errors.jsx
deleted file mode 100644
index bc8da54bbedf5f..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/errors.jsx
+++ /dev/null
@@ -1,374 +0,0 @@
-import {Box, Flex} from 'grid-emotion';
-import PropTypes from 'prop-types';
-import React from 'react';
-import styled from 'react-emotion';
-
-import {addErrorMessage} from 'app/actionCreators/indicator';
-import {t} from 'app/locale';
-import AreaChart from 'app/components/charts/areaChart';
-import Count from 'app/components/count';
-import IdBadge from 'app/components/idBadge';
-import PercentageBarChart from 'app/components/charts/percentageBarChart';
-import PieChart from 'app/components/charts/pieChart';
-import SentryTypes from 'app/sentryTypes';
-import overflowEllipsis from 'app/styles/overflowEllipsis';
-import space from 'app/styles/space';
-import withApi from 'app/utils/withApi';
-
-import Header from './styles/header';
-import HealthPanelChart from './styles/healthPanelChart';
-import HealthRequest from './util/healthRequest';
-import HealthTableChart from './styles/healthTableChart';
-import withHealth from './util/withHealth';
-
-const filterEmpty = val => !!val;
-
-class OrganizationHealthErrors extends React.Component {
- static propTypes = {
- actions: PropTypes.object,
- organization: SentryTypes.Organization,
- };
-
- handleSetSpecifier = (tag, value) => {
- this.props.actions.setSpecifier(tag, value);
- };
-
- render() {
- let {organization} = this.props;
-
- const tooltipOptions = {
- filter: filterEmpty,
- confine: true,
- };
-
- return (
- <React.Fragment>
- <Flex justify="space-between">
- <Header>{t('Errors')}</Header>
- </Flex>
-
- <Flex>
- <HealthRequest
- tag="error.handled"
- includeTimeseries
- interval="1d"
- showLoading
- getCategory={value => (value ? t('Handled') : t('Crash'))}
- >
- {({timeseriesData, previousTimeseriesData}) => {
- return (
- <HealthPanelChart
- height={200}
- title={t('Errors')}
- series={timeseriesData}
- previousPeriod={previousTimeseriesData}
- >
- {props => <AreaChart isGroupedByDate {...props} />}
- </HealthPanelChart>
- );
- }}
- </HealthRequest>
-
- <HealthRequest tag="user" showLoading includeTop includeTimeseries={false}>
- {({originalTagData: originalData, tag}) => (
- <HealthTableChart
- headers={[t('Most Impacted')]}
- data={originalData.map(row => [row, row])}
- widths={[null, 120]}
- getValue={item => (typeof item === 'number' ? item : item && item.count)}
- renderHeaderCell={({getValue, value, columnIndex}) => {
- return typeof value === 'string' ? (
- value
- ) : (
- <div>
- <IdBadge
- user={value[tag].value}
- displayName={value[tag].value && value[tag].value.label}
- />
- </div>
- );
- }}
- renderDataCell={({getValue, value}) => {
- return <Count value={getValue(value)} />;
- }}
- showRowTotal={false}
- showColumnTotal={false}
- shadeRowPercentage
- />
- )}
- </HealthRequest>
- </Flex>
-
- <Flex>
- <HealthRequest
- tag="error.type"
- showLoading
- includeTimeseries={false}
- includeTop
- interval="1d"
- >
- {({tagData}) => {
- return (
- <HealthTableChart
- title={t('Error Type')}
- headers={[t('Error Type')]}
- data={tagData}
- widths={[null, 60, 60, 60, 60]}
- showColumnTotal
- shadeRowPercentage
- renderDataCell={({value}) => <Count value={value} />}
- />
- );
- }}
- </HealthRequest>
- </Flex>
-
- <Flex>
- <ReleasesRequest organization={organization}>
- {({loading, timeseriesData}) => {
- if (loading) return null;
- return (
- <HealthPanelChart
- height={200}
- title={t('Releases (most recent)')}
- series={timeseriesData}
- >
- {props => (
- <AreaChart isGroupedByDate tooltip={tooltipOptions} {...props} />
- )}
- </HealthPanelChart>
- );
- }}
- </ReleasesRequest>
- </Flex>
-
- <Flex>
- <HealthRequest
- tag="release"
- includeTimeseries
- interval="1d"
- showLoading
- limit={10}
- getCategory={({shortVersion}) => shortVersion}
- >
- {({timeseriesData}) => {
- return (
- <HealthPanelChart
- height={200}
- title={t('Releases (most in period)')}
- series={timeseriesData}
- >
- {props => <AreaChart tooltip={tooltipOptions} {...props} />}
- </HealthPanelChart>
- );
- }}
- </HealthRequest>
- </Flex>
-
- <Flex>
- <ReleasesRequest organization={organization}>
- {({timeseriesData, loading}) => {
- if (loading) return null;
- return (
- <HealthPanelChart
- height={200}
- title={t('Releases (most recent)')}
- series={timeseriesData}
- >
- {props => <PercentageBarChart isGroupedByDate {...props} />}
- </HealthPanelChart>
- );
- }}
- </ReleasesRequest>
-
- <HealthRequest
- tag="release"
- includeTimeseries
- interval="1d"
- showLoading
- limit={10}
- getCategory={({shortVersion}) => shortVersion}
- >
- {({timeseriesData}) => {
- return (
- <HealthPanelChart
- height={200}
- title={t('Releases (most in period)')}
- series={timeseriesData}
- >
- {props => <PercentageBarChart isGroupedByDate {...props} />}
- </HealthPanelChart>
- );
- }}
- </HealthRequest>
- </Flex>
-
- <Flex>
- <HealthRequest
- tag="release"
- showLoading
- includeTimeseries={false}
- includeTop
- limit={5}
- topk={5}
- getCategory={({shortVersion}) => shortVersion}
- >
- {({originalTagData: data, tag}) => {
- return (
- <React.Fragment>
- <HealthTableChart
- headers={[t('Errors by Release')]}
- data={data.map(row => [row, row])}
- widths={[null, 120]}
- getValue={item =>
- typeof item === 'number' ? item : item && item.count}
- renderHeaderCell={({getValue, value, columnIndex}) => {
- return (
- <Flex justify="space-between">
- <ReleaseName
- onClick={() =>
- this.handleSetSpecifier(tag, value[tag]._health_id)}
- >
- {value[tag].value.shortVersion}
- </ReleaseName>
- <Project>
- {value.topProjects.map(p => (
- <IdBadge key={p.slug} project={p} />
- ))}
- </Project>
- </Flex>
- );
- }}
- renderDataCell={({getValue, value, columnIndex}) => {
- return <Count value={getValue(value)} />;
- }}
- showRowTotal={false}
- showColumnTotal={false}
- shadeRowPercentage
- />
- <HealthPanelChart
- height={300}
- title={t('Errors By Release')}
- showLegend={false}
- series={[
- {
- seriesName: t('Errors By Release'),
- data: data.map(row => ({
- name: row.release.value.shortVersion,
- value: row.count,
- })),
- },
- ]}
- >
- {({series}) => (
- <Flex>
- <PieChartWrapper>
- <PieChart height={300} series={series} />
- </PieChartWrapper>
- </Flex>
- )}
- </HealthPanelChart>
- </React.Fragment>
- );
- }}
- </HealthRequest>
- </Flex>
- </React.Fragment>
- );
- }
-}
-
-/**
- * This is a proof of concept, unsure if we'll want this.
- *
- * What this does is fetch the most recent releases and then make a snuba query to
- * fetch counts only for those releases.
- *
- * An alternate query is to only include the releases that contain the most error counts
- */
-const ReleasesRequest = withApi(
- class ReleasesRequestComponent extends React.Component {
- static propTypes = {
- limit: PropTypes.number,
- };
-
- static defaultProps = {
- limit: 10,
- };
-
- constructor(props) {
- super(props);
- this.state = {
- data: null,
- };
- }
-
- async componentDidMount() {
- let {api, organization, limit} = this.props;
- if (!organization) return;
-
- try {
- // fetch last `limit` releases
- const releases = await api.requestPromise(
- `/organizations/${organization.slug}/releases/`,
- {
- query: {
- per_page: limit,
- },
- }
- );
-
- // eslint-disable-next-line
- this.setState({
- data: releases,
- });
- } catch (err) {
- addErrorMessage(t('Unable to fetch releases'));
- }
- }
-
- render() {
- let {children, limit, ...props} = this.props;
- let {data} = this.state;
- let loading = data === null;
-
- if (!data) {
- return children({
- loading,
- });
- }
-
- return (
- <HealthRequest
- tag="release"
- includeTimeseries
- interval="1d"
- showLoading
- limit={limit}
- getCategory={({shortVersion}) => shortVersion}
- specifiers={data.map(({version}) => `release:${version}`)}
- {...props}
- >
- {children}
- </HealthRequest>
- );
- }
- }
-);
-
-export default withHealth(OrganizationHealthErrors);
-export {OrganizationHealthErrors};
-
-const PieChartWrapper = styled(Box)`
- flex: 1;
- flex-shrink: 0;
-`;
-
-const ReleaseName = styled(Box)`
- ${overflowEllipsis};
-`;
-
-const Project = styled(Box)`
- margin-left: ${space(1)};
- flex-shrink: 0;
-`;
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/eventsTableChart.jsx b/src/sentry/static/sentry/app/views/organizationHealth/eventsTableChart.jsx
deleted file mode 100644
index c82d45e51ebde3..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/eventsTableChart.jsx
+++ /dev/null
@@ -1,164 +0,0 @@
-import {Flex} from 'grid-emotion';
-import PropTypes from 'prop-types';
-import React from 'react';
-import styled from 'react-emotion';
-
-import Count from 'app/components/count';
-import InlineSvg from 'app/components/inlineSvg';
-import TableChart from 'app/components/charts/tableChart';
-import overflowEllipsis from 'app/styles/overflowEllipsis';
-import space from 'app/styles/space';
-
-const Delta = ({current, previous, className}) => {
- const changePercent = Math.round(Math.abs(current - previous) / previous * 100);
- const direction = !changePercent ? 0 : current - previous;
- return (
- <StyledDelta direction={direction} className={className}>
- {!!direction && <DeltaCaret direction={direction} src="icon-chevron-down" />}
- {changePercent !== 0 ? `${changePercent}%` : <span>—</span>}
- </StyledDelta>
- );
-};
-Delta.propTypes = {
- current: PropTypes.number,
- previous: PropTypes.number,
-};
-
-const DeltaCaret = styled(InlineSvg)`
- /* should probably have a chevron-up svg (: */
- ${p => p.direction > 0 && 'transform: rotate(180deg)'};
- width: 10px;
- height: 10px;
-`;
-
-const StyledDelta = styled(Flex)`
- align-items: center;
- padding: 0 ${space(0.25)};
- margin-right: ${space(0.5)};
- font-size: ${p => p.theme.fontSizeSmall};
- color: ${p =>
- p.direction > 0 ? p.theme.green : p.direction < 0 ? p.theme.red : p.theme.gray2};
-`;
-
-class EventsTableChart extends React.Component {
- static propTypes = {
- headers: PropTypes.arrayOf(PropTypes.node),
- onRowClick: PropTypes.func,
- data: PropTypes.arrayOf(
- PropTypes.shape({
- name: PropTypes.node,
- percentage: PropTypes.number,
- count: PropTypes.number,
- lastCount: PropTypes.number,
- })
- ),
- };
-
- static defaultProps = {
- onRowClick: () => {},
- };
-
- handleRowClick = ({specifier}, e) => {
- const {onRowClick} = this.props;
- onRowClick(specifier, e);
- };
-
- render() {
- const {headers, data} = this.props;
-
- return (
- <TableChart
- headers={headers}
- data={data.map(({count, lastCount, name, percentage}) => [
- <Name key="name">{name}</Name>,
- <Events key="events">
- <Delta current={count} previous={lastCount} />
- <Count value={count} />
- </Events>,
- <React.Fragment key="bar">
- <BarWrapper>
- <Bar width={percentage} />
- </BarWrapper>
- <span>{percentage}%</span>
- </React.Fragment>,
- <LastEvent key="time-ago">n/a</LastEvent>,
- ])}
- renderRow={({items, rowIndex, ...other}) => (
- <Row onClick={this.handleRowClick} data={data} rowIndex={rowIndex}>
- <NameAndEventsContainer justify="space-between" align="center">
- {items[0]}
- <div>{items[1]}</div>
- </NameAndEventsContainer>
- <PercentageContainer justify="space-between" align="center">
- <Flex w={[3 / 4]} align="center" key="bar">
- {items[2]}
- </Flex>
- <Flex w={[1 / 4]} justify="flex-end" key="last-event">
- {items[3]}
- </Flex>
- </PercentageContainer>
- </Row>
- )}
- />
- );
- }
-}
-
-const Row = styled(function RowComponent({className, data, rowIndex, onClick, children}) {
- return (
- <div
- className={className}
- onClick={e => typeof onClick === 'function' && onClick(data[rowIndex], e)}
- >
- {children}
- </div>
- );
-})`
- display: flex;
- flex: 1;
- cursor: pointer;
-`;
-
-const StyledEventsTableChart = styled(EventsTableChart)`
- width: 100%;
-`;
-
-const NameAndEventsContainer = styled(Flex)`
- flex-shrink: 0;
- margin-right: ${space(2)};
- width: 50%;
-`;
-
-const PercentageContainer = styled(Flex)`
- width: 50%;
-`;
-
-const BarWrapper = styled('div')`
- width: 85%;
- margin-right: ${space(1)};
-`;
-
-const Bar = styled(({width, ...props}) => <div {...props} />)`
- flex: 1;
- width: ${p => p.width}%;
- background-color: ${p => p.theme.gray1};
- height: 12px;
- border-radius: 2px;
-`;
-
-const Name = styled('span')`
- ${overflowEllipsis};
-`;
-
-const Events = styled(Name)`
- display: flex;
- align-items: center;
- margin-left: ${space(0.5)};
-`;
-
-const LastEvent = styled(Name)`
- text-align: right;
- margin-left: ${space(0.5)};
-`;
-
-export default StyledEventsTableChart;
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/healthNavigationMenu.jsx b/src/sentry/static/sentry/app/views/organizationHealth/healthNavigationMenu.jsx
deleted file mode 100644
index e0f9f1433ceef0..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/healthNavigationMenu.jsx
+++ /dev/null
@@ -1,86 +0,0 @@
-import PropTypes from 'prop-types';
-import React from 'react';
-import styled from 'react-emotion';
-
-import {t} from 'app/locale';
-import Link from 'app/components/link';
-import SentryTypes from 'app/sentryTypes';
-import space from 'app/styles/space';
-import withLatestContext from 'app/utils/withLatestContext';
-
-const HealthNavigationMenu = styled(
- withLatestContext(
- class HealthNavigationMenu extends React.Component {
- static propTypes = {
- organization: SentryTypes.Organization,
- };
-
- render() {
- let {className, organization} = this.props;
- return (
- <div className={className}>
- <NavigationGroup title={t('Monitoring')}>
- <NavItem to={`/organizations/${organization.slug}/health/`}>
- {t('Overview')}
- </NavItem>
- <NavItem to={`/organizations/${organization.slug}/health/errors/`}>
- {t('Errors')}
- </NavItem>
- <NavItem to={`/organizations/${organization.slug}/health/transactions/`}>
- {t('Transactions')}
- </NavItem>
- </NavigationGroup>
-
- <NavigationGroup title={t('Users')}>
- <NavItem to={`/organizations/${organization.slug}/health/browsers/`}>
- {t('Browsers')}
- </NavItem>
- <NavItem to={`/organizations/${organization.slug}/health/devices/`}>
- {t('Devices')}
- </NavItem>
- </NavigationGroup>
- </div>
- );
- }
- }
- )
-)`
- border-right: 1px solid ${p => p.theme.borderLight};
- width: 180px;
- flex-shrink: 0;
-`;
-
-export default HealthNavigationMenu;
-
-const NavigationGroup = styled(
- class NavigationGroup extends React.Component {
- static propTypes = {
- title: PropTypes.node,
- };
-
- render() {
- let {className, title, children} = this.props;
- return (
- <div className={className}>
- <Title>{title}</Title>
- {children}
- </div>
- );
- }
- }
-)`
- display: flex;
- flex-direction: column;
-`;
-
-const Title = styled('div')`
- color: ${p => p.theme.gray1};
- font-size: 0.9em;
- padding: ${space(2)};
- margin-bottom: ${space(0)};
- text-transform: uppercase;
-`;
-
-const NavItem = styled(Link)`
- padding: 0 ${space(2)};
-`;
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/index.jsx b/src/sentry/static/sentry/app/views/organizationHealth/index.jsx
deleted file mode 100644
index f2dcdb78700850..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/index.jsx
+++ /dev/null
@@ -1,145 +0,0 @@
-import {Flex} from 'grid-emotion';
-import {withRouter} from 'react-router';
-import PropTypes from 'prop-types';
-import React from 'react';
-import styled from 'react-emotion';
-
-import Feature from 'app/components/acl/feature';
-import HeaderSeparator from 'app/components/organizations/headerSeparator';
-import MultipleEnvironmentSelector from 'app/components/organizations/multipleEnvironmentSelector';
-import MultipleProjectSelector from 'app/components/organizations/multipleProjectSelector';
-import SentryTypes from 'app/sentryTypes';
-import TimeRangeSelector from 'app/components/organizations/timeRangeSelector';
-import space from 'app/styles/space';
-import withLatestContext from 'app/utils/withLatestContext';
-
-import HealthContext from './util/healthContext';
-import HealthNavigationMenu from './healthNavigationMenu';
-
-class OrganizationHealth extends React.Component {
- static propTypes = {
- organization: SentryTypes.Organization,
- router: PropTypes.object,
- };
-
- static getDerivedStateFromProps(props, state) {
- const {query} = props.router.location;
-
- return {
- projects: query.projects || [],
- environments: query.environments || [],
- specifiers:
- typeof query.specifiers === 'string'
- ? [query.specifiers]
- : Array.isArray(query.specifiers) ? query.specifiers : [],
- period: query.period || '7d',
- };
- }
-
- constructor(props) {
- super(props);
-
- this.actions = {
- updateParams: this.updateParams,
- setSpecifier: this.setSpecifier,
- };
-
- this.state = {};
- }
-
- updateParams = obj => {
- const {router} = this.props;
- router.push({
- pathname: router.location.pathname,
- query: {
- ...router.location.query,
- ...obj,
- },
- });
- };
-
- setSpecifier = (tag, value) => {
- this.setState(state => ({
- ...state,
- specifiers: [`${tag}:${value}`],
- }));
- };
-
- handleChangeProjects = projects => {
- this.updateParams({projects});
- };
-
- handleChangeEnvironments = environments => {
- this.updateParams({environments});
- };
-
- handleChangeTime = period => {
- this.updateParams({period});
- };
-
- render() {
- let {organization, children} = this.props;
-
- // TODO(billy): Is this what we want, only projects user is member of?
- let projects =
- organization.projects && organization.projects.filter(({isMember}) => isMember);
-
- return (
- <Feature features={['health']} renderDisabled>
- <HealthContext.Provider value={{actions: this.actions, ...this.state}}>
- <HealthWrapper>
- <HealthNavigationMenu />
- <Content>
- <Header>
- <MultipleProjectSelector
- organization={organization}
- projects={projects}
- value={this.state.projects}
- onChange={this.handleChangeProjects}
- />
- <HeaderSeparator />
- <MultipleEnvironmentSelector
- organization={organization}
- value={this.state.environments}
- onChange={this.handleChangeEnvironments}
- />
- <HeaderSeparator />
- <TimeRangeSelector
- showAbsolute={false}
- showRelative
- relative={this.state.period}
- onChange={this.handleChangeTime}
- />
- </Header>
- <Body>{children}</Body>
- </Content>
- </HealthWrapper>
- </HealthContext.Provider>
- </Feature>
- );
- }
-}
-
-export default withRouter(withLatestContext(OrganizationHealth));
-export {OrganizationHealth};
-
-const HealthWrapper = styled(Flex)`
- flex: 1;
- margin-bottom: -20px; /* <footer> has margin-top: 20px; */
-`;
-const Content = styled(Flex)`
- flex-direction: column;
- flex: 1;
- overflow: hidden;
-`;
-
-const Header = styled(Flex)`
- border-bottom: 1px solid ${p => p.theme.borderLight};
- font-size: 18px;
- padding: ${space(1)} ${space(4)};
-`;
-
-const Body = styled('div')`
- flex: 1;
- padding: ${space(3)};
-`;
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/overview.jsx b/src/sentry/static/sentry/app/views/organizationHealth/overview.jsx
deleted file mode 100644
index cd41010ee43cc9..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/overview.jsx
+++ /dev/null
@@ -1,9 +0,0 @@
-import React from 'react';
-
-class OrganizationHealthOverview extends React.Component {
- render() {
- return <div>Overview</div>;
- }
-}
-
-export default OrganizationHealthOverview;
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/propTypes/index.jsx b/src/sentry/static/sentry/app/views/organizationHealth/propTypes/index.jsx
deleted file mode 100644
index 98710ebfbffdcc..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/propTypes/index.jsx
+++ /dev/null
@@ -1,8 +0,0 @@
-import PropTypes from 'prop-types';
-
-const HealthContextActions = PropTypes.shape({
- updateParams: PropTypes.func.isRequired,
- setSpecifier: PropTypes.func.isRequired,
-});
-
-export {HealthContextActions};
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/styles/chartMargin.jsx b/src/sentry/static/sentry/app/views/organizationHealth/styles/chartMargin.jsx
deleted file mode 100644
index b1a5103fa6cb81..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/styles/chartMargin.jsx
+++ /dev/null
@@ -1,12 +0,0 @@
-import {css} from 'react-emotion';
-
-import space from 'app/styles/space';
-
-const chartMargin = css`
- margin-right: ${space(2)};
- &:last-child {
- margin-right: 0;
- }
-`;
-
-export default chartMargin;
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/styles/header.jsx b/src/sentry/static/sentry/app/views/organizationHealth/styles/header.jsx
deleted file mode 100644
index b98924548d9a98..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/styles/header.jsx
+++ /dev/null
@@ -1,12 +0,0 @@
-import styled from 'react-emotion';
-import {Flex} from 'grid-emotion';
-
-import space from 'app/styles/space';
-
-const Header = styled(Flex)`
- align-items: center;
- font-size: ${p => p.theme.fontSizeExtraLarge};
- margin-bottom: ${space(2)};
-`;
-
-export default Header;
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/styles/healthPanelChart.jsx b/src/sentry/static/sentry/app/views/organizationHealth/styles/healthPanelChart.jsx
deleted file mode 100644
index 06bd1290a024a0..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/styles/healthPanelChart.jsx
+++ /dev/null
@@ -1,12 +0,0 @@
-import styled from 'react-emotion';
-
-import PanelChart from 'app/components/charts/panelChart';
-
-import chartMargin from './chartMargin';
-
-const HealthPanelChart = styled(PanelChart)`
- ${chartMargin};
- flex-shrink: 0;
- overflow: hidden;
-`;
-export default HealthPanelChart;
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/styles/healthTableChart.jsx b/src/sentry/static/sentry/app/views/organizationHealth/styles/healthTableChart.jsx
deleted file mode 100644
index 878a566df4ade4..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/styles/healthTableChart.jsx
+++ /dev/null
@@ -1,12 +0,0 @@
-import styled from 'react-emotion';
-
-import TableChart from 'app/components/charts/tableChart';
-
-import chartMargin from './chartMargin';
-
-const HealthPanelChart = styled(TableChart)`
- ${chartMargin};
- flex-shrink: 0;
- overflow: hidden;
-`;
-export default HealthPanelChart;
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/transactions.jsx b/src/sentry/static/sentry/app/views/organizationHealth/transactions.jsx
deleted file mode 100644
index 6b03bdc953d51e..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/transactions.jsx
+++ /dev/null
@@ -1,100 +0,0 @@
-import {Flex} from 'grid-emotion';
-import React from 'react';
-
-import {t} from 'app/locale';
-import AreaChart from 'app/components/charts/areaChart';
-import LineChart from 'app/components/charts/lineChart';
-
-import {HealthContextActions} from './propTypes';
-import HealthPanelChart from './styles/healthPanelChart';
-import EventsTableChart from './eventsTableChart';
-import HealthRequest from './util/healthRequest';
-import withHealth from './util/withHealth';
-
-class OrganizationHealthTransactions extends React.Component {
- static propTypes = {
- actions: HealthContextActions,
- };
-
- render() {
- let {className} = this.props;
- return (
- <div className={className}>
- <HealthRequest
- tag="transaction"
- showLoading
- includeTimeseries
- includeTimeAggregation
- timeAggregationSeriesName="Transactions"
- includePrevious
- >
- {({timeseriesData, timeAggregatedData, previousTimeseriesData}) => {
- return (
- <Flex>
- <HealthPanelChart
- showLegend={false}
- height={400}
- title={t('Transactions')}
- previousPeriod={previousTimeseriesData}
- >
- {props => (
- <LineChart isGroupedByDate {...props} series={[timeAggregatedData]} />
- )}
- </HealthPanelChart>
- </Flex>
- );
- }}
- </HealthRequest>
-
- <HealthRequest
- tag="transaction"
- showLoading
- includeTop
- includeTimeseries
- includeTimeAggregation
- timeAggregationSeriesName="Transactions"
- includePercentages
- includePrevious
- limit={10}
- >
- {({
- timeseriesData,
- tagDataWithPercentages,
- timeAggregatedData,
- previousTimeseriesData,
- }) => {
- return (
- <React.Fragment>
- <Flex>
- <HealthPanelChart
- showLegend={false}
- height={400}
- title={t('Transactions')}
- series={timeseriesData}
- previousPeriod={previousTimeseriesData}
- >
- {props => <AreaChart isGroupedByDate {...props} />}
- </HealthPanelChart>
- </Flex>
- <Flex>
- <EventsTableChart
- headers={[
- t('Transaction'),
- t('Events'),
- t('Percentage'),
- t('Last event'),
- ]}
- data={tagDataWithPercentages}
- />
- </Flex>
- </React.Fragment>
- );
- }}
- </HealthRequest>
- </div>
- );
- }
-}
-
-export default withHealth(OrganizationHealthTransactions);
-export {OrganizationHealthTransactions};
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/util/__mocks__/withHealth.jsx b/src/sentry/static/sentry/app/views/organizationHealth/util/__mocks__/withHealth.jsx
deleted file mode 100644
index 6f2a4611ac5179..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/util/__mocks__/withHealth.jsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import React from 'react';
-
-import getDisplayName from 'app/utils/getDisplayName';
-import withLatestContext from 'app/utils/withLatestContext';
-
-jest.mock('app/utils/withLatestContext');
-
-const ACTIONS = {
- actions: {
- setSpecifier: jest.fn(),
- updateParams: jest.fn(),
- },
-};
-
-const withHealthMock = WrappedComponent => {
- const WrappedWithLatestContext = withLatestContext(WrappedComponent);
-
- class WithHealthMockWrapper extends React.Component {
- render() {
- return <WrappedWithLatestContext {...ACTIONS} {...this.props} />;
- }
- }
- WithHealthMockWrapper.displayName = `withHealthMock(${getDisplayName(
- WrappedComponent
- )})`;
-
- return WithHealthMockWrapper;
-};
-
-export default withHealthMock;
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/util/healthContext.jsx b/src/sentry/static/sentry/app/views/organizationHealth/util/healthContext.jsx
deleted file mode 100644
index 4ef924b532a19b..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/util/healthContext.jsx
+++ /dev/null
@@ -1,9 +0,0 @@
-import React from 'react';
-
-const HealthContext = React.createContext({
- projects: [],
- environments: [],
- daterange: '7d',
-});
-
-export default HealthContext;
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/util/healthRequest.jsx b/src/sentry/static/sentry/app/views/organizationHealth/util/healthRequest.jsx
deleted file mode 100644
index d5ca10aa9d8e48..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/util/healthRequest.jsx
+++ /dev/null
@@ -1,481 +0,0 @@
-import {isEqual, omitBy} from 'lodash';
-import PropTypes from 'prop-types';
-import React from 'react';
-
-import {doHealthRequest} from 'app/actionCreators/health';
-import LoadingPanel from 'app/views/organizationHealth/loadingPanel';
-import SentryTypes from 'app/sentryTypes';
-import withApi from 'app/utils/withApi';
-import withLatestContext from 'app/utils/withLatestContext';
-
-import HealthContext from './healthContext';
-
-class HealthRequestWithParams extends React.Component {
- static propTypes = {
- /**
- * API client instance
- */
- api: PropTypes.object.isRequired,
-
- organization: SentryTypes.Organization.isRequired,
-
- /**
- * Health tag (this will use a BASE_URL defined in health actionCreators
- */
- tag: PropTypes.string.isRequired,
-
- /**
- * List of project ids to query
- */
- projects: PropTypes.arrayOf(PropTypes.number),
-
- /**
- * List of environments to query
- */
- environments: PropTypes.arrayOf(PropTypes.string),
-
- /**
- * Relative time period for query.
- *
- * Use `start` and `end` for absolute dates.
- *
- * e.g. 24h, 7d, 30d
- */
- period: PropTypes.string,
-
- /**
- * Absolute start date for query
- */
- start: PropTypes.instanceOf(Date),
- /**
- * Absolute end date for query
- */
- end: PropTypes.instanceOf(Date),
-
- /**
- * Interval to group results in
- *
- * e.g. 1d, 1h, 1m, 1s
- */
- interval: PropTypes.string,
-
- /**
- * Include data for previous period
- */
- includePrevious: PropTypes.bool,
-
- /**
- * number of rows to return
- */
- limit: PropTypes.number,
-
- /**
- * topK value, currently only hardcoded for topk projects
- */
- topk: PropTypes.number,
-
- /**
- * Callback function to process category
- */
- getCategory: PropTypes.func,
-
- /**
- * Transform the response data to be something ingestible by charts
- */
- includeTransformedData: PropTypes.bool,
-
- /**
- * Include a dataset transform that will aggregate count values for each timestamp.
- * Be sure to supply a name to `timeAggregationSeriesName`
- */
- includeTimeAggregation: PropTypes.bool,
-
- /**
- * Name of series of aggregated timeseries
- */
- timeAggregationSeriesName: PropTypes.string,
-
- /**
- * Include a map of series name -> percentage integers
- *
- * This is only valid for non-timeseries data
- */
- includePercentages: PropTypes.bool,
-
- includeTimeseries: PropTypes.bool,
-
- includeTop: PropTypes.bool,
-
- showLoading: PropTypes.bool,
- };
-
- static defaultProps = {
- period: null,
- start: null,
- end: null,
- interval: '1d',
- limit: 15,
- getCategory: i => i,
-
- includeTimeseries: true,
- includePrevious: true,
- includeTransformedData: true,
- };
-
- constructor(props) {
- super(props);
- this.state = {
- reloading: false,
- tagData: null,
- timeseriesData: null,
- };
- }
-
- componentDidMount() {
- this.fetchData();
- }
-
- componentDidUpdate(prevProps) {
- const propNamesToIgnore = [
- 'api',
- 'children',
- 'getCategory',
- 'organization',
- 'organizations',
- 'project',
- ];
-
- const prevPropsToCheck = omitBy(prevProps, (value, key) =>
- propNamesToIgnore.includes(key)
- );
-
- const propsToCheck = omitBy(this.props, (value, key) =>
- propNamesToIgnore.includes(key)
- );
-
- if (isEqual(prevPropsToCheck, propsToCheck)) return;
-
- this.fetchData();
- }
-
- componentWillUnmount() {
- this.unmounting = true;
- }
-
- fetchData = async () => {
- const {tag} = this.props;
-
- this.setState(state => ({
- reloading: state.tagData !== null && state.timeseriesData !== null,
- }));
-
- // If `includeTop` is defined and > 0, we need to fetch the top tags ordered by count
- // And then if we need timeseries, we'll pass the specific tag values into the timeseries query
- // to fetch only the counts for those tag values.
- const tagData = await this.fetchTopTag();
- const tagSpecifiers =
- (tagData &&
- tagData.data &&
- tagData.data
- .map(({[tag]: tagObject}) => tagObject && tagObject._health_id)
- .filter(id => !!id)) ||
- null;
-
- const timeseriesData = await this.fetchTimeseriesData({
- ...(tagSpecifiers && tagSpecifiers.length
- ? {
- specifiers: tagSpecifiers,
- }
- : {}),
- });
-
- if (this.unmounting) return;
-
- this.setState({
- reloading: false,
- tagData,
- timeseriesData,
- });
- };
-
- fetchTopTag = otherProps => {
- const {api, includeTop, ...props} = this.props;
-
- if (!includeTop) return Promise.resolve({});
-
- return doHealthRequest(api, {...props, ...otherProps, timeseries: false});
- };
-
- fetchTimeseriesData = otherProps => {
- const {api, includeTimeseries, ...props} = this.props;
- if (!includeTimeseries) return Promise.resolve({});
- return doHealthRequest(api, {...props, ...otherProps, timeseries: true});
- };
-
- // Is going to be called with an object with `value` and `_health_id`
- getCategory = ({value} = {}) => {
- return this.props.getCategory(value);
- };
-
- /**
- * Retrieves data set for the current period (since data can potentially contain previous period's data), as
- * well as the previous period if possible.
- *
- * Returns `null` if data does not exist
- */
- getData = (data, isTimeseries) => {
- const {includePrevious} = this.props;
-
- if (!data) {
- return {
- previous: null,
- current: null,
- };
- }
-
- const hasPreviousPeriod = isTimeseries && includePrevious;
- // Take the floor just in case, but data should always be divisible by 2
- const dataMiddleIndex = Math.floor(data.length / 2);
-
- return {
- previous: hasPreviousPeriod ? data.slice(0, dataMiddleIndex) : null,
- current: hasPreviousPeriod ? data.slice(dataMiddleIndex) : data,
- };
- };
-
- // This aggregates all values per `timestamp`
- calculateTotalsPerTimestamp = (data, getName = timestamp => timestamp * 1000) => {
- return data.map(([timestamp, countArray], i) => ({
- name: getName(timestamp, countArray, i),
- value: countArray.reduce((acc, {count}) => acc + count, 0),
- }));
- };
-
- transformSeriesPercentageMap = (transformedData, total) => {
- return new Map(
- transformedData.map(([name, value]) => [
- name,
- Math.round(value / total * 10000) / 100,
- ])
- );
- };
-
- /**
- * Get previous period data, but transform timestampts so that data fits unto the current period's data axis
- */
- transformPreviousPeriodData = (current, previous) => {
- // Need the current period data array so we can take the timestamp
- // so we can be sure the data lines up
- if (!previous) return [];
-
- return {
- seriesName: 'Previous Period',
- data: this.calculateTotalsPerTimestamp(
- previous,
- (timestamp, countArray, i) => current[i][0] * 1000
- ),
- };
- };
-
- /**
- * Aggregate all counts for each time stamp
- */
- transformAggregatedTimeseries = (data, seriesName) => {
- if (!data) return null;
-
- return {
- seriesName,
- data: this.calculateTotalsPerTimestamp(data),
- };
- };
-
- /**
- * Transforms query response into timeseries data to be used in a chart
- */
- transformTimeseriesData = (data, tag) => {
- const categorySet = new Set();
- const timestampMap = new Map();
-
- data.forEach(([timestamp, resultsForTimestamp]) => {
- resultsForTimestamp &&
- !!resultsForTimestamp.length &&
- resultsForTimestamp.forEach(({count, [tag]: tagObject}) => {
- const category = this.getCategory(tagObject);
- const timestampKey = `${timestamp}-${this.getCategory(tagObject)}`;
- categorySet.add(category);
-
- // aggregate if exists
- timestampMap.set(
- timestampKey,
- timestampMap.has(timestampKey)
- ? timestampMap.get(timestampKey) + count
- : count
- );
- });
- });
-
- return Array.from(categorySet).map(seriesName => {
- return {
- seriesName,
- data: data.map(([timestamp]) => ({
- name: timestamp * 1000,
- value: timestampMap.get(`${timestamp}-${seriesName}`) || 0,
- })),
- };
- });
- };
-
- /**
- * Transforms query response into a non-timeseries data to be used in a chart
- */
- transformNonTimeSeriesData = (data, tag) =>
- data.map(({[tag]: tagObject, count}) => [this.getCategory(tagObject), count]);
-
- transformData = (data, isTimeseries) => {
- const {tag} = this.props;
- if (!data) return null;
-
- return isTimeseries
- ? this.transformTimeseriesData(data, tag)
- : this.transformNonTimeSeriesData(data, tag);
- };
-
- processData({data, totals} = {}, isTimeseries) {
- const {
- tag,
- includeTransformedData,
- includePercentages,
- includeTimeAggregation,
- includeTop,
- timeAggregationSeriesName,
- } = this.props;
- const shouldIncludePercentages = includePercentages && includeTop && !isTimeseries;
- const {current, previous} = this.getData(data, isTimeseries);
- const transformedData =
- includeTransformedData || shouldIncludePercentages
- ? this.transformData(current, isTimeseries)
- : null;
-
- const percentageMap =
- shouldIncludePercentages &&
- totals &&
- this.transformSeriesPercentageMap(transformedData, totals.count);
-
- const dataWithPercentages =
- shouldIncludePercentages && current
- ? current.map(({count, lastCount, [tag]: tagObject}) => {
- const name = this.getCategory(tagObject);
-
- return {
- count,
- lastCount,
- name,
- percentage: percentageMap.get(name),
- };
- })
- : null;
-
- const previousData =
- isTimeseries && includeTransformedData
- ? this.transformPreviousPeriodData(current, previous)
- : null;
-
- const timeAggregatedData =
- isTimeseries && includeTimeAggregation
- ? this.transformAggregatedTimeseries(current, timeAggregationSeriesName)
- : null;
-
- return {
- data: transformedData,
- allData: data,
- originalData: current,
- totals,
- originalPreviousData: previous,
- previousData,
- timeAggregatedData,
- dataWithPercentages,
- };
- }
-
- render() {
- const {children, tag, showLoading, ...props} = this.props;
-
- const {tagData, timeseriesData, reloading} = this.state;
-
- // Is "loading" if data is null
- const loading = reloading || (tagData === null || timeseriesData === null);
-
- if (showLoading && loading) {
- return <LoadingPanel />;
- }
-
- const {
- data: transformedTagData,
- allData: allTagData,
- originalData: originalTagData,
- totals: tagTotals,
- dataWithPercentages: tagDataWithPercentages,
- } =
- (tagData && this.processData(tagData)) || {};
-
- const {
- data: transformedTimeseriesData,
- allData: allTimeseriesData,
- originalData: originalTimeseriesData,
- totals: timeseriesTotals,
- originalPreviousData: originalPreviousTimeseriesData,
- previousData: previousTimeseriesData,
- timeAggregatedData,
- } =
- (timeseriesData && this.processData(timeseriesData, true)) || {};
-
- return children({
- loading,
-
- // tg data
- tagData: transformedTagData,
- allTagData,
- originalTagData,
- tagTotals,
- tagDataWithPercentages,
-
- // timeseries data
- timeseriesData: transformedTimeseriesData,
- allTimeseriesData,
- originalTimeseriesData,
- timeseriesTotals,
- originalPreviousTimeseriesData,
- previousTimeseriesData,
- timeAggregatedData,
-
- // sometimes we want to reference props that were given to HealthRequest
- tag,
- ...props,
- });
- }
-}
-
-const HealthRequest = withLatestContext(
- withApi(
- class HealthRequest extends React.Component {
- render() {
- return (
- <HealthContext.Consumer>
- {({projects, environments, period, filters}) => (
- <HealthRequestWithParams
- projects={projects}
- environments={environments}
- period={period}
- filters={filters}
- {...this.props}
- />
- )}
- </HealthContext.Consumer>
- );
- }
- }
- )
-);
-
-export default HealthRequest;
-export {HealthRequestWithParams};
diff --git a/src/sentry/static/sentry/app/views/organizationHealth/util/withHealth.jsx b/src/sentry/static/sentry/app/views/organizationHealth/util/withHealth.jsx
deleted file mode 100644
index 075cda512c388a..00000000000000
--- a/src/sentry/static/sentry/app/views/organizationHealth/util/withHealth.jsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import React from 'react';
-
-import getDisplayName from 'app/utils/getDisplayName';
-import withLatestContext from 'app/utils/withLatestContext';
-
-import HealthContext from './healthContext';
-
-/**
- * HoC that provides component with properties from `HealthContext`
- */
-const withHealth = WrappedComponent => {
- const WrappedWithLatestContext = withLatestContext(WrappedComponent);
-
- class WithHealth extends React.Component {
- render() {
- return (
- <HealthContext.Consumer>
- {context => <WrappedWithLatestContext {...context} {...this.props} />}
- </HealthContext.Consumer>
- );
- }
- }
-
- WithHealth.displayName = `withHealth(${getDisplayName(WrappedComponent)})`;
-
- return WithHealth;
-};
-
-export default withHealth;
diff --git a/tests/acceptance/test_health.py b/tests/acceptance/test_health.py
deleted file mode 100644
index 606aed11df042e..00000000000000
--- a/tests/acceptance/test_health.py
+++ /dev/null
@@ -1,53 +0,0 @@
-from __future__ import absolute_import
-
-from sentry.testutils import AcceptanceTestCase
-
-
-class HealthTest(AcceptanceTestCase):
- def setUp(self):
- super(HealthTest, self).setUp()
- self.user = self.create_user('[email protected]')
- self.org = self.create_organization(
- name='Rowdy Tiger Rowdy Tiger',
- owner=None,
- )
- self.team = self.create_team(organization=self.org, name='Mariachi Band Mariachi Band')
- self.project = self.create_project(
- organization=self.org,
- teams=[self.team],
- name='Bengal',
- )
-
- self.create_member(
- user=self.user,
- organization=self.org,
- role='owner',
- teams=[self.team],
- )
-
- self.login_as(self.user)
- self.path = u'/organizations/{}/health'.format(self.org.slug)
-
- def test_overview_without_feature_flag(self):
- self.browser.get(u'{}/'.format(self.path))
- self.browser.wait_until_not('.loading-indicator')
- self.browser.snapshot('health overview - no permissions')
-
- def test_overview(self):
- with self.feature('organizations:health'):
- self.browser.get(u'{}/'.format(self.path))
- self.browser.wait_until_not('.loading-indicator')
- self.browser.snapshot('health overview')
-
- # TODO(billyvg): Skipping until API endpoints are ready
- # def test_errors(self):
- # with self.feature('organizations:health'):
- # self.browser.get('{}/errors/'.format(self.path))
- # self.browser.wait_until_not('.loading-indicator')
- # self.browser.snapshot('health errors')
-
- # def test_transactions(self):
- # with self.feature('organizations:health'):
- # self.browser.get('{}/transactions/'.format(self.path))
- # self.browser.wait_until_not('.loading-indicator')
- # self.browser.snapshot('health transactions')
diff --git a/tests/js/spec/views/organizationHealth/__snapshots__/overview.spec.jsx.snap b/tests/js/spec/views/organizationHealth/__snapshots__/overview.spec.jsx.snap
deleted file mode 100644
index 3d29b2735725e2..00000000000000
--- a/tests/js/spec/views/organizationHealth/__snapshots__/overview.spec.jsx.snap
+++ /dev/null
@@ -1,9 +0,0 @@
-// Jest Snapshot v1, https://goo.gl/fbAQLP
-
-exports[`OrganizationHealthOverview renders 1`] = `
-<OrganizationHealthOverview>
- <div>
- Overview
- </div>
-</OrganizationHealthOverview>
-`;
diff --git a/tests/js/spec/views/organizationHealth/browsers.spec.jsx b/tests/js/spec/views/organizationHealth/browsers.spec.jsx
deleted file mode 100644
index 4afa4d13ef9e5f..00000000000000
--- a/tests/js/spec/views/organizationHealth/browsers.spec.jsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import React from 'react';
-import {mount} from 'enzyme';
-
-import OrganizationHealthBrowsers from 'app/views/organizationHealth/browsers';
-
-jest.mock('app/views/organizationHealth/util/withHealth');
-jest.mock('app/utils/withLatestContext');
-
-describe('OrganizationHealthBrowsers', function() {
- const org = TestStubs.Organization();
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/health/top/',
- body: (url, opts) => {
- return TestStubs.HealthTop(opts.query);
- },
- });
-
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/health/graph/',
- body: (url, opts) => {
- return TestStubs.HealthGraph(opts.query);
- },
- });
-
- it('renders with PieChart, and EventTableChart', async function() {
- let wrapper = mount(
- <OrganizationHealthBrowsers organization={org} />,
- TestStubs.routerContext()
- );
- await tick();
- wrapper.update();
- expect(wrapper.find('PieChart')).toHaveLength(2);
- expect(wrapper.find('EventsTableChart')).toHaveLength(1);
- });
-});
diff --git a/tests/js/spec/views/organizationHealth/devices.spec.jsx b/tests/js/spec/views/organizationHealth/devices.spec.jsx
deleted file mode 100644
index fd3a55db0c052a..00000000000000
--- a/tests/js/spec/views/organizationHealth/devices.spec.jsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import React from 'react';
-import {mount} from 'enzyme';
-
-import OrganizationHealthDevices from 'app/views/organizationHealth/devices';
-
-jest.mock('app/utils/withLatestContext');
-jest.mock('app/views/organizationHealth/util/withHealth');
-
-describe('OrganizationHealthDevices', function() {
- const org = TestStubs.Organization();
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/health/top/',
- body: (url, opts) => {
- return TestStubs.HealthTop(opts.query);
- },
- });
-
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/health/graph/',
- body: (url, opts) => {
- return TestStubs.HealthGraph(opts.query);
- },
- });
-
- it('renders with PieChart, and EventTableChart', async function() {
- let wrapper = mount(
- <OrganizationHealthDevices
- actions={{updateParams: jest.fn(), setSpecifier: jest.fn()}}
- router={TestStubs.router()}
- organization={org}
- />,
- TestStubs.routerContext()
- );
- await tick();
- wrapper.update();
- expect(wrapper.find('PieChart')).toHaveLength(1);
- expect(wrapper.find('EventsTableChart')).toHaveLength(1);
- });
-});
diff --git a/tests/js/spec/views/organizationHealth/errors.spec.jsx b/tests/js/spec/views/organizationHealth/errors.spec.jsx
deleted file mode 100644
index 9dbe42ff706323..00000000000000
--- a/tests/js/spec/views/organizationHealth/errors.spec.jsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import React from 'react';
-import {mount} from 'enzyme';
-
-import OrganizationHealthErrors from 'app/views/organizationHealth/errors';
-
-jest.mock('app/utils/withLatestContext');
-
-describe('OrganizationHealthErrors', function() {
- const org = TestStubs.Organization();
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/health/top/',
- body: (url, opts) => {
- return TestStubs.HealthTop(opts.query);
- },
- });
-
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/health/graph/',
- body: (url, opts) => {
- return TestStubs.HealthGraph(opts.query);
- },
- });
-
- it('renders with PieChart, and EventTableChart', async function() {
- let wrapper = mount(
- <OrganizationHealthErrors organization={org} />,
- TestStubs.routerContext()
- );
- await tick();
- wrapper.update();
- expect(wrapper.find('LoadingIndicator')).toHaveLength(0);
- });
-});
diff --git a/tests/js/spec/views/organizationHealth/eventsTableChart.spec.jsx b/tests/js/spec/views/organizationHealth/eventsTableChart.spec.jsx
deleted file mode 100644
index 610b93b3a79710..00000000000000
--- a/tests/js/spec/views/organizationHealth/eventsTableChart.spec.jsx
+++ /dev/null
@@ -1,85 +0,0 @@
-import React from 'react';
-import {mount} from 'enzyme';
-import EventsTableChart from 'app/views/organizationHealth/eventsTableChart';
-
-describe('EventsTableChart', function() {
- let wrapper;
-
- beforeEach(function() {
- wrapper = mount(
- <EventsTableChart
- headers={['User', <span key="events-column">Events</span>, null, 'Last Column']}
- data={[
- {
- count: 40,
- lastCount: 20,
- name: 'billy',
- percentage: 40,
- },
- {
- count: 60,
- lastCount: 120,
- name: 'not billy',
- percentage: 60,
- },
- ]}
- />
- );
- });
-
- it('renders headers', function() {
- expect(
- wrapper.find('PanelHeader NameAndEventsContainer').prop('children')
- ).toHaveLength(2);
-
- expect(wrapper.find('PanelHeader').text()).toContain('User');
- expect(wrapper.find('PanelHeader').text()).toContain('Events');
- expect(wrapper.find('PanelHeader').text()).toContain('Last Column');
- });
-
- it('renders data rows', function() {
- expect(wrapper.find('TableChartRow')).toHaveLength(2);
-
- expect(
- wrapper
- .find('TableChartRow Name')
- .at(0)
- .text()
- ).toBe('billy');
-
- expect(
- wrapper
- .find('TableChartRow Events DeltaCaret')
- .at(0)
- .prop('direction')
- ).toBeGreaterThan(0);
-
- expect(
- wrapper
- .find('TableChartRow Bar')
- .at(0)
- .prop('width')
- ).toBe(40);
-
- expect(
- wrapper
- .find('TableChartRow Name')
- .at(1)
- .text()
- ).toBe('not billy');
-
- expect(
- wrapper
- .find('TableChartRow Events DeltaCaret')
- .at(1)
- .prop('direction')
- ).toBeLessThan(0);
-
- expect(
- wrapper
- .find('TableChartRow Bar')
- .at(1)
- .prop('width')
- ).toBe(60);
- });
-});
diff --git a/tests/js/spec/views/organizationHealth/index.spec.jsx b/tests/js/spec/views/organizationHealth/index.spec.jsx
deleted file mode 100644
index bcc76960939472..00000000000000
--- a/tests/js/spec/views/organizationHealth/index.spec.jsx
+++ /dev/null
@@ -1,83 +0,0 @@
-import React from 'react';
-
-import {OrganizationHealth} from 'app/views/organizationHealth';
-import {mount} from 'enzyme';
-import {setActiveOrganization} from 'app/actionCreators/organizations';
-
-describe('OrganizationHealth', function() {
- let wrapper;
- const router = TestStubs.router({
- location: {
- pathname: '/organizations/org-slug/health/',
- query: {},
- },
- });
- const project = TestStubs.Project({isMember: true});
- const organization = TestStubs.Organization({
- features: ['health'],
- projects: [project],
- });
-
- beforeAll(async function() {
- MockApiClient.addMockResponse({
- url: `/organizations/${organization.slug}/environments/`,
- body: TestStubs.Environments(),
- });
-
- setActiveOrganization(organization);
- await tick();
-
- wrapper = mount(
- <OrganizationHealth router={router} organization={organization}>
- <div />
- </OrganizationHealth>,
- TestStubs.routerContext([
- {
- organization,
- },
- ])
- );
- });
-
- it('renders', function() {
- expect(wrapper.find('HealthWrapper')).toHaveLength(1);
- });
-
- it('updates component state when router is updated', async function() {
- wrapper = mount(
- <OrganizationHealth router={router} organization={organization}>
- <div />
- </OrganizationHealth>,
- TestStubs.routerContext([
- {
- organization,
- },
- ])
- );
- expect(wrapper.state('environments')).toEqual([]);
-
- wrapper.setProps({
- router: {
- location: {
- pathname: '/organizations/org-slug/health/',
- query: {
- environments: ['production'],
- },
- },
- },
- });
- expect(wrapper.state('environments')).toEqual(['production']);
-
- wrapper.setProps({
- router: {
- location: {
- pathname: '/organizations/org-slug/health/',
- query: {
- environments: ['production', 'staging'],
- },
- },
- },
- });
- expect(wrapper.state('environments')).toEqual(['production', 'staging']);
- });
-});
diff --git a/tests/js/spec/views/organizationHealth/overview.spec.jsx b/tests/js/spec/views/organizationHealth/overview.spec.jsx
deleted file mode 100644
index 27b32eafdd82c4..00000000000000
--- a/tests/js/spec/views/organizationHealth/overview.spec.jsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import React from 'react';
-import {mount} from 'enzyme';
-
-import OrganizationHealthOverview from 'app/views/organizationHealth/overview';
-
-describe('OrganizationHealthOverview', function() {
- it('renders', function() {
- let wrapper = mount(<OrganizationHealthOverview />);
- expect(wrapper).toMatchSnapshot();
- });
-});
diff --git a/tests/js/spec/views/organizationHealth/transactions.spec.jsx b/tests/js/spec/views/organizationHealth/transactions.spec.jsx
deleted file mode 100644
index aefb18cbbce3a8..00000000000000
--- a/tests/js/spec/views/organizationHealth/transactions.spec.jsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import React from 'react';
-import {mount} from 'enzyme';
-
-import OrganizationHealthTransactions from 'app/views/organizationHealth/transactions';
-
-jest.mock('app/utils/withLatestContext');
-
-describe('OrganizationHealthTransactions', function() {
- const org = TestStubs.Organization();
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/health/top/',
- body: (url, opts) => {
- return TestStubs.HealthTop(opts.query);
- },
- });
-
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/health/graph/',
- body: (url, opts) => {
- return TestStubs.HealthGraph(opts.query);
- },
- });
-
- it('renders with LineChart, AreaChart, and TableChart', async function() {
- let wrapper = mount(
- <OrganizationHealthTransactions organization={org} />,
- TestStubs.routerContext()
- );
- await tick();
- wrapper.update();
- expect(wrapper.find('TableChart')).toHaveLength(1);
- expect(wrapper.find('AreaChart')).toHaveLength(1);
- expect(wrapper.find('LineChart')).toHaveLength(1);
- });
-});
diff --git a/tests/js/spec/views/organizationHealth/util/healthRequest.spec.jsx b/tests/js/spec/views/organizationHealth/util/healthRequest.spec.jsx
deleted file mode 100644
index e763f9aa3a46ac..00000000000000
--- a/tests/js/spec/views/organizationHealth/util/healthRequest.spec.jsx
+++ /dev/null
@@ -1,503 +0,0 @@
-import {mount} from 'enzyme';
-import React from 'react';
-
-import {doHealthRequest} from 'app/actionCreators/health';
-import {HealthRequestWithParams} from 'app/views/organizationHealth/util/healthRequest';
-
-const COUNT_OBJ = {
- count: 123,
- release: {
- _health_id: 'release:release-slug',
- value: {slug: 'release-slug'},
- },
-};
-
-jest.mock('app/actionCreators/health', () => {
- return {
- doHealthRequest: jest.fn(),
- };
-});
-
-describe('HealthRequest', function() {
- const project = TestStubs.Project();
- const organization = TestStubs.Organization();
- const mock = jest.fn(() => null);
- const DEFAULTS = {
- api: {},
- projects: [parseInt(project.id, 10)],
- environments: [],
- period: '24h',
- organization,
- tag: 'release',
- includePrevious: false,
- includeTimeseries: true,
- };
-
- let wrapper;
-
- describe('with props changes', function() {
- beforeAll(function() {
- doHealthRequest.mockImplementation(() =>
- Promise.resolve({
- data: [[new Date(), [COUNT_OBJ]]],
- })
- );
- wrapper = mount(
- <HealthRequestWithParams {...DEFAULTS}>{mock}</HealthRequestWithParams>
- );
- });
-
- it('makes requests', async function() {
- expect(mock).toHaveBeenNthCalledWith(
- 1,
- expect.objectContaining({
- loading: true,
- })
- );
-
- expect(mock).toHaveBeenLastCalledWith(
- expect.objectContaining({
- loading: false,
- timeseriesData: [
- {
- seriesName: expect.anything(),
- data: [
- expect.objectContaining({
- name: expect.any(Number),
- value: 123,
- }),
- ],
- },
- ],
- originalTimeseriesData: [[expect.anything(), expect.anything()]],
- tagData: null,
- originalTagData: null,
- })
- );
-
- expect(doHealthRequest).toHaveBeenCalled();
- });
-
- it('makes a new request if projects prop changes', async function() {
- doHealthRequest.mockClear();
-
- wrapper.setProps({projects: [123]});
- await tick();
- wrapper.update();
- expect(doHealthRequest).toHaveBeenCalledWith(
- expect.anything(),
- expect.objectContaining({
- projects: [123],
- })
- );
- });
-
- it('makes a new request if environments prop changes', async function() {
- doHealthRequest.mockClear();
-
- wrapper.setProps({environments: ['dev']});
- await tick();
- wrapper.update();
- expect(doHealthRequest).toHaveBeenCalledWith(
- expect.anything(),
- expect.objectContaining({
- environments: ['dev'],
- })
- );
- });
-
- it('makes a new request if period prop changes', async function() {
- doHealthRequest.mockClear();
-
- wrapper.setProps({period: '7d'});
- await tick();
- wrapper.update();
- expect(doHealthRequest).toHaveBeenCalledWith(
- expect.anything(),
- expect.objectContaining({
- period: '7d',
- })
- );
- });
-
- it('makes a new request if includeTimeseries prop changes', async function() {
- doHealthRequest.mockClear();
-
- wrapper.setProps({includeTimeseries: false, includeTop: true});
- await tick();
- wrapper.update();
- expect(doHealthRequest).toHaveBeenCalledWith(
- expect.anything(),
- expect.objectContaining({
- timeseries: false,
- })
- );
- });
- });
-
- describe('transforms', function() {
- beforeEach(function() {
- doHealthRequest.mockClear();
- });
-
- it('defines a category name getter', async function() {
- doHealthRequest.mockImplementation(() =>
- Promise.resolve({
- data: [[new Date(), [COUNT_OBJ]]],
- })
- );
- wrapper = mount(
- <HealthRequestWithParams
- {...DEFAULTS}
- getCategory={release => release && release.slug}
- >
- {mock}
- </HealthRequestWithParams>
- );
- await tick();
- wrapper.update();
- expect(mock).toHaveBeenLastCalledWith(
- expect.objectContaining({
- loading: false,
- timeseriesData: [
- {
- seriesName: 'release-slug',
- data: [
- expect.objectContaining({
- name: expect.anything(),
- value: 123,
- }),
- ],
- },
- ],
- originalTimeseriesData: [[expect.anything(), expect.anything()]],
- })
- );
- });
-
- it('expands period in query if `includePrevious` and `timeseries`', async function() {
- doHealthRequest.mockImplementation(() =>
- Promise.resolve({
- data: [
- [new Date(), [{...COUNT_OBJ, count: 321}, {...COUNT_OBJ, count: 79}]],
- [new Date(), [COUNT_OBJ]],
- ],
- })
- );
- wrapper = mount(
- <HealthRequestWithParams
- {...DEFAULTS}
- includeTimeseries={true}
- includePrevious={true}
- getCategory={({slug} = {}) => slug}
- >
- {mock}
- </HealthRequestWithParams>
- );
-
- await tick();
- wrapper.update();
-
- // actionCreator handles expanding the period when calling the API
- expect(doHealthRequest).toHaveBeenCalledWith(
- expect.anything(),
- expect.objectContaining({
- period: '24h',
- })
- );
-
- expect(mock).toHaveBeenLastCalledWith(
- expect.objectContaining({
- loading: false,
- allTimeseriesData: [
- [
- expect.anything(),
- [
- expect.objectContaining({count: 321}),
- expect.objectContaining({count: 79}),
- ],
- ],
- [expect.anything(), [expect.objectContaining({count: 123})]],
- ],
- timeseriesData: [
- {
- seriesName: expect.anything(),
- data: [
- expect.objectContaining({
- name: expect.anything(),
- value: 123,
- }),
- ],
- },
- ],
- previousTimeseriesData: {
- seriesName: 'Previous Period',
- data: [
- expect.objectContaining({
- name: expect.anything(),
- value: 400,
- }),
- ],
- },
-
- originalTimeseriesData: [
- [expect.anything(), [expect.objectContaining({count: 123})]],
- ],
-
- originalPreviousTimeseriesData: [
- [
- expect.anything(),
- [
- expect.objectContaining({count: 321}),
- expect.objectContaining({count: 79}),
- ],
- ],
- ],
- })
- );
- });
-
- it('transforms data for non-timeseries response', async function() {
- doHealthRequest.mockImplementation(() =>
- Promise.resolve({
- data: [COUNT_OBJ],
- })
- );
- wrapper = mount(
- <HealthRequestWithParams
- {...DEFAULTS}
- includeTimeseries={false}
- includeTop={true}
- getCategory={({slug} = {}) => slug}
- >
- {mock}
- </HealthRequestWithParams>
- );
-
- await tick();
- wrapper.update();
-
- expect(mock).toHaveBeenLastCalledWith(
- expect.objectContaining({
- loading: false,
- tagData: [['release-slug', 123]],
- originalTagData: [
- {
- count: 123,
- release: {
- value: {slug: 'release-slug'},
- _health_id: 'release:release-slug',
- },
- },
- ],
- })
- );
- });
-
- it('transforms data with percentages only when `includPercentages` prop is true', async function() {
- doHealthRequest.mockImplementation(() =>
- Promise.resolve({
- data: [
- {...COUNT_OBJ, count: 100, lastCount: 50},
- {
- count: 80,
- lastCount: 100,
- release: {
- value: {
- slug: 'new-release',
- },
- },
- },
- ],
- totals: {
- count: 180,
- },
- })
- );
-
- wrapper = mount(
- <HealthRequestWithParams
- {...DEFAULTS}
- includeTimeseries={false}
- includeTop={true}
- includePercentages={false}
- getCategory={({slug} = {}) => slug}
- >
- {mock}
- </HealthRequestWithParams>
- );
-
- await tick();
- wrapper.update();
-
- expect(mock).toHaveBeenLastCalledWith(
- expect.objectContaining({
- tagDataWithPercentages: null,
- })
- );
-
- wrapper.setProps({includePercentages: true});
- await tick();
- wrapper.update();
-
- expect(mock).toHaveBeenLastCalledWith(
- expect.objectContaining({
- tagDataWithPercentages: [
- expect.objectContaining({
- count: 100,
- lastCount: 50,
- percentage: 55.56,
- }),
- expect.objectContaining({
- count: 80,
- lastCount: 100,
- percentage: 44.44,
- }),
- ],
- })
- );
- });
-
- it('aggregates counts per timestamp only when `includeTimeAggregation` prop is true', async function() {
- doHealthRequest.mockImplementation(() =>
- Promise.resolve({
- data: [[new Date(), [COUNT_OBJ, {...COUNT_OBJ, count: 100}]]],
- })
- );
-
- wrapper = mount(
- <HealthRequestWithParams
- {...DEFAULTS}
- includeTimeseries={true}
- getCategory={({slug} = {}) => slug}
- >
- {mock}
- </HealthRequestWithParams>
- );
-
- await tick();
- wrapper.update();
-
- expect(mock).toHaveBeenLastCalledWith(
- expect.objectContaining({
- timeAggregatedData: null,
- })
- );
-
- wrapper.setProps({
- includeTimeAggregation: true,
- timeAggregationSeriesName: 'aggregated series',
- });
- await tick();
- wrapper.update();
-
- expect(mock).toHaveBeenLastCalledWith(
- expect.objectContaining({
- timeAggregatedData: {
- seriesName: 'aggregated series',
- data: [{name: expect.anything(), value: 223}],
- },
- })
- );
- });
-
- it('aggregates all counts per timestamp when category name identical', async function() {
- doHealthRequest.mockImplementation(() =>
- Promise.resolve({
- data: [[new Date(), [COUNT_OBJ, {...COUNT_OBJ, count: 100}]]],
- })
- );
-
- wrapper = mount(
- <HealthRequestWithParams
- {...DEFAULTS}
- includeTimeseries={true}
- getCategory={() => 'static-category'}
- >
- {mock}
- </HealthRequestWithParams>
- );
-
- await tick();
- wrapper.update();
-
- expect(mock).toHaveBeenLastCalledWith(
- expect.objectContaining({
- timeAggregatedData: null,
- })
- );
-
- wrapper.setProps({
- includeTimeAggregation: true,
- timeAggregationSeriesName: 'aggregated series',
- });
- await tick();
- wrapper.update();
-
- expect(mock).toHaveBeenLastCalledWith(
- expect.objectContaining({
- timeAggregatedData: {
- seriesName: 'aggregated series',
- data: [{name: expect.anything(), value: 223}],
- },
- })
- );
- });
-
- it('transparently queries for top tags and then queries for timeseries data using only those top tags', async function() {
- doHealthRequest.mockClear();
- doHealthRequest.mockImplementation((api, props) => {
- if (props.timeseries) {
- return Promise.resolve({
- data: [[new Date(), [COUNT_OBJ, {...COUNT_OBJ, count: 100}]]],
- });
- }
-
- return Promise.resolve({
- data: [{...COUNT_OBJ, count: 100}],
- totals: {
- count: 100,
- lastCount: 50,
- },
- });
- });
-
- wrapper = mount(
- <HealthRequestWithParams
- {...DEFAULTS}
- includeTop
- includeTimeseries
- includePercentages
- includeTimeAggregation
- includePrevious
- timeAggregationSeriesName="Aggregated"
- getCategory={({slug} = {}) => slug}
- >
- {mock}
- </HealthRequestWithParams>
- );
-
- await tick();
- wrapper.update();
-
- expect(doHealthRequest).toHaveBeenCalledTimes(2);
- expect(doHealthRequest).toHaveBeenNthCalledWith(
- 2,
- expect.anything(),
- expect.objectContaining({
- timeseries: true,
- specifiers: ['release:release-slug'],
- })
- );
-
- expect(mock).toHaveBeenLastCalledWith(
- expect.objectContaining({
- timeAggregatedData: {
- seriesName: 'Aggregated',
- data: [{name: expect.anything(), value: 223}],
- },
- })
- );
- });
- });
-});
|
e97372fd67de6cf06d841e7bc34e75fd042552e2
|
2018-07-09 21:10:08
|
MeredithAnya
|
feat(ui): Add ConfirmDelete component (#8927)
| false
|
Add ConfirmDelete component (#8927)
|
feat
|
diff --git a/docs-ui/components/confirmDelete.stories.js b/docs-ui/components/confirmDelete.stories.js
new file mode 100644
index 00000000000000..a8f6d8b3851fab
--- /dev/null
+++ b/docs-ui/components/confirmDelete.stories.js
@@ -0,0 +1,25 @@
+import React from 'react';
+import {storiesOf} from '@storybook/react';
+import {withInfo} from '@storybook/addon-info';
+import {action} from '@storybook/addon-actions';
+
+import ConfirmDelete from 'app/components/confirmDelete';
+import Button from 'app/components/buttons/button';
+
+storiesOf('Confirm/ConfirmDelete', module).add(
+ 'default',
+ withInfo({
+ text: 'A Confirm Modal that requires a user to enter a confirmation string.',
+ propTablesExclude: [Button],
+ })(() => (
+ <div>
+ <ConfirmDelete
+ onConfirm={action('confirmed')}
+ confirmInput="Type this out"
+ message="Are you sure you want to do this?"
+ >
+ <Button priority="primary">Confirm on Button click</Button>
+ </ConfirmDelete>
+ </div>
+ ))
+);
diff --git a/src/sentry/static/sentry/app/components/confirm.jsx b/src/sentry/static/sentry/app/components/confirm.jsx
index f49675d44092ff..771159f6e54a61 100644
--- a/src/sentry/static/sentry/app/components/confirm.jsx
+++ b/src/sentry/static/sentry/app/components/confirm.jsx
@@ -22,37 +22,48 @@ class Confirm extends React.PureComponent {
* `close`: Allows renderer to toggle confirm modal
*/
renderMessage: PropTypes.func,
-
disabled: PropTypes.bool,
+ disableConfirmButton: PropTypes.bool,
onConfirming: PropTypes.func,
onCancel: PropTypes.func,
};
static defaultProps = {
priority: 'primary',
+ disableConfirmButton: false,
cancelText: t('Cancel'),
confirmText: t('Confirm'),
};
- constructor(...args) {
- super(...args);
+ static getDerivedStateFromProps(props, state) {
+ // Reset the state to handle prop changes from ConfirmDelete
+ if (props.disableConfirmButton !== state.disableConfirmButton) {
+ return {
+ disableConfirmButton: props.disableConfirmButton,
+ };
+ }
+ return null;
+ }
+
+ constructor(props) {
+ super(props);
this.state = {
isModalOpen: false,
- disableConfirmButton: false,
+ disableConfirmButton: props.disableConfirmButton,
};
this.confirming = false;
}
openModal = () => {
- let {onConfirming} = this.props;
+ let {onConfirming, disableConfirmButton} = this.props;
if (typeof onConfirming === 'function') {
onConfirming();
}
this.setState(state => ({
isModalOpen: true,
- disableConfirmButton: false,
+ disableConfirmButton,
}));
// always reset `confirming` when modal visibility changes
@@ -60,13 +71,13 @@ class Confirm extends React.PureComponent {
};
closeModal = () => {
- let {onCancel} = this.props;
+ let {onCancel, disableConfirmButton} = this.props;
if (typeof onCancel === 'function') {
onCancel();
}
this.setState(state => ({
isModalOpen: false,
- disableConfirmButton: false,
+ disableConfirmButton,
}));
// always reset `confirming` when modal visibility changes
@@ -138,7 +149,10 @@ class Confirm extends React.PureComponent {
close: this.closeModal,
open: this.openModal,
})
- : React.cloneElement(children, {disabled, onClick: this.handleToggle})}
+ : React.cloneElement(children, {
+ disabled,
+ onClick: this.handleToggle,
+ })}
<Modal show={this.state.isModalOpen} animation={false} onHide={this.handleToggle}>
<div className="modal-body">{confirmMessage}</div>
<div className="modal-footer">
diff --git a/src/sentry/static/sentry/app/components/confirmDelete.jsx b/src/sentry/static/sentry/app/components/confirmDelete.jsx
new file mode 100644
index 00000000000000..6b65ff9699d828
--- /dev/null
+++ b/src/sentry/static/sentry/app/components/confirmDelete.jsx
@@ -0,0 +1,88 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+import Confirm from 'app/components/confirm';
+import Alert from 'app/components/alert';
+import Input from 'app/views/settings/components/forms/controls/input';
+import Field from 'app/views/settings/components/forms/field';
+import {t} from 'app/locale';
+
+class ConfirmDelete extends React.PureComponent {
+ static propTypes = {
+ onConfirm: PropTypes.func.isRequired,
+ confirmText: PropTypes.string.isRequired,
+ confirmInput: PropTypes.string.isRequired,
+ cancelText: PropTypes.string.isRequired,
+ priority: PropTypes.oneOf(['primary', 'danger']).isRequired,
+ message: PropTypes.node,
+ /**
+ * Renderer that passes:
+ * `confirm`: Allows renderer to perform confirm action
+ * `close`: Allows renderer to toggle confirm modal
+ */
+ renderMessage: PropTypes.func,
+ disabled: PropTypes.bool,
+ onConfirming: PropTypes.func,
+ onCancel: PropTypes.func,
+ };
+
+ static defaultProps = {
+ priority: 'primary',
+ cancelText: t('Cancel'),
+ confirmText: t('Confirm'),
+ };
+
+ constructor(...args) {
+ super(...args);
+
+ this.state = {
+ disableConfirmButton: true,
+ confirmInput: '',
+ };
+ }
+
+ handleChange = evt => {
+ let input = evt.target.value;
+ if (input === this.props.confirmInput) {
+ this.setState({disableConfirmButton: false, confirmInput: input});
+ } else {
+ this.setState({disableConfirmButton: true, confirmInput: input});
+ }
+ };
+
+ render() {
+ let {confirmInput, message, ...props} = this.props;
+ let {disableConfirmButton} = this.state;
+
+ return (
+ <Confirm
+ {...props}
+ bypass={false}
+ disableConfirmButton={disableConfirmButton}
+ message={
+ <React.Fragment>
+ <Alert type="error">{message}</Alert>
+ <Field
+ p={0}
+ flexibleControlStateSize={true}
+ inline={false}
+ label={
+ <div>
+ Please enter <code>{confirmInput}</code> to confirm the deletion
+ </div>
+ }
+ >
+ <Input
+ type="text"
+ placeholder={confirmInput}
+ onChange={this.handleChange}
+ value={this.state.confirmInput}
+ />
+ </Field>
+ </React.Fragment>
+ }
+ />
+ );
+ }
+}
+
+export default ConfirmDelete;
diff --git a/tests/js/spec/components/__snapshots__/confirmDelete.spec.jsx.snap b/tests/js/spec/components/__snapshots__/confirmDelete.spec.jsx.snap
new file mode 100644
index 00000000000000..b93ef476f1cb54
--- /dev/null
+++ b/tests/js/spec/components/__snapshots__/confirmDelete.spec.jsx.snap
@@ -0,0 +1,382 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`ConfirmDelete renders 1`] = `
+<ModalDialog
+ bsClass="modal"
+ className="in"
+ onClick={[Function]}
+ role="document"
+ style={Object {}}
+ tabIndex="-1"
+>
+ <div
+ className="in modal"
+ onClick={[Function]}
+ role="dialog"
+ style={
+ Object {
+ "display": "block",
+ }
+ }
+ tabIndex="-1"
+ >
+ <div
+ className="modal-dialog"
+ >
+ <div
+ className="modal-content"
+ role="document"
+ >
+ <div
+ className="modal-body"
+ >
+ <Alert
+ type="error"
+ >
+ <AlertWrapper
+ className="ref-error"
+ type="error"
+ >
+ <div
+ className="ref-error css-1gmjigt-AlertWrapper e1xb5l7j1"
+ type="error"
+ >
+ <StyledTextBlock>
+ <Component
+ className="css-1h3n7tg-TextBlock-StyledTextBlock e1xb5l7j2"
+ >
+ <div
+ className="css-1h3n7tg-TextBlock-StyledTextBlock e1xb5l7j2"
+ >
+ Are you sure?
+ </div>
+ </Component>
+ </StyledTextBlock>
+ </div>
+ </AlertWrapper>
+ </Alert>
+ <Field
+ alignRight={false}
+ disabled={false}
+ flexibleControlStateSize={true}
+ inline={false}
+ label={
+ <div>
+ Please enter
+ <code>
+ CoolOrg
+ </code>
+ to confirm the deletion
+ </div>
+ }
+ p={0}
+ required={false}
+ visible={true}
+ >
+ <FieldWrapper
+ hasControlState={false}
+ inline={false}
+ p={0}
+ >
+ <Component
+ className="css-1vm8clh-FieldWrapper-inlineStyle etqqcs20"
+ hasControlState={false}
+ inline={false}
+ p={0}
+ >
+ <Flex
+ className="css-1vm8clh-FieldWrapper-inlineStyle etqqcs20"
+ >
+ <Base
+ className="etqqcs20 css-1hq624p-FieldWrapper-inlineStyle"
+ >
+ <div
+ className="etqqcs20 css-1hq624p-FieldWrapper-inlineStyle"
+ is={null}
+ >
+ <FieldDescription
+ inline={false}
+ >
+ <Component
+ className="css-19gs2h3-FieldDescription-inlineStyle e12jefmo0"
+ inline={false}
+ >
+ <label
+ className="css-19gs2h3-FieldDescription-inlineStyle e12jefmo0"
+ >
+ <FieldLabel>
+ <div
+ className="css-qzvhly-FieldLabel ejkuyjq0"
+ >
+ <div>
+ Please enter
+ <code>
+ CoolOrg
+ </code>
+ to confirm the deletion
+ </div>
+
+ </div>
+ </FieldLabel>
+ </label>
+ </Component>
+ </FieldDescription>
+ <FieldControl
+ alignRight={false}
+ disabled={false}
+ flexibleControlStateSize={true}
+ inline={false}
+ >
+ <FieldControlErrorWrapper
+ inline={false}
+ >
+ <Component
+ className="css-1ge7tqf-FieldControlErrorWrapper e78b1iv0"
+ inline={false}
+ >
+ <Box
+ className="css-1ge7tqf-FieldControlErrorWrapper e78b1iv0"
+ >
+ <Base
+ className="e78b1iv0 css-nnn2ut-FieldControlErrorWrapper"
+ >
+ <div
+ className="e78b1iv0 css-nnn2ut-FieldControlErrorWrapper"
+ is={null}
+ >
+ <FieldControlWrapper>
+ <Component
+ className="css-1ke1xob-FieldControlWrapper e78b1iv2"
+ >
+ <Flex
+ className="css-1ke1xob-FieldControlWrapper e78b1iv2"
+ >
+ <Base
+ className="e78b1iv2 css-w4o1g8-FieldControlWrapper"
+ >
+ <div
+ className="e78b1iv2 css-w4o1g8-FieldControlWrapper"
+ is={null}
+ >
+ <FieldControlStyled
+ alignRight={false}
+ >
+ <Component
+ alignRight={false}
+ className="css-1pkvhmy-FieldControlStyled e78b1iv1"
+ >
+ <Box
+ className="css-1pkvhmy-FieldControlStyled e78b1iv1"
+ >
+ <Base
+ className="e78b1iv1 css-wkkbba-FieldControlStyled"
+ >
+ <div
+ className="e78b1iv1 css-wkkbba-FieldControlStyled"
+ is={null}
+ >
+ <Input
+ onChange={[Function]}
+ placeholder="CoolOrg"
+ type="text"
+ value=""
+ >
+ <input
+ className="css-1m7xmcf-Input-inputStyles e1xej46s0"
+ onChange={[Function]}
+ placeholder="CoolOrg"
+ type="text"
+ value=""
+ />
+ </Input>
+ </div>
+ </Base>
+ </Box>
+ </Component>
+ </FieldControlStyled>
+ <FieldControlState
+ flexibleControlStateSize={true}
+ >
+ <Component
+ className="css-1x60lk6-FieldControlState e1rziqw00"
+ flexibleControlStateSize={true}
+ >
+ <Flex
+ className="css-1x60lk6-FieldControlState e1rziqw00"
+ >
+ <Base
+ className="e1rziqw00 css-dgyrfj-FieldControlState"
+ >
+ <div
+ className="e1rziqw00 css-dgyrfj-FieldControlState"
+ is={null}
+ />
+ </Base>
+ </Flex>
+ </Component>
+ </FieldControlState>
+ </div>
+ </Base>
+ </Flex>
+ </Component>
+ </FieldControlWrapper>
+ </div>
+ </Base>
+ </Box>
+ </Component>
+ </FieldControlErrorWrapper>
+ </FieldControl>
+ </div>
+ </Base>
+ </Flex>
+ </Component>
+ </FieldWrapper>
+ </Field>
+ </div>
+ <div
+ className="modal-footer"
+ >
+ <Button
+ disabled={false}
+ onClick={[Function]}
+ style={
+ Object {
+ "marginRight": 10,
+ }
+ }
+ >
+ <StyledButton
+ aria-label="Cancel"
+ disabled={false}
+ onClick={[Function]}
+ role="button"
+ style={
+ Object {
+ "marginRight": 10,
+ }
+ }
+ >
+ <Component
+ aria-label="Cancel"
+ className="css-cmo08-StyledButton-getColors e17811v30"
+ disabled={false}
+ onClick={[Function]}
+ role="button"
+ style={
+ Object {
+ "marginRight": 10,
+ }
+ }
+ >
+ <button
+ aria-label="Cancel"
+ className="css-cmo08-StyledButton-getColors e17811v30"
+ disabled={false}
+ onClick={[Function]}
+ role="button"
+ style={
+ Object {
+ "marginRight": 10,
+ }
+ }
+ >
+ <ButtonLabel>
+ <Component
+ className="css-1dxlw1i-ButtonLabel e17811v31"
+ >
+ <Flex
+ align="center"
+ className="css-1dxlw1i-ButtonLabel e17811v31"
+ >
+ <Base
+ align="center"
+ className="e17811v31 css-mvnt76-ButtonLabel"
+ >
+ <div
+ className="e17811v31 css-mvnt76-ButtonLabel"
+ is={null}
+ >
+ Cancel
+ </div>
+ </Base>
+ </Flex>
+ </Component>
+ </ButtonLabel>
+ </button>
+ </Component>
+ </StyledButton>
+ </Button>
+ <Button
+ autoFocus={true}
+ data-test-id="confirm-modal"
+ disabled={true}
+ onClick={[Function]}
+ priority="primary"
+ >
+ <StyledButton
+ aria-label="Confirm"
+ autoFocus={true}
+ data-test-id="confirm-modal"
+ disabled={true}
+ href={null}
+ onClick={[Function]}
+ priority="primary"
+ role="button"
+ to={null}
+ >
+ <Component
+ aria-label="Confirm"
+ autoFocus={true}
+ className="css-fn4jle-StyledButton-getColors e17811v30"
+ data-test-id="confirm-modal"
+ disabled={true}
+ href={null}
+ onClick={[Function]}
+ priority="primary"
+ role="button"
+ to={null}
+ >
+ <button
+ aria-label="Confirm"
+ autoFocus={true}
+ className="css-fn4jle-StyledButton-getColors e17811v30"
+ data-test-id="confirm-modal"
+ disabled={true}
+ href={null}
+ onClick={[Function]}
+ priority="primary"
+ role="button"
+ to={null}
+ >
+ <ButtonLabel>
+ <Component
+ className="css-1dxlw1i-ButtonLabel e17811v31"
+ >
+ <Flex
+ align="center"
+ className="css-1dxlw1i-ButtonLabel e17811v31"
+ >
+ <Base
+ align="center"
+ className="e17811v31 css-mvnt76-ButtonLabel"
+ >
+ <div
+ className="e17811v31 css-mvnt76-ButtonLabel"
+ is={null}
+ >
+ Confirm
+ </div>
+ </Base>
+ </Flex>
+ </Component>
+ </ButtonLabel>
+ </button>
+ </Component>
+ </StyledButton>
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+</ModalDialog>
+`;
diff --git a/tests/js/spec/components/actions/__snapshots__/ignore.spec.jsx.snap b/tests/js/spec/components/actions/__snapshots__/ignore.spec.jsx.snap
index c815cec494aa45..b6e31aac9dd32e 100644
--- a/tests/js/spec/components/actions/__snapshots__/ignore.spec.jsx.snap
+++ b/tests/js/spec/components/actions/__snapshots__/ignore.spec.jsx.snap
@@ -245,6 +245,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -456,6 +457,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -550,6 +552,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -644,6 +647,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -738,6 +742,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -832,6 +837,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -1035,6 +1041,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -1123,6 +1130,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -1211,6 +1219,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -1299,6 +1308,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -1431,6 +1441,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -1519,6 +1530,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -1607,6 +1619,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -1695,6 +1708,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -1827,6 +1841,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -1915,6 +1930,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -2003,6 +2019,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -2091,6 +2108,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -2223,6 +2241,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -2311,6 +2330,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -2399,6 +2419,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -2487,6 +2508,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -2619,6 +2641,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -2707,6 +2730,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -2795,6 +2819,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -2883,6 +2908,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -3085,6 +3111,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -3173,6 +3200,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -3261,6 +3289,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -3349,6 +3378,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -3481,6 +3511,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -3569,6 +3600,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -3657,6 +3689,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -3745,6 +3778,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -3877,6 +3911,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -3965,6 +4000,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -4053,6 +4089,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -4141,6 +4178,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -4273,6 +4311,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -4361,6 +4400,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -4449,6 +4489,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -4537,6 +4578,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -4669,6 +4711,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -4757,6 +4800,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -4845,6 +4889,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
@@ -4933,6 +4978,7 @@ exports[`IgnoreActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Ignore"
+ disableConfirmButton={false}
message="Yoooooo"
onConfirm={[Function]}
priority="primary"
diff --git a/tests/js/spec/components/actions/__snapshots__/resolve.spec.jsx.snap b/tests/js/spec/components/actions/__snapshots__/resolve.spec.jsx.snap
index 2165057dd1282a..cbd96b0d0a139a 100644
--- a/tests/js/spec/components/actions/__snapshots__/resolve.spec.jsx.snap
+++ b/tests/js/spec/components/actions/__snapshots__/resolve.spec.jsx.snap
@@ -95,6 +95,7 @@ exports[`ResolveActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Resolve"
+ disableConfirmButton={false}
message="Are you sure???"
onConfirm={[Function]}
priority="primary"
@@ -271,6 +272,7 @@ exports[`ResolveActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Resolve"
+ disableConfirmButton={false}
message="Are you sure???"
onConfirm={[Function]}
priority="primary"
@@ -353,6 +355,7 @@ exports[`ResolveActions with confirmation step renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Resolve"
+ disableConfirmButton={false}
message="Are you sure???"
onConfirm={[Function]}
priority="primary"
diff --git a/tests/js/spec/components/confirmDelete.spec.jsx b/tests/js/spec/components/confirmDelete.spec.jsx
new file mode 100644
index 00000000000000..da97b641c1ad2f
--- /dev/null
+++ b/tests/js/spec/components/confirmDelete.spec.jsx
@@ -0,0 +1,73 @@
+import React from 'react';
+import {mount} from 'enzyme';
+import ConfirmDelete from 'app/components/confirmDelete';
+
+describe('ConfirmDelete', function() {
+ it('renders', function() {
+ let mock = jest.fn();
+ let wrapper = mount(
+ <ConfirmDelete message="Are you sure?" onConfirm={mock} confirmInput="CoolOrg">
+ <button>Confirm?</button>
+ </ConfirmDelete>,
+ TestStubs.routerContext()
+ );
+ wrapper.find('button').simulate('click');
+ // jest had an issue rendering root component snapshot so using ModalDialog instead
+ expect(wrapper.find('ModalDialog')).toMatchSnapshot();
+ });
+
+ it('confirm button is disabled and bypass prop is false when modal opens', function() {
+ let mock = jest.fn();
+ let wrapper = mount(
+ <ConfirmDelete message="Are you sure?" onConfirm={mock} confirmInput="CoolOrg">
+ <button>Confirm?</button>
+ </ConfirmDelete>,
+ TestStubs.routerContext()
+ );
+
+ wrapper.find('button').simulate('click');
+
+ expect(wrapper.find('Confirm').prop('bypass')).toBe(false);
+ expect(wrapper.state('disableConfirmButton')).toBe(true);
+ });
+
+ it('confirm button stays disabled with non-matching input', function() {
+ let mock = jest.fn();
+ let wrapper = mount(
+ <ConfirmDelete message="Are you sure?" onConfirm={mock} confirmInput="CoolOrg">
+ <button>Confirm?</button>
+ </ConfirmDelete>,
+ TestStubs.routerContext()
+ );
+ wrapper.find('button').simulate('click');
+ wrapper.find('input').simulate('change', {target: {value: 'Cool'}});
+ expect(wrapper.find('Confirm').prop('disableConfirmButton')).toBe(true);
+ });
+
+ it('confirm button is enabled when confirm input matches', function() {
+ let mock = jest.fn();
+ let wrapper = mount(
+ <ConfirmDelete message="Are you sure?" onConfirm={mock} confirmInput="CoolOrg">
+ <button>Confirm?</button>
+ </ConfirmDelete>,
+ TestStubs.routerContext()
+ );
+ wrapper.find('button').simulate('click');
+ wrapper.find('input').simulate('change', {target: {value: 'CoolOrg'}});
+ expect(wrapper.find('Confirm').prop('disableConfirmButton')).toBe(false);
+
+ wrapper
+ .find('Button')
+ .last()
+ .simulate('click');
+
+ expect(
+ wrapper
+ .find('Modal')
+ .first()
+ .prop('show')
+ ).toBe(false);
+ expect(mock).toHaveBeenCalled();
+ expect(mock.mock.calls).toHaveLength(1);
+ });
+});
diff --git a/tests/js/spec/views/__snapshots__/groupMergedView.spec.jsx.snap b/tests/js/spec/views/__snapshots__/groupMergedView.spec.jsx.snap
index 2053193e354cd6..7ac22160508f9a 100644
--- a/tests/js/spec/views/__snapshots__/groupMergedView.spec.jsx.snap
+++ b/tests/js/spec/views/__snapshots__/groupMergedView.spec.jsx.snap
@@ -320,6 +320,7 @@ exports[`Issues -> Merged View renders with mocked data 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Confirm"
+ disableConfirmButton={false}
disabled={true}
message="These events will be unmerged and grouped into a new issue. Are you sure you want to unmerge these events?"
onConfirm={[Function]}
@@ -1784,6 +1785,7 @@ exports[`Issues -> Merged View renders with mocked data 2`] = `
<Confirm
cancelText="Cancel"
confirmText="Confirm"
+ disableConfirmButton={false}
disabled={true}
message="These events will be unmerged and grouped into a new issue. Are you sure you want to unmerge these events?"
onConfirm={[Function]}
diff --git a/tests/js/spec/views/__snapshots__/groupSimilarView.spec.jsx.snap b/tests/js/spec/views/__snapshots__/groupSimilarView.spec.jsx.snap
index 68e8ae9122839f..f2731d2555b0ce 100644
--- a/tests/js/spec/views/__snapshots__/groupSimilarView.spec.jsx.snap
+++ b/tests/js/spec/views/__snapshots__/groupSimilarView.spec.jsx.snap
@@ -400,6 +400,7 @@ exports[`Issues Similar View renders with mocked data 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Confirm"
+ disableConfirmButton={false}
disabled={true}
message="Are you sure you want to merge these issues?"
onConfirm={[Function]}
diff --git a/tests/js/spec/views/__snapshots__/projectAlertRules.spec.jsx.snap b/tests/js/spec/views/__snapshots__/projectAlertRules.spec.jsx.snap
index 1bf4fd0099da92..c3aaa13e92314b 100644
--- a/tests/js/spec/views/__snapshots__/projectAlertRules.spec.jsx.snap
+++ b/tests/js/spec/views/__snapshots__/projectAlertRules.spec.jsx.snap
@@ -521,6 +521,7 @@ exports[`projectAlertRules renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Confirm"
+ disableConfirmButton={false}
disabled={false}
message="Are you sure you want to remove this rule?"
onConfirm={[Function]}
diff --git a/tests/js/spec/views/__snapshots__/projectSavedSearches.spec.jsx.snap b/tests/js/spec/views/__snapshots__/projectSavedSearches.spec.jsx.snap
index baea0a7f88b8d0..20d5e703e45d28 100644
--- a/tests/js/spec/views/__snapshots__/projectSavedSearches.spec.jsx.snap
+++ b/tests/js/spec/views/__snapshots__/projectSavedSearches.spec.jsx.snap
@@ -347,6 +347,7 @@ exports[`ProjectSavedSearches renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Confirm"
+ disableConfirmButton={false}
message="Are you sure you want to remove this?"
onConfirm={[Function]}
priority="primary"
@@ -680,6 +681,7 @@ exports[`ProjectSavedSearches renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Confirm"
+ disableConfirmButton={false}
message="Are you sure you want to remove this?"
onConfirm={[Function]}
priority="primary"
diff --git a/tests/js/spec/views/__snapshots__/projectTags.spec.jsx.snap b/tests/js/spec/views/__snapshots__/projectTags.spec.jsx.snap
index 00955b3f783cb1..943bb52b9d417b 100644
--- a/tests/js/spec/views/__snapshots__/projectTags.spec.jsx.snap
+++ b/tests/js/spec/views/__snapshots__/projectTags.spec.jsx.snap
@@ -217,6 +217,7 @@ exports[`ProjectTags renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Confirm"
+ disableConfirmButton={false}
disabled={false}
message="Are you sure you want to remove this tag?"
onConfirm={[Function]}
@@ -462,6 +463,7 @@ exports[`ProjectTags renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Confirm"
+ disableConfirmButton={false}
disabled={false}
message="Are you sure you want to remove this tag?"
onConfirm={[Function]}
@@ -707,6 +709,7 @@ exports[`ProjectTags renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Confirm"
+ disableConfirmButton={false}
disabled={false}
message="Are you sure you want to remove this tag?"
onConfirm={[Function]}
@@ -959,6 +962,7 @@ exports[`ProjectTags renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Confirm"
+ disableConfirmButton={false}
disabled={true}
message="Are you sure you want to remove this tag?"
onConfirm={[Function]}
diff --git a/tests/js/spec/views/settings/__snapshots__/organizationApiKeysList.spec.jsx.snap b/tests/js/spec/views/settings/__snapshots__/organizationApiKeysList.spec.jsx.snap
index 6fddc2d1074cbb..7c754e369affb4 100644
--- a/tests/js/spec/views/settings/__snapshots__/organizationApiKeysList.spec.jsx.snap
+++ b/tests/js/spec/views/settings/__snapshots__/organizationApiKeysList.spec.jsx.snap
@@ -515,6 +515,7 @@ exports[`OrganizationApiKeysList renders 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Confirm"
+ disableConfirmButton={false}
message="Are you sure you want to remove this API key?"
onConfirm={[Function]}
priority="primary"
diff --git a/tests/js/spec/views/settings/__snapshots__/organizationRepositories.spec.jsx.snap b/tests/js/spec/views/settings/__snapshots__/organizationRepositories.spec.jsx.snap
index 6ca05e624c6b48..9240c29279bcf1 100644
--- a/tests/js/spec/views/settings/__snapshots__/organizationRepositories.spec.jsx.snap
+++ b/tests/js/spec/views/settings/__snapshots__/organizationRepositories.spec.jsx.snap
@@ -99,6 +99,7 @@ exports[`OrganizationRepositories renders with a repository 1`] = `
<Confirm
cancelText="Cancel"
confirmText="Confirm"
+ disableConfirmButton={false}
disabled={false}
message="Are you sure you want to remove this repository?"
onConfirm={[Function]}
|
b60ed5cae0ed01ce734ceccd22d46e5343cd2338
|
2023-07-05 21:31:06
|
Malachi Willey
|
feat(issue-details): Add analytics for event has_profile (#52049)
| false
|
Add analytics for event has_profile (#52049)
|
feat
|
diff --git a/static/app/types/event.tsx b/static/app/types/event.tsx
index c6ad2a208b5d33..75c0fa2178cae0 100644
--- a/static/app/types/event.tsx
+++ b/static/app/types/event.tsx
@@ -648,6 +648,7 @@ type EventContexts = {
// TODO (udameli): add better types here
// once perf issue data shape is more clear
performance_issue?: any;
+ profile?: ProfileContext;
replay?: ReplayContext;
response?: ResponseContext;
runtime?: RuntimeContext;
diff --git a/static/app/utils/analytics/workflowAnalyticsEvents.tsx b/static/app/utils/analytics/workflowAnalyticsEvents.tsx
index 686b77135f05b4..1e09ada173876e 100644
--- a/static/app/utils/analytics/workflowAnalyticsEvents.tsx
+++ b/static/app/utils/analytics/workflowAnalyticsEvents.tsx
@@ -21,6 +21,7 @@ export type BaseEventAnalyticsParams = {
event_id: string;
has_commit: boolean;
has_exception_group: boolean;
+ has_profile: boolean;
has_release: boolean;
has_source_context: boolean;
has_source_maps: boolean;
diff --git a/static/app/utils/events.tsx b/static/app/utils/events.tsx
index a060b7d3e98c2b..5030bc3d9eb429 100644
--- a/static/app/utils/events.tsx
+++ b/static/app/utils/events.tsx
@@ -217,6 +217,10 @@ function hasTrace(event: Event) {
return !!event.contexts?.trace;
}
+function hasProfile(event: Event) {
+ return defined(event.contexts?.profile);
+}
+
/**
* Function to determine if an event has source maps
* by ensuring that every inApp frame has a valid sourcemap
@@ -437,6 +441,7 @@ export function getAnalyticsDataForEvent(event?: Event | null): BaseEventAnalyti
has_release: !!event?.release,
has_exception_group: event ? eventHasExceptionGroup(event) : false,
has_graphql_request: event ? eventHasGraphQlRequest(event) : false,
+ has_profile: event ? hasProfile(event) : false,
has_source_context: event ? eventHasSourceContext(event) : false,
has_source_maps: event ? eventHasSourceMaps(event) : false,
has_trace: event ? hasTrace(event) : false,
|
fc8225b8ae9b3798ed00781ad18c5285dc406eb8
|
2024-11-27 22:57:49
|
Jodi Jang
|
chore(similarity): Handle no filename and module (#81272)
| false
|
Handle no filename and module (#81272)
|
chore
|
diff --git a/src/sentry/seer/similarity/utils.py b/src/sentry/seer/similarity/utils.py
index d1aa9849a7500a..29ce438ac8865e 100644
--- a/src/sentry/seer/similarity/utils.py
+++ b/src/sentry/seer/similarity/utils.py
@@ -161,6 +161,10 @@ class TooManyOnlySystemFramesException(Exception):
pass
+class NoFilenameOrModuleException(Exception):
+ pass
+
+
def _get_value_if_exists(exception_value: dict[str, Any]) -> str:
return exception_value["values"][0] if exception_value.get("values") else ""
@@ -188,6 +192,7 @@ def get_stacktrace_string(data: dict[str, Any]) -> str:
frame_count = 0
html_frame_count = 0 # for a temporary metric
is_frames_truncated = False
+ has_no_filename_or_module = False
stacktrace_str = ""
found_non_snipped_context_line = False
@@ -197,6 +202,7 @@ def _process_frames(frames: list[dict[str, Any]]) -> list[str]:
nonlocal frame_count
nonlocal html_frame_count
nonlocal is_frames_truncated
+ nonlocal has_no_filename_or_module
nonlocal found_non_snipped_context_line
frame_strings = []
@@ -211,7 +217,7 @@ def _process_frames(frames: list[dict[str, Any]]) -> list[str]:
frame_count += len(contributing_frames)
for frame in contributing_frames:
- frame_dict = {"filename": "", "function": "", "context-line": ""}
+ frame_dict = {"filename": "", "function": "", "context-line": "", "module": ""}
for frame_values in frame.get("values", []):
if frame_values.get("id") in frame_dict:
frame_dict[frame_values["id"]] = _get_value_if_exists(frame_values)
@@ -219,6 +225,11 @@ def _process_frames(frames: list[dict[str, Any]]) -> list[str]:
if not _is_snipped_context_line(frame_dict["context-line"]):
found_non_snipped_context_line = True
+ if frame_dict["filename"] == "" and frame_dict["module"] == "":
+ has_no_filename_or_module = True
+ elif frame_dict["filename"] == "":
+ frame_dict["filename"] = frame_dict["module"]
+
# Not an exhaustive list of tests we could run to detect HTML, but this is only
# meant to be a temporary, quick-and-dirty metric
# TODO: Don't let this, and the metric below, hang around forever. It's only to
@@ -271,6 +282,8 @@ def _process_frames(frames: list[dict[str, Any]]) -> list[str]:
frame_strings = _process_frames(exception_value["values"])
if is_frames_truncated and not app_hash:
raise TooManyOnlySystemFramesException
+ if has_no_filename_or_module:
+ raise NoFilenameOrModuleException
# Only exceptions have the type and value properties, so we don't need to handle the threads
# case here
header = f"{exc_type}: {exc_value}\n" if exception["id"] == "exception" else ""
@@ -328,6 +341,17 @@ def get_stacktrace_string_with_metrics(
},
)
stacktrace_string = None
+ except NoFilenameOrModuleException:
+ if referrer == ReferrerOptions.INGEST:
+ metrics.incr(
+ "grouping.similarity.did_call_seer",
+ sample_rate=options.get("seer.similarity.metrics_sample_rate"),
+ tags={
+ "call_made": False,
+ "blocker": "no-module-or-filename",
+ },
+ )
+ stacktrace_string = None
return stacktrace_string
diff --git a/tests/sentry/seer/similarity/test_utils.py b/tests/sentry/seer/similarity/test_utils.py
index 353d81db1d25a5..8675c4a2e2b6a2 100644
--- a/tests/sentry/seer/similarity/test_utils.py
+++ b/tests/sentry/seer/similarity/test_utils.py
@@ -1,20 +1,25 @@
import copy
from collections.abc import Callable
from typing import Any, Literal, cast
+from unittest.mock import patch
from uuid import uuid1
import pytest
+from sentry import options
from sentry.eventstore.models import Event
from sentry.seer.similarity.utils import (
BASE64_ENCODED_PREFIXES,
MAX_FRAME_COUNT,
SEER_ELIGIBLE_PLATFORMS,
+ NoFilenameOrModuleException,
+ ReferrerOptions,
TooManyOnlySystemFramesException,
_is_snipped_context_line,
event_content_is_seer_eligible,
filter_null_from_string,
get_stacktrace_string,
+ get_stacktrace_string_with_metrics,
)
from sentry.testutils.cases import TestCase
@@ -331,14 +336,14 @@ class GetStacktraceStringTest(TestCase):
"name": None,
"contributes": True,
"hint": None,
- "values": [],
+ "values": ["module"],
},
{
"id": "filename",
"name": None,
"contributes": True,
"hint": None,
- "values": [],
+ "values": ["filename"],
},
{
"id": "function",
@@ -691,7 +696,7 @@ def test_chained_too_many_exceptions(self):
def test_thread(self):
stacktrace_str = get_stacktrace_string(self.MOBILE_THREAD_DATA)
- assert stacktrace_str == 'File "", function TestHandler'
+ assert stacktrace_str == 'File "filename", function TestHandler'
def test_system(self):
data_system = copy.deepcopy(self.BASE_APP_DATA)
@@ -814,6 +819,42 @@ def test_only_stacktrace_frames(self):
stacktrace_str = get_stacktrace_string(self.ONLY_STACKTRACE)
assert stacktrace_str == 'File "index.php", function \n $server->emit($server->run());'
+ def test_replace_file_with_module(self):
+ exception = copy.deepcopy(self.BASE_APP_DATA)
+ # delete filename from the exception
+ del exception["app"]["component"]["values"][0]["values"][0]["values"][0]["values"][1]
+ stacktrace_string = get_stacktrace_string_with_metrics(
+ exception, "python", ReferrerOptions.INGEST
+ )
+ assert (
+ stacktrace_string
+ == 'ZeroDivisionError: division by zero\n File "__main__", function divide_by_zero\n divide = 1/0'
+ )
+
+ @patch("sentry.seer.similarity.utils.metrics")
+ def test_no_filename_or_module(self, mock_metrics):
+ exception = copy.deepcopy(self.BASE_APP_DATA)
+ # delete module from the exception
+ del exception["app"]["component"]["values"][0]["values"][0]["values"][0]["values"][0]
+ # delete filename from the exception
+ del exception["app"]["component"]["values"][0]["values"][0]["values"][0]["values"][0]
+ with pytest.raises(NoFilenameOrModuleException):
+ get_stacktrace_string(exception)
+
+ stacktrace_string = get_stacktrace_string_with_metrics(
+ exception, "python", ReferrerOptions.INGEST
+ )
+ sample_rate = options.get("seer.similarity.metrics_sample_rate")
+ assert stacktrace_string is None
+ mock_metrics.incr.assert_called_with(
+ "grouping.similarity.did_call_seer",
+ sample_rate=sample_rate,
+ tags={
+ "call_made": False,
+ "blocker": "no-module-or-filename",
+ },
+ )
+
class EventContentIsSeerEligibleTest(TestCase):
def get_eligible_event_data(self) -> dict[str, Any]:
|
d1c9ddaf59784d23e8e00726ef9d906c64d2195d
|
2023-05-04 23:50:26
|
Ash Anand
|
ref(starfish): Move extra endpoint details to new Endpoint Overview page (#48401)
| false
|
Move extra endpoint details to new Endpoint Overview page (#48401)
|
ref
|
diff --git a/static/app/routes.tsx b/static/app/routes.tsx
index 4a2d0f6d73d7f6..30fcb12cb6ad7f 100644
--- a/static/app/routes.tsx
+++ b/static/app/routes.tsx
@@ -1713,6 +1713,12 @@ function buildRoutes() {
() => import('sentry/views/starfish/views/webServiceView/endpointFailureEvents')
)}
/>
+ <Route
+ path="endpoint-overview/"
+ component={make(
+ () => import('sentry/views/starfish/views/webServiceView/endpointOverview')
+ )}
+ />
<Route
path="database/"
component={make(() => import('sentry/views/starfish/modules/databaseModule'))}
diff --git a/static/app/views/starfish/views/webServiceView/endpointDetails/index.tsx b/static/app/views/starfish/views/webServiceView/endpointDetails/index.tsx
index 58a78d2a616aed..07cb77206e99b7 100644
--- a/static/app/views/starfish/views/webServiceView/endpointDetails/index.tsx
+++ b/static/app/views/starfish/views/webServiceView/endpointDetails/index.tsx
@@ -1,13 +1,12 @@
import {Fragment} from 'react';
-import {browserHistory} from 'react-router';
import {useTheme} from '@emotion/react';
import styled from '@emotion/styled';
import {Location} from 'history';
import isNil from 'lodash/isNil';
import * as qs from 'query-string';
+import {Button} from 'sentry/components/button';
import _EventsRequest from 'sentry/components/charts/eventsRequest';
-import {COL_WIDTH_UNDEFINED} from 'sentry/components/gridEditable';
import {t} from 'sentry/locale';
import {space} from 'sentry/styles/space';
import {Organization} from 'sentry/types';
@@ -15,14 +14,10 @@ import EventView from 'sentry/utils/discover/eventView';
import {formatAbbreviatedNumber, getDuration} from 'sentry/utils/formatters';
import {useQuery} from 'sentry/utils/queryClient';
import {MutableSearch} from 'sentry/utils/tokenizeSearch';
-import usePageFilters from 'sentry/utils/usePageFilters';
import withApi from 'sentry/utils/withApi';
import FacetBreakdownBar from 'sentry/views/starfish/components/breakdownBar';
import Chart from 'sentry/views/starfish/components/chart';
import Detail from 'sentry/views/starfish/components/detailPanel';
-import EndpointTable from 'sentry/views/starfish/modules/APIModule/endpointTable';
-import DatabaseTableView from 'sentry/views/starfish/modules/databaseModule/databaseTableView';
-import {useQueryMainTable} from 'sentry/views/starfish/modules/databaseModule/queries';
import {HOST} from 'sentry/views/starfish/utils/constants';
import {getModuleBreakdown} from 'sentry/views/starfish/views/webServiceView/queries';
@@ -52,63 +47,6 @@ type EndpointDetailProps = Partial<EndpointDetailBodyProps> & {
onClose: () => void;
};
-const HTTP_SPAN_COLUMN_ORDER = [
- {
- key: 'description',
- name: 'URL',
- width: 400,
- },
- {
- key: 'throughput',
- name: 'Throughput',
- width: 125,
- },
- {
- key: 'p50(exclusive_time)',
- name: 'p50',
- width: COL_WIDTH_UNDEFINED,
- },
- {
- key: 'transaction_count',
- name: 'Transactions',
- width: COL_WIDTH_UNDEFINED,
- },
-
- {
- key: 'total_exclusive_time',
- name: 'Total Time',
- width: COL_WIDTH_UNDEFINED,
- },
-];
-
-const DATABASE_SPAN_COLUMN_ORDER = [
- {
- key: 'description',
- name: 'Query',
- width: 400,
- },
- {
- key: 'domain',
- name: 'Table',
- width: 100,
- },
- {
- key: 'epm',
- name: 'Tpm',
- width: COL_WIDTH_UNDEFINED,
- },
- {
- key: 'p75',
- name: 'p75',
- width: COL_WIDTH_UNDEFINED,
- },
- {
- key: 'total_time',
- name: 'Total Time',
- width: COL_WIDTH_UNDEFINED,
- },
-];
-
export default function EndpointDetail({
row,
onClose,
@@ -133,21 +71,15 @@ export default function EndpointDetail({
);
}
-function EndpointDetailBody({
- row,
- eventView,
- organization,
- location,
-}: EndpointDetailBodyProps) {
+function EndpointDetailBody({row, eventView, organization}: EndpointDetailBodyProps) {
const theme = useTheme();
- const pageFilter = usePageFilters();
- const {aggregateDetails} = row;
+ const {aggregateDetails, transaction, httpOp} = row;
const {data: moduleBreakdown} = useQuery({
queryKey: [`moduleBreakdown${row.transaction}`],
queryFn: () =>
- fetch(`${HOST}/?query=${getModuleBreakdown({transaction: row.transaction})}`).then(
- res => res.json()
+ fetch(`${HOST}/?query=${getModuleBreakdown({transaction})}`).then(res =>
+ res.json()
),
retry: false,
initialData: [],
@@ -156,19 +88,28 @@ function EndpointDetailBody({
const query = new MutableSearch([
'has:http.method',
'transaction.op:http.server',
- `transaction:${row.transaction}`,
- `http.method:${row.httpOp}`,
+ `transaction:${transaction}`,
+ `http.method:${httpOp}`,
]);
- const {
- isLoading: isTableDataLoading,
- data: tableData,
- isRefetching: isTableRefetching,
- } = useQueryMainTable({transaction: row.transaction});
return (
<div>
<h2>{t('Endpoint Detail')}</h2>
<p>{t('Details of endpoint. More breakdowns, etc. Maybe some trends?')}</p>
+ <OverviewButton
+ to={`/organizations/${
+ organization.slug
+ }/starfish/endpoint-overview/?${qs.stringify({
+ endpoint: transaction,
+ method: httpOp,
+ statsPeriod: eventView.statsPeriod,
+ project: eventView.project,
+ start: eventView.start,
+ end: eventView.end,
+ })}`}
+ >
+ {t('Go to Endpoint Overview')}
+ </OverviewButton>
<SubHeader>{t('Endpoint URL')}</SubHeader>
<pre>{row?.endpoint}</pre>
<EventsRequest
@@ -254,38 +195,6 @@ function EndpointDetailBody({
title={t('Where is time spent in this endpoint?')}
transaction={row.transaction}
/>
- <SubHeader>{t('HTTP Spans')}</SubHeader>
- <EndpointTable
- location={location}
- onSelect={r => {
- browserHistory.push(
- `/starfish/span/${encodeURIComponent(r.group_id)}/?${qs.stringify({
- transaction: row.transaction,
- })}`
- );
- }}
- columns={HTTP_SPAN_COLUMN_ORDER}
- filterOptions={{
- action: '',
- domain: '',
- transaction: row.transaction,
- datetime: pageFilter.selection.datetime,
- }}
- />
- <SubHeader>{t('Database Spans')}</SubHeader>
- <DatabaseTableView
- location={location}
- onSelect={r => {
- browserHistory.push(
- `/starfish/span/${encodeURIComponent(r.group_id)}/?${qs.stringify({
- transaction: row.transaction,
- })}`
- );
- }}
- isDataLoading={isTableDataLoading || isTableRefetching}
- data={tableData}
- columns={DATABASE_SPAN_COLUMN_ORDER}
- />
</div>
);
}
@@ -313,3 +222,7 @@ const FlexRowItem = styled('div')`
padding-right: ${space(4)};
flex: 1;
`;
+
+const OverviewButton = styled(Button)`
+ margin-bottom: ${space(2)};
+`;
diff --git a/static/app/views/starfish/views/webServiceView/endpointOverview/index.tsx b/static/app/views/starfish/views/webServiceView/endpointOverview/index.tsx
new file mode 100644
index 00000000000000..f0e4264a42d8dc
--- /dev/null
+++ b/static/app/views/starfish/views/webServiceView/endpointOverview/index.tsx
@@ -0,0 +1,297 @@
+import {Fragment} from 'react';
+import {browserHistory} from 'react-router';
+import {useTheme} from '@emotion/react';
+import styled from '@emotion/styled';
+import * as qs from 'query-string';
+
+import _EventsRequest from 'sentry/components/charts/eventsRequest';
+import DatePageFilter from 'sentry/components/datePageFilter';
+import {COL_WIDTH_UNDEFINED} from 'sentry/components/gridEditable';
+import * as Layout from 'sentry/components/layouts/thirds';
+import PageFilterBar from 'sentry/components/organizations/pageFilterBar';
+import {t} from 'sentry/locale';
+import {space} from 'sentry/styles/space';
+import {NewQuery} from 'sentry/types';
+import EventView from 'sentry/utils/discover/eventView';
+import {useQuery} from 'sentry/utils/queryClient';
+import {MutableSearch} from 'sentry/utils/tokenizeSearch';
+import {useLocation} from 'sentry/utils/useLocation';
+import useOrganization from 'sentry/utils/useOrganization';
+import usePageFilters from 'sentry/utils/usePageFilters';
+import withApi from 'sentry/utils/withApi';
+import FacetBreakdownBar from 'sentry/views/starfish/components/breakdownBar';
+import Chart from 'sentry/views/starfish/components/chart';
+import EndpointTable from 'sentry/views/starfish/modules/APIModule/endpointTable';
+import DatabaseTableView from 'sentry/views/starfish/modules/databaseModule/databaseTableView';
+import {useQueryMainTable} from 'sentry/views/starfish/modules/databaseModule/queries';
+import {HOST} from 'sentry/views/starfish/utils/constants';
+import {getModuleBreakdown} from 'sentry/views/starfish/views/webServiceView/queries';
+
+const EventsRequest = withApi(_EventsRequest);
+
+const HTTP_SPAN_COLUMN_ORDER = [
+ {
+ key: 'description',
+ name: 'URL',
+ width: 400,
+ },
+ {
+ key: 'throughput',
+ name: 'Throughput',
+ width: 350,
+ },
+ {
+ key: 'p50(exclusive_time)',
+ name: 'p50',
+ width: COL_WIDTH_UNDEFINED,
+ },
+ {
+ key: 'transaction_count',
+ name: 'Transactions',
+ width: COL_WIDTH_UNDEFINED,
+ },
+
+ {
+ key: 'total_exclusive_time',
+ name: 'Total Time',
+ width: COL_WIDTH_UNDEFINED,
+ },
+];
+
+const DATABASE_SPAN_COLUMN_ORDER = [
+ {
+ key: 'description',
+ name: 'Query',
+ width: 400,
+ },
+ {
+ key: 'domain',
+ name: 'Table',
+ width: 100,
+ },
+ {
+ key: 'epm',
+ name: 'Tpm',
+ width: COL_WIDTH_UNDEFINED,
+ },
+ {
+ key: 'p75',
+ name: 'p75',
+ width: COL_WIDTH_UNDEFINED,
+ },
+ {
+ key: 'total_time',
+ name: 'Total Time',
+ width: COL_WIDTH_UNDEFINED,
+ },
+];
+
+export default function EndpointOverview() {
+ const location = useLocation();
+ const organization = useOrganization();
+ const theme = useTheme();
+
+ const {endpoint: transaction, method, statsPeriod} = location.query;
+ const pageFilter = usePageFilters();
+
+ const {
+ isLoading: isTableDataLoading,
+ data: tableData,
+ isRefetching: isTableRefetching,
+ } = useQueryMainTable({});
+
+ const {data: moduleBreakdown} = useQuery({
+ queryKey: [`moduleBreakdown${transaction}`],
+ queryFn: () =>
+ fetch(`${HOST}/?query=${getModuleBreakdown({transaction})}`).then(res =>
+ res.json()
+ ),
+ retry: false,
+ initialData: [],
+ });
+
+ if (!transaction) {
+ return null;
+ }
+
+ const query = new MutableSearch([
+ 'has:http.method',
+ 'transaction.op:http.server',
+ `transaction:${transaction}`,
+ `http.method:${method}`,
+ ]);
+
+ const savedQuery: NewQuery = {
+ id: undefined,
+ name: t('Endpoint Overview'),
+ query: query.formatString(),
+ projects: [],
+ fields: [],
+ version: 2,
+ };
+
+ const eventView = EventView.fromNewQueryWithLocation(savedQuery, location);
+
+ return (
+ <Layout.Page>
+ <Layout.Header>
+ <Layout.HeaderContent>
+ <Layout.Title>{t('Endpoint Overview')}</Layout.Title>
+ </Layout.HeaderContent>
+ </Layout.Header>
+
+ <Layout.Body>
+ <SearchContainerWithFilterAndMetrics>
+ <PageFilterBar condensed>
+ <DatePageFilter alignDropdown="left" />
+ </PageFilterBar>
+ </SearchContainerWithFilterAndMetrics>
+
+ <Layout.Main fullWidth>
+ <SubHeader>{t('Endpoint URL')}</SubHeader>
+ <pre>{`${method} ${transaction}`}</pre>
+ <EventsRequest
+ query={query.formatString()}
+ includePrevious={false}
+ partial
+ limit={5}
+ interval="1h"
+ includeTransformedData
+ environment={eventView.environment}
+ project={eventView.project}
+ period={pageFilter.selection.datetime.period}
+ referrer="starfish-endpoint-overview"
+ start={pageFilter.selection.datetime.start}
+ end={pageFilter.selection.datetime.end}
+ organization={organization}
+ yAxis={['tpm()', 'p50(transaction.duration)']}
+ queryExtras={{dataset: 'metrics'}}
+ >
+ {({results, loading}) => {
+ return (
+ <Fragment>
+ <FlexRowContainer>
+ <FlexRowItem>
+ <SubHeader>{t('Throughput')}</SubHeader>
+ <Chart
+ statsPeriod={(statsPeriod as string) ?? '24h'}
+ height={110}
+ data={results?.[0] ? [results?.[0]] : []}
+ start=""
+ end=""
+ loading={loading}
+ utc={false}
+ stacked
+ isLineChart
+ disableXAxis
+ hideYAxisSplitLine
+ chartColors={[theme.charts.getColorPalette(0)[0]]}
+ grid={{
+ left: '0',
+ right: '0',
+ top: '8px',
+ bottom: '16px',
+ }}
+ />
+ </FlexRowItem>
+ <FlexRowItem>
+ <SubHeader>{t('p50(duration)')}</SubHeader>
+ <Chart
+ statsPeriod={(statsPeriod as string) ?? '24h'}
+ height={110}
+ data={results?.[1] ? [results?.[1]] : []}
+ start=""
+ end=""
+ loading={loading}
+ utc={false}
+ stacked
+ isLineChart
+ disableXAxis
+ hideYAxisSplitLine
+ chartColors={[theme.charts.getColorPalette(0)[1]]}
+ grid={{
+ left: '0',
+ right: '0',
+ top: '8px',
+ bottom: '16px',
+ }}
+ />
+ </FlexRowItem>
+ </FlexRowContainer>
+ </Fragment>
+ );
+ }}
+ </EventsRequest>
+ <FacetBreakdownBar
+ segments={moduleBreakdown}
+ title={t('Where is time spent in this endpoint?')}
+ transaction={transaction as string}
+ />
+ <SubHeader>{t('HTTP Spans')}</SubHeader>
+ <EndpointTable
+ location={location}
+ onSelect={r => {
+ browserHistory.push(
+ `/starfish/span/${encodeURIComponent(r.group_id)}/?${qs.stringify({
+ transaction,
+ })}`
+ );
+ }}
+ columns={HTTP_SPAN_COLUMN_ORDER}
+ filterOptions={{
+ action: '',
+ domain: '',
+ transaction: (transaction as string) ?? '',
+ datetime: pageFilter.selection.datetime,
+ }}
+ />
+ <SubHeader>{t('Database Spans')}</SubHeader>
+ <DatabaseTableView
+ location={location}
+ onSelect={r => {
+ browserHistory.push(
+ `/starfish/span/${encodeURIComponent(r.group_id)}/?${qs.stringify({
+ transaction,
+ })}`
+ );
+ }}
+ isDataLoading={isTableDataLoading || isTableRefetching}
+ data={tableData}
+ columns={DATABASE_SPAN_COLUMN_ORDER}
+ />
+ </Layout.Main>
+ </Layout.Body>
+ </Layout.Page>
+ );
+}
+
+const SubHeader = styled('h3')`
+ color: ${p => p.theme.gray300};
+ font-size: ${p => p.theme.fontSizeLarge};
+ margin: 0;
+ margin-bottom: ${space(1)};
+`;
+
+const SearchContainerWithFilterAndMetrics = styled('div')`
+ display: grid;
+ grid-template-rows: auto auto auto;
+ gap: ${space(2)};
+ margin-bottom: ${space(2)};
+
+ @media (min-width: ${p => p.theme.breakpoints.small}) {
+ grid-template-rows: auto;
+ grid-template-columns: auto 1fr auto;
+ }
+`;
+
+const FlexRowContainer = styled('div')`
+ display: flex;
+ & > div:last-child {
+ padding-right: ${space(1)};
+ }
+`;
+
+const FlexRowItem = styled('div')`
+ padding-right: ${space(4)};
+ flex: 1;
+`;
|
05f12fe31481af132fb258af051b75cf91d3fecf
|
2024-09-13 02:29:46
|
Evan Purkhiser
|
ref(py): Make withs in test_results_consumers easier to read (#77433)
| false
|
Make withs in test_results_consumers easier to read (#77433)
|
ref
|
diff --git a/tests/sentry/uptime/consumers/test_results_consumers.py b/tests/sentry/uptime/consumers/test_results_consumers.py
index a916acd6ca72d1..d716f88bb59ff7 100644
--- a/tests/sentry/uptime/consumers/test_results_consumers.py
+++ b/tests/sentry/uptime/consumers/test_results_consumers.py
@@ -71,11 +71,13 @@ def test(self):
self.subscription.subscription_id,
scheduled_check_time=datetime.now() - timedelta(minutes=5),
)
- with mock.patch(
- "sentry.uptime.consumers.results_consumer.metrics"
- ) as metrics, self.feature("organizations:uptime-create-issues"), mock.patch(
- "sentry.uptime.consumers.results_consumer.ACTIVE_FAILURE_THRESHOLD",
- new=2,
+ with (
+ mock.patch("sentry.uptime.consumers.results_consumer.metrics") as metrics,
+ self.feature("organizations:uptime-create-issues"),
+ mock.patch(
+ "sentry.uptime.consumers.results_consumer.ACTIVE_FAILURE_THRESHOLD",
+ new=2,
+ ),
):
self.send_result(result)
metrics.incr.assert_has_calls(
@@ -124,9 +126,10 @@ def test(self):
assert self.project_subscription.uptime_status == UptimeStatus.FAILED
def test_reset_fail_count(self):
- with mock.patch(
- "sentry.uptime.consumers.results_consumer.metrics"
- ) as metrics, self.feature("organizations:uptime-create-issues"):
+ with (
+ mock.patch("sentry.uptime.consumers.results_consumer.metrics") as metrics,
+ self.feature("organizations:uptime-create-issues"),
+ ):
self.send_result(
self.create_uptime_result(
self.subscription.subscription_id,
@@ -206,9 +209,12 @@ def test_reset_fail_count(self):
def test_no_create_issues_feature(self):
result = self.create_uptime_result(self.subscription.subscription_id)
- with mock.patch("sentry.uptime.consumers.results_consumer.metrics") as metrics, mock.patch(
- "sentry.uptime.consumers.results_consumer.ACTIVE_FAILURE_THRESHOLD",
- new=1,
+ with (
+ mock.patch("sentry.uptime.consumers.results_consumer.metrics") as metrics,
+ mock.patch(
+ "sentry.uptime.consumers.results_consumer.ACTIVE_FAILURE_THRESHOLD",
+ new=1,
+ ),
):
self.send_result(result)
metrics.incr.assert_has_calls(
@@ -232,11 +238,13 @@ def test_no_create_issues_feature(self):
assert self.project_subscription.uptime_status == UptimeStatus.FAILED
def test_resolve(self):
- with mock.patch(
- "sentry.uptime.consumers.results_consumer.metrics"
- ) as metrics, self.feature("organizations:uptime-create-issues"), mock.patch(
- "sentry.uptime.consumers.results_consumer.ACTIVE_FAILURE_THRESHOLD",
- new=2,
+ with (
+ mock.patch("sentry.uptime.consumers.results_consumer.metrics") as metrics,
+ self.feature("organizations:uptime-create-issues"),
+ mock.patch(
+ "sentry.uptime.consumers.results_consumer.ACTIVE_FAILURE_THRESHOLD",
+ new=2,
+ ),
):
self.send_result(
self.create_uptime_result(
@@ -315,9 +323,10 @@ def test_resolve(self):
def test_no_subscription(self):
subscription_id = uuid.uuid4().hex
result = self.create_uptime_result(subscription_id)
- with mock.patch(
- "sentry.uptime.consumers.results_consumer.metrics"
- ) as metrics, self.feature("organizations:uptime-create-issues"):
+ with (
+ mock.patch("sentry.uptime.consumers.results_consumer.metrics") as metrics,
+ self.feature("organizations:uptime-create-issues"),
+ ):
self.send_result(result)
metrics.incr.assert_has_calls(
[call("uptime.result_processor.subscription_not_found", sample_rate=1.0)]
@@ -330,9 +339,10 @@ def test_skip_already_processed(self):
build_last_update_key(self.project_subscription),
int(result["scheduled_check_time_ms"]),
)
- with mock.patch(
- "sentry.uptime.consumers.results_consumer.metrics"
- ) as metrics, self.feature("organizations:uptime-create-issues"):
+ with (
+ mock.patch("sentry.uptime.consumers.results_consumer.metrics") as metrics,
+ self.feature("organizations:uptime-create-issues"),
+ ):
self.send_result(result)
metrics.incr.assert_has_calls(
[
@@ -396,9 +406,10 @@ def test_onboarding_failure(self):
redis = _get_cluster()
key = build_onboarding_failure_key(self.project_subscription)
assert redis.get(key) is None
- with mock.patch(
- "sentry.uptime.consumers.results_consumer.metrics"
- ) as metrics, self.feature("organizations:uptime-create-issues"):
+ with (
+ mock.patch("sentry.uptime.consumers.results_consumer.metrics") as metrics,
+ self.feature("organizations:uptime-create-issues"),
+ ):
self.send_result(result)
metrics.incr.assert_has_calls(
[
@@ -475,9 +486,10 @@ def test_onboarding_success_ongoing(self):
redis = _get_cluster()
key = build_onboarding_failure_key(self.project_subscription)
assert redis.get(key) is None
- with mock.patch(
- "sentry.uptime.consumers.results_consumer.metrics"
- ) as metrics, self.feature("organizations:uptime-create-issues"):
+ with (
+ mock.patch("sentry.uptime.consumers.results_consumer.metrics") as metrics,
+ self.feature("organizations:uptime-create-issues"),
+ ):
self.send_result(result)
metrics.incr.assert_has_calls(
[
@@ -513,9 +525,11 @@ def test_onboarding_success_graduate(self):
redis = _get_cluster()
key = build_onboarding_failure_key(self.project_subscription)
assert redis.get(key) is None
- with mock.patch(
- "sentry.uptime.consumers.results_consumer.metrics"
- ) as metrics, self.tasks(), self.feature("organizations:uptime-create-issues"):
+ with (
+ mock.patch("sentry.uptime.consumers.results_consumer.metrics") as metrics,
+ self.tasks(),
+ self.feature("organizations:uptime-create-issues"),
+ ):
self.send_result(result)
metrics.incr.assert_has_calls(
[
|
69cdde9185c4e824fd9edaf8b77d93b18f2dc7a7
|
2019-05-07 14:07:57
|
Daniel Griesser
|
feat: Tracing setup (#12952)
| false
|
Tracing setup (#12952)
|
feat
|
diff --git a/package.json b/package.json
index 7532b6dc21bba7..4100c7c2a635e6 100644
--- a/package.json
+++ b/package.json
@@ -18,8 +18,8 @@
"@babel/preset-env": "^7.0.0",
"@babel/preset-react": "^7.0.0",
"@babel/runtime": "^7.0.0",
- "@sentry/browser": "5.0.8",
- "@sentry/integrations": "^5.0.8",
+ "@sentry/browser": "5.2.0-beta.0",
+ "@sentry/integrations": "5.2.0-beta.0",
"algoliasearch": "^3.32.0",
"babel-core": "^7.0.0-bridge.0",
"babel-loader": "^8.0.0",
diff --git a/requirements-base.txt b/requirements-base.txt
index a258c101e12f17..69c048d9403185 100644
--- a/requirements-base.txt
+++ b/requirements-base.txt
@@ -57,7 +57,7 @@ requests-oauthlib==0.3.3
requests[security]>=2.20.0,<2.21.0
selenium==3.141.0
semaphore>=0.4.32,<0.5.0
-sentry-sdk>=0.7.0
+sentry-sdk>=0.7.14
setproctitle>=1.1.7,<1.2.0
simplejson>=3.2.0,<3.9.0
six>=1.10.0,<1.11.0
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index e950511a7112db..3da389eb682fa9 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -236,7 +236,6 @@ def env(key, default='', type=None):
# TODO(dcramer): kill this once we verify its safe
# 'sentry.middleware.social_auth.SentrySocialAuthExceptionMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
- 'sentry.middleware.tracing.SentryTracingMiddleware',
'sentry.debug.middleware.DebugMiddleware',
)
diff --git a/src/sentry/interfaces/contexts.py b/src/sentry/interfaces/contexts.py
index e3b26afbdd9ed8..b0fe2d8369f3f9 100644
--- a/src/sentry/interfaces/contexts.py
+++ b/src/sentry/interfaces/contexts.py
@@ -168,6 +168,16 @@ class MonitorContextType(ContextType):
}
+@contexttype
+class TraceContextType(ContextType):
+ type = 'trace'
+ indexed_fields = {
+ '': u'{trace_id}',
+ 'span': u'{span_id}',
+ 'ctx': u'{trace_id}-{span_id}',
+ }
+
+
class Contexts(Interface):
"""
This interface stores context specific information.
diff --git a/src/sentry/middleware/tracing.py b/src/sentry/middleware/tracing.py
deleted file mode 100644
index a9d7f599ec29ca..00000000000000
--- a/src/sentry/middleware/tracing.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from __future__ import absolute_import
-
-import six
-from uuid import uuid1
-
-import sentry_sdk
-
-from sentry import logging
-
-
-class SentryTracingMiddleware(object):
- def process_request(self, request):
- span_id = six.text_type(uuid1())
- transaction_id = request.META.get('HTTP_X_TRANSACTION_ID') or six.text_type(uuid1())
- request_id = request.META.get('HTTP_X_REQUEST_ID')
- with sentry_sdk.configure_scope() as scope:
- scope.set_tag('span_id', span_id)
- scope.set_tag('transaction_id', transaction_id)
- if request_id is not None:
- scope.set_tag('request_id', request_id)
- logging.bind('sentry', request_id=request_id)
- else:
- # Need to be explicitly unbound when not set
- # otherwise it'll carry onto future requests
- logging.unbind('sentry', 'request_id')
diff --git a/src/sentry/static/sentry/app/api.jsx b/src/sentry/static/sentry/app/api.jsx
index 54bc7882db9060..42651b94d145ff 100644
--- a/src/sentry/static/sentry/app/api.jsx
+++ b/src/sentry/static/sentry/app/api.jsx
@@ -12,7 +12,6 @@ import {openSudo, redirectToProject} from 'app/actionCreators/modal';
import {uniqueId} from 'app/utils/guid';
import GroupActions from 'app/actions/groupActions';
import createRequestError from 'app/utils/requestError/createRequestError';
-import * as tracing from 'app/utils/tracing';
export class Request {
constructor(xhr) {
@@ -208,8 +207,6 @@ export class Client {
contentType: 'application/json',
headers: {
Accept: 'application/json; charset=utf-8',
- 'X-Transaction-ID': tracing.getTransactionId(),
- 'X-Span-ID': tracing.getSpanId(),
},
success: (...args) => {
const [resp] = args || [];
diff --git a/src/sentry/static/sentry/app/index.js b/src/sentry/static/sentry/app/index.js
index 75d0c84f525f42..92a53ee0babdcb 100644
--- a/src/sentry/static/sentry/app/index.js
+++ b/src/sentry/static/sentry/app/index.js
@@ -20,13 +20,12 @@ import * as ReactEmotion from 'react-emotion';
import Reflux from 'reflux';
import * as Router from 'react-router';
import * as Sentry from '@sentry/browser';
-import {ExtraErrorData} from '@sentry/integrations';
+import {ExtraErrorData, Tracing} from '@sentry/integrations';
import createReactClass from 'create-react-class';
import jQuery from 'jquery';
import moment from 'moment';
import {metric} from 'app/utils/analytics';
-import * as tracing from 'app/utils/tracing';
import ConfigStore from 'app/stores/configStore';
import Main from 'app/main';
import ajaxCsrfSetup from 'app/utils/ajaxCsrfSetup';
@@ -38,7 +37,13 @@ import plugins from 'app/plugins';
// window.__SENTRY__OPTIONS will be emmited by sdk-config.html before loading this script
Sentry.init({
...window.__SENTRY__OPTIONS,
- integrations: [new ExtraErrorData()],
+ integrations: [
+ new ExtraErrorData(),
+ new Tracing({
+ tracingOrigins: ['localhost', 'sentry.io', /^\//],
+ autoStartOnDomReady: false,
+ }),
+ ],
});
Sentry.configureScope(scope => {
@@ -48,14 +53,6 @@ Sentry.configureScope(scope => {
if (window.__SENTRY__VERSION) {
scope.setTag('sentry_version', window.__SENTRY__VERSION);
}
-
- // There's no setTransaction API *yet*, so we have to be explicit here
- scope.addEventProcessor(event => {
- return {
- ...event,
- transaction: tracing.getRoute(),
- };
- });
});
function __raven_deprecated() {
diff --git a/src/sentry/static/sentry/app/utils/tracing.jsx b/src/sentry/static/sentry/app/utils/tracing.jsx
deleted file mode 100644
index fc13991f745401..00000000000000
--- a/src/sentry/static/sentry/app/utils/tracing.jsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import {uniqueId} from './guid';
-
-let spanId = null;
-let transactionId = null;
-let route = null;
-
-export function startTransaction() {
- spanId = uniqueId();
- transactionId = uniqueId();
- if (window.Sentry) {
- window.Sentry.configureScope(function(scope) {
- scope.setTag('span_id', spanId);
- scope.setTag('transaction_id', transactionId);
- });
- }
- return {spanId, transactionId};
-}
-
-export function setRoute(currentRoute) {
- route = currentRoute;
- return route;
-}
-
-export function getRoute() {
- return route;
-}
-
-export function getTransactionId() {
- if (!transactionId) {
- startTransaction();
- }
- return transactionId;
-}
-
-export function getSpanId() {
- if (!spanId) {
- startTransaction();
- }
- return spanId;
-}
diff --git a/src/sentry/static/sentry/app/views/app.jsx b/src/sentry/static/sentry/app/views/app.jsx
index 76526ef498ca6e..7ad7aac308ecf0 100644
--- a/src/sentry/static/sentry/app/views/app.jsx
+++ b/src/sentry/static/sentry/app/views/app.jsx
@@ -7,6 +7,8 @@ import React from 'react';
import Reflux from 'reflux';
import createReactClass from 'create-react-class';
import keydown from 'react-keydown';
+import {getCurrentHub} from '@sentry/browser';
+import {Tracing} from '@sentry/integrations';
import {openCommandPalette} from 'app/actionCreators/modal';
import {t} from 'app/locale';
@@ -25,7 +27,6 @@ import NewsletterConsent from 'app/views/newsletterConsent';
import OrganizationsStore from 'app/stores/organizationsStore';
import theme from 'app/utils/theme';
import getRouteStringFromRoutes from 'app/utils/getRouteStringFromRoutes';
-import * as tracing from 'app/utils/tracing';
function getAlertTypeForProblem(problem) {
switch (problem.severity) {
@@ -157,12 +158,8 @@ const App = createReactClass({
},
updateTracing() {
- tracing.startTransaction();
-
const route = getRouteStringFromRoutes(this.props.routes);
- if (route) {
- tracing.setRoute(route);
- }
+ Tracing.startTrace(getCurrentHub(), route);
},
onConfigStoreChange(config) {
diff --git a/tests/js/setup.js b/tests/js/setup.js
index c62f528e7844d4..9831376519a076 100644
--- a/tests/js/setup.js
+++ b/tests/js/setup.js
@@ -110,6 +110,7 @@ jest.mock('@sentry/browser', () => {
captureException: jest.fn(),
showReportDialog: jest.fn(),
lastEventId: jest.fn(),
+ getCurrentHub: jest.spyOn(SentryBrowser, 'getCurrentHub'),
withScope: jest.spyOn(SentryBrowser, 'withScope'),
};
});
diff --git a/yarn.lock b/yarn.lock
index 1ad0c7a8738ca6..4bc78f90ca2f49 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1130,64 +1130,65 @@
resolved "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-1.1.3.tgz#2b5a3ab3f918cca48a8c754c08168e3f03eba61b"
integrity sha512-shAmDyaQC4H92APFoIaVDHCx5bStIocgvbwQyxPRrbUY20V1EYTbSDchWbuwlMG3V17cprZhA6+78JfB+3DTPw==
-"@sentry/[email protected]":
- version "5.0.8"
- resolved "https://registry.yarnpkg.com/@sentry/browser/-/browser-5.0.8.tgz#12350d1e1d0881eb4641f44ffa8ddcefb2b03217"
- integrity sha512-hMV3mF8R3YZ0IhkjdYMSNdPfC2XbImCL88Mqxkc53KPGMes/8psPd40aWChRcMw0qJIovgezAdn41oxMH8XimQ==
- dependencies:
- "@sentry/core" "5.0.8"
- "@sentry/types" "5.0.6"
- "@sentry/utils" "5.0.8"
+"@sentry/[email protected]":
+ version "5.2.0-beta.0"
+ resolved "https://registry.yarnpkg.com/@sentry/browser/-/browser-5.2.0-beta.0.tgz#8c2f54cdf946dd535d51e95c4272cd8df76cfc61"
+ integrity sha512-GkpXX32CsSrSQAZPYAEpWRb3U2uCAvHNpgfnWEBq0tshneYa4MG3SAGawit4F+CloIeLuFoqnjRGsEmDCZn++g==
+ dependencies:
+ "@sentry/core" "5.2.0-beta.0"
+ "@sentry/types" "5.2.0-beta.0"
+ "@sentry/utils" "5.2.0-beta.0"
tslib "^1.9.3"
-"@sentry/[email protected]":
- version "5.0.8"
- resolved "https://registry.yarnpkg.com/@sentry/core/-/core-5.0.8.tgz#8a05f1c024cda726b4cabeb2e56c5a6e3857e475"
- integrity sha512-LGTPMx4PqSOCUiUjHZ45kwealcqAnHgUZonnIv8pcqd1NmY5oOUAhI/rO60Yj9Ij6TVaSHppWpYHI7Wt9Ot6kQ==
+"@sentry/[email protected]":
+ version "5.2.0-beta.0"
+ resolved "https://registry.yarnpkg.com/@sentry/core/-/core-5.2.0-beta.0.tgz#c0c03b6ab1899090aceeadd1b71ab8e7694700dd"
+ integrity sha512-B8FU9MpAXQCFPv/7wLJc+hvBbhqTab1/0e+o0Estpnv2m45p0k1OZN3ruReuGNlv8md8y5Un7OSjbRq46YE48A==
dependencies:
- "@sentry/hub" "5.0.8"
- "@sentry/minimal" "5.0.8"
- "@sentry/types" "5.0.6"
- "@sentry/utils" "5.0.8"
+ "@sentry/hub" "5.2.0-beta.0"
+ "@sentry/minimal" "5.2.0-beta.0"
+ "@sentry/types" "5.2.0-beta.0"
+ "@sentry/utils" "5.2.0-beta.0"
tslib "^1.9.3"
-"@sentry/[email protected]":
- version "5.0.8"
- resolved "https://registry.yarnpkg.com/@sentry/hub/-/hub-5.0.8.tgz#9a229c4afee0b59a238b7c804d20369e7d3346b2"
- integrity sha512-a9+hnYO42Rpdk7lrxk3dhmZYfOGMDEq2WP2blNiKIU2efI6CQ3G9Ka/6WzVOXSgV3rY+4zx60vHUhNkQVgsbsg==
+"@sentry/[email protected]":
+ version "5.2.0-beta.0"
+ resolved "https://registry.yarnpkg.com/@sentry/hub/-/hub-5.2.0-beta.0.tgz#20b88a772a1538ce304e5ffa435a18dd513b4ef2"
+ integrity sha512-KHBP6tMxkmse3gvza0Uw0cs2QvtJErH8rhcbmUVP+J4PKYaSaCdFAyt4zZcO9QTZSXOUUxZNK4zyvu9U9hTsqw==
dependencies:
- "@sentry/types" "5.0.6"
- "@sentry/utils" "5.0.8"
+ "@sentry/types" "5.2.0-beta.0"
+ "@sentry/utils" "5.2.0-beta.0"
tslib "^1.9.3"
-"@sentry/integrations@^5.0.8":
- version "5.0.8"
- resolved "https://registry.yarnpkg.com/@sentry/integrations/-/integrations-5.0.8.tgz#9322520827ad4014b4501e44501a3e6db22d26aa"
- integrity sha512-qpk31GZtT9kIGUY1X5rV9dgTsefxjFjxJPdwWUlVpmgNYbcGGJJqnqnTCsBL2oKA3T/VHAbEP2rcE33HGiuEKA==
+"@sentry/[email protected]":
+ version "5.2.0-beta.0"
+ resolved "https://registry.yarnpkg.com/@sentry/integrations/-/integrations-5.2.0-beta.0.tgz#e3f4909b97ec7c16d80062d86c2cbe92ede3ced3"
+ integrity sha512-0WdWLeYuBL0Q+Y9oAC1Rz1AYtlPYiiRTKY1gda3pLp8jAO54U14c5Bj0VYipATg4t107BvWvn4/SKx0f1S/1fw==
dependencies:
- "@sentry/types" "5.0.6"
- "@sentry/utils" "5.0.8"
+ "@sentry/types" "5.2.0-beta.0"
+ "@sentry/utils" "5.2.0-beta.0"
+ tslib "^1.9.3"
-"@sentry/[email protected]":
- version "5.0.8"
- resolved "https://registry.yarnpkg.com/@sentry/minimal/-/minimal-5.0.8.tgz#21a6521dfbc02d098ae604813e90d945fec6c820"
- integrity sha512-MP5bFuqC0xMWT9LTkX0rkX1Xxlj3G4zKdhF8rxwM9YLZUUmS5vvNs/AiPGaEAlw8i9C+0TBTcvQt3va2qVVEHA==
+"@sentry/[email protected]":
+ version "5.2.0-beta.0"
+ resolved "https://registry.yarnpkg.com/@sentry/minimal/-/minimal-5.2.0-beta.0.tgz#2b3cde2adc9114e9488cb06749162060abdbe11b"
+ integrity sha512-vsdr4h4X2Pe7VnQ05nB7Nz3b7QkAOA+68bNPwWDWstd4QWjlSyuav8gQrert/rVOmU7C5leps4mT655d82PjYA==
dependencies:
- "@sentry/hub" "5.0.8"
- "@sentry/types" "5.0.6"
+ "@sentry/hub" "5.2.0-beta.0"
+ "@sentry/types" "5.2.0-beta.0"
tslib "^1.9.3"
-"@sentry/[email protected]":
- version "5.0.6"
- resolved "https://registry.yarnpkg.com/@sentry/types/-/types-5.0.6.tgz#df1b318977e5308741049cc4f35986cf8255115f"
- integrity sha512-EJYzjfnTfTQgqR3p6dSvIVZe0xe2Jz+tSmvuPABf7VoCmrFtEYkMCSf5IshMHeebmXUS5prrPSCAgVcIrJC+Bw==
+"@sentry/[email protected]":
+ version "5.2.0-beta.0"
+ resolved "https://registry.yarnpkg.com/@sentry/types/-/types-5.2.0-beta.0.tgz#c40d157a39850e715b5494094eac6317bcfb43e6"
+ integrity sha512-JB1nCQbzTGuZDH3jX7CMkd8OgRtAYl1wViTsc/ZMgpDqDjSJZvJzD+FEnW4H9AzPjcdNP7t9+VMwSJRNDDh7xg==
-"@sentry/[email protected]":
- version "5.0.8"
- resolved "https://registry.yarnpkg.com/@sentry/utils/-/utils-5.0.8.tgz#3dcc95b84fef1a862236c9950c257322817bf0da"
- integrity sha512-NZUVl3i2Rm5WKgPEb0DSPYTMQsCxdbZXOiOEq2/9Ee1bY29VTzmjM08KZTYI8+ZiUJwB2l3y/nvNGkqlEoXQCg==
+"@sentry/[email protected]":
+ version "5.2.0-beta.0"
+ resolved "https://registry.yarnpkg.com/@sentry/utils/-/utils-5.2.0-beta.0.tgz#1faaf2239e74af0f62509430df3124c0ecfa74a7"
+ integrity sha512-D87a+s4qG/9kBTikN4Oodh3sEXXV9AVHKQEEpOpNqVzBaLjDcJVhwO7lGIgGj03BqqHTd+inFMxed7wU3tbXsw==
dependencies:
- "@sentry/types" "5.0.6"
+ "@sentry/types" "5.2.0-beta.0"
tslib "^1.9.3"
"@storybook/addon-a11y@^4.1.3":
|
fd2313a851f02703c350ae5761f2530a19794f1e
|
2023-01-18 22:49:36
|
Jonas
|
feat(codecov): profiling team components (#43384)
| false
|
profiling team components (#43384)
|
feat
|
diff --git a/codecov.yml b/codecov.yml
index efc24cd4695a50..770d394ed5988f 100644
--- a/codecov.yml
+++ b/codecov.yml
@@ -27,6 +27,22 @@ coverage:
- static/app/routes.tsx
- tests/
+component_management:
+ individual_components:
+ # Profiling team components
+ - component_id: "profiling_views"
+ name: "Profiling Views"
+ paths:
+ - "static/app/views/profiling/**"
+ - component_id: "profiling_components"
+ name: "Profiling Components"
+ paths:
+ - "src/sentry/static/sentry/app/components/profiling/**"
+ - component_id: "profiling_utils"
+ name: "Profiling Utils"
+ paths:
+ - "src/sentry/static/sentry/app/utils/profiling/**"
+
flags:
frontend:
paths:
|
0172dc5171862e8dc7062c896da228bd5b1a8b91
|
2023-10-09 18:09:50
|
Riccardo Busetti
|
fix(ddm): Fix wrong condition for the metrics backend (#57768)
| false
|
Fix wrong condition for the metrics backend (#57768)
|
fix
|
diff --git a/src/sentry/metrics/composite_experimental.py b/src/sentry/metrics/composite_experimental.py
index 593b5a3389c14e..fe00009d6175b1 100644
--- a/src/sentry/metrics/composite_experimental.py
+++ b/src/sentry/metrics/composite_experimental.py
@@ -50,7 +50,7 @@ def incr(
sample_rate: float = 1,
) -> None:
self._primary_backend.incr(key, instance, tags, amount, sample_rate)
- if self._is_allowed(key):
+ if self._is_allowed(key) or options.get("delightful_metrics.allow_all_incr"):
self._minimetrics.incr(key, instance, tags, amount, self._minimetrics_sample_rate())
def timing(
@@ -62,7 +62,7 @@ def timing(
sample_rate: float = 1,
) -> None:
self._primary_backend.timing(key, value, instance, tags, sample_rate)
- if self._is_allowed(key):
+ if self._is_allowed(key) or options.get("delightful_metrics.allow_all_timing"):
self._minimetrics.timing(key, value, instance, tags, self._minimetrics_sample_rate())
def gauge(
@@ -74,5 +74,5 @@ def gauge(
sample_rate: float = 1,
) -> None:
self._primary_backend.gauge(key, value, instance, tags, sample_rate)
- if self._is_allowed(key):
+ if self._is_allowed(key) or options.get("delightful_metrics.allow_all_gauge"):
self._minimetrics.gauge(key, value, instance, tags, self._minimetrics_sample_rate())
diff --git a/src/sentry/metrics/minimetrics.py b/src/sentry/metrics/minimetrics.py
index 75ad0fbbaad4ee..d107d266bf4b53 100644
--- a/src/sentry/metrics/minimetrics.py
+++ b/src/sentry/metrics/minimetrics.py
@@ -113,7 +113,7 @@ def incr(
amount: Union[float, int] = 1,
sample_rate: float = 1,
) -> None:
- if self._keep_metric(sample_rate) or options.get("delightful_metrics.allow_all_incr"):
+ if self._keep_metric(sample_rate):
sentry_sdk.metrics.incr(
key=self._get_key(key),
value=amount,
@@ -128,7 +128,7 @@ def timing(
tags: Optional[Tags] = None,
sample_rate: float = 1,
) -> None:
- if self._keep_metric(sample_rate) or options.get("delightful_metrics.allow_all_timing"):
+ if self._keep_metric(sample_rate):
sentry_sdk.metrics.distribution(
key=self._get_key(key), value=value, tags=tags, unit="second"
)
@@ -141,6 +141,6 @@ def gauge(
tags: Optional[Tags] = None,
sample_rate: float = 1,
) -> None:
- if self._keep_metric(sample_rate) or options.get("delightful_metrics.allow_all_gauge"):
+ if self._keep_metric(sample_rate):
# XXX: make this into a gauge later
sentry_sdk.metrics.incr(key=self._get_key(key), value=value, tags=tags)
|
9695e1940730f5b5b0209a2e147f8c65ee19c3e2
|
2019-03-08 04:11:29
|
Armin Ronacher
|
feat(grouping): more accurately report the filename (#12331)
| false
|
more accurately report the filename (#12331)
|
feat
|
diff --git a/src/sentry/interfaces/stacktrace.py b/src/sentry/interfaces/stacktrace.py
index df7c55f0a7f5b4..99ae6440003d1b 100644
--- a/src/sentry/interfaces/stacktrace.py
+++ b/src/sentry/interfaces/stacktrace.py
@@ -485,15 +485,27 @@ def get_grouping_component(self, platform=None, variant=None):
# so that they're more likely to group together
filename_component = GroupingComponent(id='filename')
if self.filename == '<anonymous>':
- filename_component.update(hint='anonymous filename discarded')
+ filename_component.update(
+ contributes=False,
+ values=[self.filename],
+ hint='anonymous filename discarded'
+ )
elif self.filename == '[native code]':
contributes = False
hint = 'native code indicated by filename'
elif self.filename:
if self.is_url():
- filename_component.update(hint='ignored because filename is a URL')
+ filename_component.update(
+ contributes=False,
+ values=[self.filename],
+ hint='ignored because filename is a URL',
+ )
elif self.is_caused_by():
- filename_component.update(hint='ignored because invalid')
+ filename_component.update(
+ values=[self.filename],
+ contributes=False,
+ hint='ignored because invalid'
+ )
else:
hashable_filename, hashable_filename_hint = \
remove_filename_outliers(self.filename, platform)
@@ -519,10 +531,12 @@ def get_grouping_component(self, platform=None, variant=None):
values=[module_name],
hint=module_hint
)
- filename_component.update(
- contributes=False,
- hint='module takes precedence'
- )
+ if self.filename:
+ filename_component.update(
+ values=[self.filename],
+ contributes=False,
+ hint='module takes precedence'
+ )
# Context line when available is the primary contributor
context_line_component = GroupingComponent(id='context-line')
diff --git a/tests/sentry/event_hashing/fixtures/aspnetcore.out b/tests/sentry/event_hashing/fixtures/aspnetcore.out
index a29a44dae62f79..ccbdc093e5e785 100644
--- a/tests/sentry/event_hashing/fixtures/aspnetcore.out
+++ b/tests/sentry/event_hashing/fixtures/aspnetcore.out
@@ -7,7 +7,6 @@ app:
frame (non app frame)
module*
u'Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -15,7 +14,6 @@ app:
frame (non app frame)
module*
u'System.Runtime.CompilerServices.TaskAwaiter'
- filename (module takes precedence)
context-line*
u'Void HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)'
function (function name is used only if module or filename are available)
@@ -23,7 +21,6 @@ app:
frame (non app frame)
module*
u'System.Runtime.ExceptionServices.ExceptionDispatchInfo'
- filename (module takes precedence)
context-line*
u'Void Throw()'
function (function name is used only if module or filename are available)
@@ -31,7 +28,6 @@ app:
frame (non app frame)
module*
u'Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -39,7 +35,6 @@ app:
frame (non app frame)
module*
u'System.Runtime.CompilerServices.TaskAwaiter'
- filename (module takes precedence)
context-line*
u'Void HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)'
function (function name is used only if module or filename are available)
@@ -47,7 +42,6 @@ app:
frame (non app frame)
module*
u'System.Runtime.ExceptionServices.ExceptionDispatchInfo'
- filename (module takes precedence)
context-line*
u'Void Throw()'
function (function name is used only if module or filename are available)
@@ -55,7 +49,6 @@ app:
frame (non app frame)
module*
u'Microsoft.AspNetCore.Routing.EndpointMiddleware'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -63,7 +56,6 @@ app:
frame (non app frame)
module*
u'System.Runtime.CompilerServices.TaskAwaiter'
- filename (module takes precedence)
context-line*
u'Void HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)'
function (function name is used only if module or filename are available)
@@ -71,7 +63,6 @@ app:
frame (non app frame)
module*
u'System.Runtime.ExceptionServices.ExceptionDispatchInfo'
- filename (module takes precedence)
context-line*
u'Void Throw()'
function (function name is used only if module or filename are available)
@@ -79,7 +70,6 @@ app:
frame (non app frame)
module*
u'Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -87,7 +77,6 @@ app:
frame (non app frame)
module*
u'System.Runtime.CompilerServices.TaskAwaiter'
- filename (module takes precedence)
context-line*
u'Void HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)'
function (function name is used only if module or filename are available)
@@ -95,7 +84,6 @@ app:
frame (non app frame)
module*
u'System.Runtime.ExceptionServices.ExceptionDispatchInfo'
- filename (module takes precedence)
context-line*
u'Void Throw()'
function (function name is used only if module or filename are available)
@@ -103,7 +91,6 @@ app:
frame (non app frame)
module*
u'Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -111,7 +98,6 @@ app:
frame (non app frame)
module*
u'Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker'
- filename (module takes precedence)
context-line*
u'System.Threading.Tasks.Task Next(State ByRef, Scope ByRef, System.Object ByRef, Boolean ByRef)'
function (function name is used only if module or filename are available)
@@ -119,7 +105,6 @@ app:
frame (non app frame)
module*
u'Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker'
- filename (module takes precedence)
context-line*
u'Void Rethrow(Microsoft.AspNetCore.Mvc.Filters.ResourceExecutedContext)'
function (function name is used only if module or filename are available)
@@ -127,7 +112,6 @@ app:
frame (non app frame)
module*
u'System.Runtime.ExceptionServices.ExceptionDispatchInfo'
- filename (module takes precedence)
context-line*
u'Void Throw()'
function (function name is used only if module or filename are available)
@@ -135,7 +119,6 @@ app:
frame (non app frame)
module*
u'Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -143,7 +126,6 @@ app:
frame (non app frame)
module*
u'System.Runtime.CompilerServices.TaskAwaiter'
- filename (module takes precedence)
context-line*
u'Void HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)'
function (function name is used only if module or filename are available)
@@ -151,7 +133,6 @@ app:
frame (non app frame)
module*
u'System.Runtime.ExceptionServices.ExceptionDispatchInfo'
- filename (module takes precedence)
context-line*
u'Void Throw()'
function (function name is used only if module or filename are available)
@@ -159,7 +140,6 @@ app:
frame (non app frame)
module*
u'Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -167,7 +147,6 @@ app:
frame (non app frame)
module*
u'Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker'
- filename (module takes precedence)
context-line*
u'System.Threading.Tasks.Task Next(State ByRef, Scope ByRef, System.Object ByRef, Boolean ByRef)'
function (function name is used only if module or filename are available)
@@ -175,7 +154,6 @@ app:
frame (non app frame)
module*
u'Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker'
- filename (module takes precedence)
context-line*
u'Void Rethrow(Microsoft.AspNetCore.Mvc.Filters.ActionExecutedContext)'
function (function name is used only if module or filename are available)
@@ -183,7 +161,6 @@ app:
frame (non app frame)
module*
u'System.Runtime.ExceptionServices.ExceptionDispatchInfo'
- filename (module takes precedence)
context-line*
u'Void Throw()'
function (function name is used only if module or filename are available)
@@ -191,7 +168,6 @@ app:
frame (non app frame)
module*
u'Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -199,7 +175,6 @@ app:
frame (non app frame)
module*
u'System.Runtime.CompilerServices.TaskAwaiter'
- filename (module takes precedence)
context-line*
u'Void HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)'
function (function name is used only if module or filename are available)
@@ -207,7 +182,6 @@ app:
frame (non app frame)
module*
u'System.Runtime.ExceptionServices.ExceptionDispatchInfo'
- filename (module takes precedence)
context-line*
u'Void Throw()'
function (function name is used only if module or filename are available)
@@ -215,7 +189,6 @@ app:
frame (non app frame)
module*
u'Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -223,14 +196,12 @@ app:
frame (non app frame)
module*
u'Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor+SyncObjectResultExecutor'
- filename (module takes precedence)
context-line (discarded because line too long)
function*
u'Execute'
frame (non app frame)
module*
u'Microsoft.Extensions.Internal.ObjectMethodExecutor'
- filename (module takes precedence)
context-line*
u'System.Object Execute(System.Object, System.Object[])'
function (function name is used only if module or filename are available)
@@ -238,7 +209,6 @@ app:
frame*
module*
u'(unknown)'
- filename (module takes precedence)
context-line*
u'System.Object lambda_method(System.Runtime.CompilerServices.Closure, System.Object, System.Object[])'
function (function name is used only if module or filename are available)
@@ -275,7 +245,6 @@ system:
frame*
module*
u'Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -283,7 +252,6 @@ system:
frame*
module*
u'System.Runtime.CompilerServices.TaskAwaiter'
- filename (module takes precedence)
context-line*
u'Void HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)'
function (function name is used only if module or filename are available)
@@ -291,7 +259,6 @@ system:
frame*
module*
u'System.Runtime.ExceptionServices.ExceptionDispatchInfo'
- filename (module takes precedence)
context-line*
u'Void Throw()'
function (function name is used only if module or filename are available)
@@ -299,7 +266,6 @@ system:
frame*
module*
u'Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -307,7 +273,6 @@ system:
frame*
module*
u'System.Runtime.CompilerServices.TaskAwaiter'
- filename (module takes precedence)
context-line*
u'Void HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)'
function (function name is used only if module or filename are available)
@@ -315,7 +280,6 @@ system:
frame*
module*
u'System.Runtime.ExceptionServices.ExceptionDispatchInfo'
- filename (module takes precedence)
context-line*
u'Void Throw()'
function (function name is used only if module or filename are available)
@@ -323,7 +287,6 @@ system:
frame*
module*
u'Microsoft.AspNetCore.Routing.EndpointMiddleware'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -331,7 +294,6 @@ system:
frame*
module*
u'System.Runtime.CompilerServices.TaskAwaiter'
- filename (module takes precedence)
context-line*
u'Void HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)'
function (function name is used only if module or filename are available)
@@ -339,7 +301,6 @@ system:
frame*
module*
u'System.Runtime.ExceptionServices.ExceptionDispatchInfo'
- filename (module takes precedence)
context-line*
u'Void Throw()'
function (function name is used only if module or filename are available)
@@ -347,7 +308,6 @@ system:
frame*
module*
u'Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -355,7 +315,6 @@ system:
frame*
module*
u'System.Runtime.CompilerServices.TaskAwaiter'
- filename (module takes precedence)
context-line*
u'Void HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)'
function (function name is used only if module or filename are available)
@@ -363,7 +322,6 @@ system:
frame*
module*
u'System.Runtime.ExceptionServices.ExceptionDispatchInfo'
- filename (module takes precedence)
context-line*
u'Void Throw()'
function (function name is used only if module or filename are available)
@@ -371,7 +329,6 @@ system:
frame*
module*
u'Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -379,7 +336,6 @@ system:
frame*
module*
u'Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker'
- filename (module takes precedence)
context-line*
u'System.Threading.Tasks.Task Next(State ByRef, Scope ByRef, System.Object ByRef, Boolean ByRef)'
function (function name is used only if module or filename are available)
@@ -387,7 +343,6 @@ system:
frame*
module*
u'Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker'
- filename (module takes precedence)
context-line*
u'Void Rethrow(Microsoft.AspNetCore.Mvc.Filters.ResourceExecutedContext)'
function (function name is used only if module or filename are available)
@@ -395,7 +350,6 @@ system:
frame*
module*
u'System.Runtime.ExceptionServices.ExceptionDispatchInfo'
- filename (module takes precedence)
context-line*
u'Void Throw()'
function (function name is used only if module or filename are available)
@@ -403,7 +357,6 @@ system:
frame*
module*
u'Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -411,7 +364,6 @@ system:
frame*
module*
u'System.Runtime.CompilerServices.TaskAwaiter'
- filename (module takes precedence)
context-line*
u'Void HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)'
function (function name is used only if module or filename are available)
@@ -419,7 +371,6 @@ system:
frame*
module*
u'System.Runtime.ExceptionServices.ExceptionDispatchInfo'
- filename (module takes precedence)
context-line*
u'Void Throw()'
function (function name is used only if module or filename are available)
@@ -427,7 +378,6 @@ system:
frame*
module*
u'Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -435,7 +385,6 @@ system:
frame*
module*
u'Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker'
- filename (module takes precedence)
context-line*
u'System.Threading.Tasks.Task Next(State ByRef, Scope ByRef, System.Object ByRef, Boolean ByRef)'
function (function name is used only if module or filename are available)
@@ -443,7 +392,6 @@ system:
frame*
module*
u'Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker'
- filename (module takes precedence)
context-line*
u'Void Rethrow(Microsoft.AspNetCore.Mvc.Filters.ActionExecutedContext)'
function (function name is used only if module or filename are available)
@@ -451,7 +399,6 @@ system:
frame*
module*
u'System.Runtime.ExceptionServices.ExceptionDispatchInfo'
- filename (module takes precedence)
context-line*
u'Void Throw()'
function (function name is used only if module or filename are available)
@@ -459,7 +406,6 @@ system:
frame*
module*
u'Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -467,7 +413,6 @@ system:
frame*
module*
u'System.Runtime.CompilerServices.TaskAwaiter'
- filename (module takes precedence)
context-line*
u'Void HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)'
function (function name is used only if module or filename are available)
@@ -475,7 +420,6 @@ system:
frame*
module*
u'System.Runtime.ExceptionServices.ExceptionDispatchInfo'
- filename (module takes precedence)
context-line*
u'Void Throw()'
function (function name is used only if module or filename are available)
@@ -483,7 +427,6 @@ system:
frame*
module*
u'Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker'
- filename (module takes precedence)
context-line*
u'Void MoveNext()'
function (function name is used only if module or filename are available)
@@ -491,14 +434,12 @@ system:
frame*
module*
u'Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor+SyncObjectResultExecutor'
- filename (module takes precedence)
context-line (discarded because line too long)
function*
u'Execute'
frame*
module*
u'Microsoft.Extensions.Internal.ObjectMethodExecutor'
- filename (module takes precedence)
context-line*
u'System.Object Execute(System.Object, System.Object[])'
function (function name is used only if module or filename are available)
@@ -506,7 +447,6 @@ system:
frame*
module*
u'(unknown)'
- filename (module takes precedence)
context-line*
u'System.Object lambda_method(System.Runtime.CompilerServices.Closure, System.Object, System.Object[])'
function (function name is used only if module or filename are available)
diff --git a/tests/sentry/event_hashing/fixtures/minified-javascript.out b/tests/sentry/event_hashing/fixtures/minified-javascript.out
index 51d5be83665b43..d5823037993516 100644
--- a/tests/sentry/event_hashing/fixtures/minified-javascript.out
+++ b/tests/sentry/event_hashing/fixtures/minified-javascript.out
@@ -8,6 +8,7 @@ app:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'M'
@@ -17,6 +18,7 @@ app:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'S/<'
@@ -26,6 +28,7 @@ app:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'i'
@@ -35,6 +38,7 @@ app:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'b'
@@ -44,6 +48,7 @@ app:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'n'
@@ -53,6 +58,7 @@ app:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'g/</t[e]'
@@ -62,6 +68,7 @@ app:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'h/p._invoke</<'
@@ -71,6 +78,7 @@ app:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'W'
@@ -80,6 +88,7 @@ app:
module*
u'sentry/dist/app'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/app.js'
context-line (discarded because line too long)
function*
u'e/<'
@@ -89,6 +98,7 @@ app:
module*
u'sentry/dist/app'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/app.js'
context-line (discarded because line too long)
function*
u'e/</a</<'
@@ -98,6 +108,7 @@ app:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u't.exports/<'
@@ -107,6 +118,7 @@ app:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'L'
@@ -116,6 +128,7 @@ app:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u't.exports/</<'
@@ -125,6 +138,7 @@ app:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'c'
@@ -134,6 +148,7 @@ app:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'n'
@@ -143,6 +158,7 @@ app:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'g/</t[e]'
@@ -152,6 +168,7 @@ app:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'h/p._invoke</<'
@@ -161,6 +178,7 @@ app:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'W'
@@ -170,6 +188,7 @@ app:
module*
u'sentry/dist/app'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/app.js'
context-line (discarded because line too long)
function*
u'e/<'
@@ -179,6 +198,7 @@ app:
module*
u'sentry/dist/app'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/app.js'
context-line (discarded because line too long)
function*
u'componentPromise'
@@ -188,6 +208,7 @@ app:
module*
u'sentry/dist/app'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/app.js'
context-line (discarded because line too long)
function*
u'o.e'
@@ -197,6 +218,7 @@ app:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'Pt</t.prototype.wrapTimeFunction/<'
@@ -215,6 +237,7 @@ system:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'M'
@@ -224,6 +247,7 @@ system:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'S/<'
@@ -233,6 +257,7 @@ system:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'i'
@@ -242,6 +267,7 @@ system:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'b'
@@ -251,6 +277,7 @@ system:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'n'
@@ -260,6 +287,7 @@ system:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'g/</t[e]'
@@ -269,6 +297,7 @@ system:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'h/p._invoke</<'
@@ -278,6 +307,7 @@ system:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'W'
@@ -287,6 +317,7 @@ system:
module*
u'sentry/dist/app'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/app.js'
context-line (discarded because line too long)
function*
u'e/<'
@@ -296,6 +327,7 @@ system:
module*
u'sentry/dist/app'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/app.js'
context-line (discarded because line too long)
function*
u'e/</a</<'
@@ -305,6 +337,7 @@ system:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u't.exports/<'
@@ -314,6 +347,7 @@ system:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'L'
@@ -323,6 +357,7 @@ system:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u't.exports/</<'
@@ -332,6 +367,7 @@ system:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'c'
@@ -341,6 +377,7 @@ system:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'n'
@@ -350,6 +387,7 @@ system:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'g/</t[e]'
@@ -359,6 +397,7 @@ system:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'h/p._invoke</<'
@@ -368,6 +407,7 @@ system:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'W'
@@ -377,6 +417,7 @@ system:
module*
u'sentry/dist/app'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/app.js'
context-line (discarded because line too long)
function*
u'e/<'
@@ -386,6 +427,7 @@ system:
module*
u'sentry/dist/app'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/app.js'
context-line (discarded because line too long)
function*
u'componentPromise'
@@ -395,6 +437,7 @@ system:
module*
u'sentry/dist/app'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/app.js'
context-line (discarded because line too long)
function*
u'o.e'
@@ -404,6 +447,7 @@ system:
module*
u'sentry/dist/vendor'
filename (module takes precedence)
+ u'/_static/5788ef38fefa0df624cb96af56fd1435/sentry/dist/vendor.js'
context-line (discarded because line too long)
function*
u'Pt</t.prototype.wrapTimeFunction/<'
|
0f77e5a18a4ac05091c44f9675b15574efc79e3a
|
2024-09-24 04:34:48
|
Christinarlong
|
chore(sentry_apps): Move over misc sentry app endpoints to sentry_apps (#77887)
| false
|
Move over misc sentry app endpoints to sentry_apps (#77887)
|
chore
|
diff --git a/pyproject.toml b/pyproject.toml
index a581b0063764c7..078d2f3629a718 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -136,11 +136,7 @@ module = [
"sentry.api.endpoints.group_integration_details",
"sentry.api.endpoints.group_integrations",
"sentry.api.endpoints.index",
- "sentry.api.endpoints.integrations.sentry_apps.details",
- "sentry.api.endpoints.integrations.sentry_apps.index",
"sentry.api.endpoints.integrations.sentry_apps.internal_app_token.index",
- "sentry.api.endpoints.integrations.sentry_apps.publish_request",
- "sentry.api.endpoints.integrations.sentry_apps.requests",
"sentry.api.endpoints.integrations.sentry_apps.stats.details",
"sentry.api.endpoints.internal.mail",
"sentry.api.endpoints.organization_details",
diff --git a/src/sentry/api/endpoints/avatar/__init__.py b/src/sentry/api/endpoints/avatar/__init__.py
index 664a67ff74ec8a..1bbd8c9d306d35 100644
--- a/src/sentry/api/endpoints/avatar/__init__.py
+++ b/src/sentry/api/endpoints/avatar/__init__.py
@@ -1,7 +1,3 @@
from .organization import OrganizationAvatarEndpoint
-from .sentry_app import SentryAppAvatarEndpoint
-__all__ = (
- "OrganizationAvatarEndpoint",
- "SentryAppAvatarEndpoint",
-)
+__all__ = ("OrganizationAvatarEndpoint",)
diff --git a/src/sentry/api/endpoints/integrations/sentry_apps/__init__.py b/src/sentry/api/endpoints/integrations/sentry_apps/__init__.py
index a6a8d05d8ed9dc..a3654763c8be02 100644
--- a/src/sentry/api/endpoints/integrations/sentry_apps/__init__.py
+++ b/src/sentry/api/endpoints/integrations/sentry_apps/__init__.py
@@ -1,30 +1,9 @@
-from .authorizations import SentryAppAuthorizationsEndpoint
-from .components import OrganizationSentryAppComponentsEndpoint, SentryAppComponentsEndpoint
-from .details import SentryAppDetailsEndpoint
-from .features import SentryAppFeaturesEndpoint
-from .index import SentryAppsEndpoint
-from .interaction import SentryAppInteractionEndpoint
from .internal_app_token.details import SentryInternalAppTokenDetailsEndpoint
from .internal_app_token.index import SentryInternalAppTokensEndpoint
-from .organization_sentry_apps import OrganizationSentryAppsEndpoint
-from .publish_request import SentryAppPublishRequestEndpoint
-from .requests import SentryAppRequestsEndpoint
-from .rotate_secret import SentryAppRotateSecretEndpoint
from .stats.details import SentryAppStatsEndpoint
from .stats.index import SentryAppsStatsEndpoint
__all__ = (
- "OrganizationSentryAppComponentsEndpoint",
- "OrganizationSentryAppsEndpoint",
- "SentryAppAuthorizationsEndpoint",
- "SentryAppComponentsEndpoint",
- "SentryAppDetailsEndpoint",
- "SentryAppFeaturesEndpoint",
- "SentryAppInteractionEndpoint",
- "SentryAppPublishRequestEndpoint",
- "SentryAppRequestsEndpoint",
- "SentryAppRotateSecretEndpoint",
- "SentryAppsEndpoint",
"SentryAppsStatsEndpoint",
"SentryAppStatsEndpoint",
"SentryInternalAppTokenDetailsEndpoint",
diff --git a/src/sentry/api/endpoints/integrations/sentry_apps/internal_app_token/details.py b/src/sentry/api/endpoints/integrations/sentry_apps/internal_app_token/details.py
index 302ee27a4c140f..13b86f04d78b35 100644
--- a/src/sentry/api/endpoints/integrations/sentry_apps/internal_app_token/details.py
+++ b/src/sentry/api/endpoints/integrations/sentry_apps/internal_app_token/details.py
@@ -9,10 +9,8 @@
from sentry.api.api_publish_status import ApiPublishStatus
from sentry.api.base import control_silo_endpoint
from sentry.api.bases import SentryAppBaseEndpoint, SentryInternalAppTokenPermission
-from sentry.api.endpoints.integrations.sentry_apps.details import (
- PARTNERSHIP_RESTRICTED_ERROR_MESSAGE,
-)
from sentry.models.apitoken import ApiToken
+from sentry.sentry_apps.api.endpoints.sentry_app_details import PARTNERSHIP_RESTRICTED_ERROR_MESSAGE
from sentry.sentry_apps.models.sentry_app_installation_token import SentryAppInstallationToken
diff --git a/src/sentry/api/endpoints/integrations/sentry_apps/internal_app_token/index.py b/src/sentry/api/endpoints/integrations/sentry_apps/internal_app_token/index.py
index 0999cf93d6cc35..932ace3fd120db 100644
--- a/src/sentry/api/endpoints/integrations/sentry_apps/internal_app_token/index.py
+++ b/src/sentry/api/endpoints/integrations/sentry_apps/internal_app_token/index.py
@@ -7,12 +7,10 @@
from sentry.api.authentication import SessionNoAuthTokenAuthentication
from sentry.api.base import control_silo_endpoint
from sentry.api.bases import SentryAppBaseEndpoint, SentryInternalAppTokenPermission
-from sentry.api.endpoints.integrations.sentry_apps.details import (
- PARTNERSHIP_RESTRICTED_ERROR_MESSAGE,
-)
from sentry.api.serializers.models.apitoken import ApiTokenSerializer
from sentry.exceptions import ApiTokenLimitError
from sentry.models.apitoken import ApiToken
+from sentry.sentry_apps.api.endpoints.sentry_app_details import PARTNERSHIP_RESTRICTED_ERROR_MESSAGE
from sentry.sentry_apps.installations import SentryAppInstallationTokenCreator
from sentry.sentry_apps.models.sentry_app import MASKED_VALUE
from sentry.sentry_apps.models.sentry_app_installation import SentryAppInstallation
diff --git a/src/sentry/api/urls.py b/src/sentry/api/urls.py
index b7803b5bd5fad5..b57570d5f0507c 100644
--- a/src/sentry/api/urls.py
+++ b/src/sentry/api/urls.py
@@ -290,7 +290,25 @@
from sentry.sentry_apps.api.endpoints.installation_external_requests import (
SentryAppInstallationExternalRequestsEndpoint,
)
+from sentry.sentry_apps.api.endpoints.organization_sentry_apps import OrganizationSentryAppsEndpoint
+from sentry.sentry_apps.api.endpoints.sentry_app_authorizations import (
+ SentryAppAuthorizationsEndpoint,
+)
+from sentry.sentry_apps.api.endpoints.sentry_app_avatar import SentryAppAvatarEndpoint
+from sentry.sentry_apps.api.endpoints.sentry_app_components import (
+ OrganizationSentryAppComponentsEndpoint,
+ SentryAppComponentsEndpoint,
+)
+from sentry.sentry_apps.api.endpoints.sentry_app_details import SentryAppDetailsEndpoint
+from sentry.sentry_apps.api.endpoints.sentry_app_features import SentryAppFeaturesEndpoint
from sentry.sentry_apps.api.endpoints.sentry_app_installations import SentryAppInstallationsEndpoint
+from sentry.sentry_apps.api.endpoints.sentry_app_interaction import SentryAppInteractionEndpoint
+from sentry.sentry_apps.api.endpoints.sentry_app_publish_request import (
+ SentryAppPublishRequestEndpoint,
+)
+from sentry.sentry_apps.api.endpoints.sentry_app_requests import SentryAppRequestsEndpoint
+from sentry.sentry_apps.api.endpoints.sentry_app_rotate_secret import SentryAppRotateSecretEndpoint
+from sentry.sentry_apps.api.endpoints.sentry_apps import SentryAppsEndpoint
from sentry.uptime.endpoints.project_uptime_alert_details import ProjectUptimeAlertDetailsEndpoint
from sentry.uptime.endpoints.project_uptime_alert_index import ProjectUptimeAlertIndexEndpoint
from sentry.users.api.endpoints.authenticator_index import AuthenticatorIndexEndpoint
@@ -335,7 +353,7 @@
from .endpoints.auth_index import AuthIndexEndpoint
from .endpoints.auth_login import AuthLoginEndpoint
from .endpoints.auth_validate import AuthValidateEndpoint
-from .endpoints.avatar import OrganizationAvatarEndpoint, SentryAppAvatarEndpoint
+from .endpoints.avatar import OrganizationAvatarEndpoint
from .endpoints.broadcast_details import BroadcastDetailsEndpoint
from .endpoints.broadcast_index import BroadcastIndexEndpoint
from .endpoints.builtin_symbol_sources import BuiltinSymbolSourcesEndpoint
@@ -380,17 +398,6 @@
from .endpoints.grouping_configs import GroupingConfigsEndpoint
from .endpoints.index import IndexEndpoint
from .endpoints.integrations.sentry_apps import (
- OrganizationSentryAppComponentsEndpoint,
- OrganizationSentryAppsEndpoint,
- SentryAppAuthorizationsEndpoint,
- SentryAppComponentsEndpoint,
- SentryAppDetailsEndpoint,
- SentryAppFeaturesEndpoint,
- SentryAppInteractionEndpoint,
- SentryAppPublishRequestEndpoint,
- SentryAppRequestsEndpoint,
- SentryAppRotateSecretEndpoint,
- SentryAppsEndpoint,
SentryAppsStatsEndpoint,
SentryAppStatsEndpoint,
SentryInternalAppTokenDetailsEndpoint,
diff --git a/src/sentry/api/endpoints/integrations/sentry_apps/organization_sentry_apps.py b/src/sentry/sentry_apps/api/endpoints/organization_sentry_apps.py
similarity index 100%
rename from src/sentry/api/endpoints/integrations/sentry_apps/organization_sentry_apps.py
rename to src/sentry/sentry_apps/api/endpoints/organization_sentry_apps.py
diff --git a/src/sentry/api/endpoints/integrations/sentry_apps/authorizations.py b/src/sentry/sentry_apps/api/endpoints/sentry_app_authorizations.py
similarity index 100%
rename from src/sentry/api/endpoints/integrations/sentry_apps/authorizations.py
rename to src/sentry/sentry_apps/api/endpoints/sentry_app_authorizations.py
diff --git a/src/sentry/api/endpoints/avatar/sentry_app.py b/src/sentry/sentry_apps/api/endpoints/sentry_app_avatar.py
similarity index 100%
rename from src/sentry/api/endpoints/avatar/sentry_app.py
rename to src/sentry/sentry_apps/api/endpoints/sentry_app_avatar.py
diff --git a/src/sentry/api/endpoints/integrations/sentry_apps/components.py b/src/sentry/sentry_apps/api/endpoints/sentry_app_components.py
similarity index 100%
rename from src/sentry/api/endpoints/integrations/sentry_apps/components.py
rename to src/sentry/sentry_apps/api/endpoints/sentry_app_components.py
diff --git a/src/sentry/api/endpoints/integrations/sentry_apps/details.py b/src/sentry/sentry_apps/api/endpoints/sentry_app_details.py
similarity index 96%
rename from src/sentry/api/endpoints/integrations/sentry_apps/details.py
rename to src/sentry/sentry_apps/api/endpoints/sentry_app_details.py
index 635361f7ce03ed..2d335e1e986299 100644
--- a/src/sentry/api/endpoints/integrations/sentry_apps/details.py
+++ b/src/sentry/sentry_apps/api/endpoints/sentry_app_details.py
@@ -25,6 +25,8 @@
from sentry.sentry_apps.logic import SentryAppUpdater
from sentry.sentry_apps.models.sentry_app import SentryApp
from sentry.sentry_apps.models.sentry_app_installation import SentryAppInstallation
+from sentry.users.models.user import User
+from sentry.users.services.user.model import RpcUser
from sentry.utils.audit import create_audit_entry
logger = logging.getLogger(__name__)
@@ -91,6 +93,10 @@ def put(self, request: Request, sentry_app) -> Response:
if serializer.is_valid():
result = serializer.validated_data
+
+ assert isinstance(
+ request.user, (User, RpcUser)
+ ), "User must be authenticated to update a Sentry App"
updated_app = SentryAppUpdater(
sentry_app=sentry_app,
name=result.get("name"),
diff --git a/src/sentry/api/endpoints/integrations/sentry_apps/features.py b/src/sentry/sentry_apps/api/endpoints/sentry_app_features.py
similarity index 100%
rename from src/sentry/api/endpoints/integrations/sentry_apps/features.py
rename to src/sentry/sentry_apps/api/endpoints/sentry_app_features.py
diff --git a/src/sentry/api/endpoints/integrations/sentry_apps/interaction.py b/src/sentry/sentry_apps/api/endpoints/sentry_app_interaction.py
similarity index 100%
rename from src/sentry/api/endpoints/integrations/sentry_apps/interaction.py
rename to src/sentry/sentry_apps/api/endpoints/sentry_app_interaction.py
diff --git a/src/sentry/api/endpoints/integrations/sentry_apps/publish_request.py b/src/sentry/sentry_apps/api/endpoints/sentry_app_publish_request.py
similarity index 84%
rename from src/sentry/api/endpoints/integrations/sentry_apps/publish_request.py
rename to src/sentry/sentry_apps/api/endpoints/sentry_app_publish_request.py
index e08901bf55e3d4..63b096b75f41f6 100644
--- a/src/sentry/api/endpoints/integrations/sentry_apps/publish_request.py
+++ b/src/sentry/sentry_apps/api/endpoints/sentry_app_publish_request.py
@@ -1,3 +1,5 @@
+from collections.abc import Iterable
+
from rest_framework.request import Request
from rest_framework.response import Response
@@ -10,6 +12,8 @@
from sentry.models.avatars.sentry_app_avatar import SentryAppAvatar, SentryAppAvatarTypes
from sentry.models.organizationmapping import OrganizationMapping
from sentry.sentry_apps.logic import SentryAppUpdater
+from sentry.users.models.user import User
+from sentry.users.services.user.model import RpcUser
from sentry.utils import email
@@ -54,6 +58,9 @@ def post(self, request: Request, sentry_app) -> Response:
status=400,
)
+ assert isinstance(request.user, User) or isinstance(
+ request.user, RpcUser
+ ), "User must be authenticated to update a Sentry App"
SentryAppUpdater(
sentry_app=sentry_app,
status=SentryAppStatus.PUBLISH_REQUEST_INPROGRESS_STR,
@@ -65,8 +72,11 @@ def post(self, request: Request, sentry_app) -> Response:
org_slug = "<unknown>" if org_mapping is None else org_mapping.slug
message = f"User {request.user.email} of organization {org_slug} wants to publish {sentry_app.slug}\n"
- for question_pair in request.data.get("questionnaire"):
- message += "\n\n>{}\n{}".format(question_pair["question"], question_pair["answer"])
+ questionnaire: Iterable[dict[str, str]] = request.data.get("questionnaire", [])
+ for question_pair in questionnaire:
+ message += "\n\n>{}\n{}".format(
+ question_pair.get("question", ""), question_pair.get("answer", "")
+ )
subject = "Sentry Integration Publication Request from %s" % org_slug
diff --git a/src/sentry/api/endpoints/integrations/sentry_apps/requests.py b/src/sentry/sentry_apps/api/endpoints/sentry_app_requests.py
similarity index 81%
rename from src/sentry/api/endpoints/integrations/sentry_apps/requests.py
rename to src/sentry/sentry_apps/api/endpoints/sentry_app_requests.py
index fed9ed90bf669c..0d0b4c6db90731 100644
--- a/src/sentry/api/endpoints/integrations/sentry_apps/requests.py
+++ b/src/sentry/sentry_apps/api/endpoints/sentry_app_requests.py
@@ -18,7 +18,7 @@
INVALID_DATE_FORMAT_MESSAGE = "Invalid date format. Format must be YYYY-MM-DD HH:MM:SS."
-def filter_by_date(request: Mapping[str, Any], start: float, end: float) -> bool:
+def filter_by_date(request: Mapping[str, Any], start: datetime, end: datetime) -> bool:
date_str = request.get("date")
if not date_str:
return False
@@ -26,7 +26,7 @@ def filter_by_date(request: Mapping[str, Any], start: float, end: float) -> bool
return start <= timestamp <= end
-def filter_by_organization(request: Mapping[str, Any], organization: Organization) -> bool:
+def filter_by_organization(request: Mapping[str, Any], organization: Organization | None) -> bool:
if not organization:
return True
return request["organization_id"] == organization.id
@@ -57,27 +57,31 @@ def get(self, request: Request, sentry_app) -> Response:
:qparam string start: Optionally specify a date to begin at. Format must be YYYY-MM-DD HH:MM:SS
:qparam string end: Optionally specify a date to end at. Format must be YYYY-MM-DD HH:MM:SS
"""
+
date_format = "%Y-%m-%d %H:%M:%S"
- now = datetime.now().strftime(date_format)
- default_start = "2000-01-01 00:00:00"
+ start_time: datetime = datetime.strptime("2000-01-01 00:00:00", date_format)
+ end_time: datetime = datetime.now()
event_type = request.GET.get("eventType")
errors_only = request.GET.get("errorsOnly")
org_slug = request.GET.get("organizationSlug")
- start = request.GET.get("start", default_start)
- end = request.GET.get("end", now)
+ start_parameter = request.GET.get("start", None)
+ end_parameter = request.GET.get("end", None)
try:
- start = datetime.strptime(start, date_format)
+ start_time = (
+ datetime.strptime(start_parameter, date_format) if start_parameter else start_time
+ )
except ValueError:
return Response({"detail": INVALID_DATE_FORMAT_MESSAGE}, status=400)
try:
- end = datetime.strptime(end, date_format)
+
+ end_time = datetime.strptime(end_parameter, date_format) if end_parameter else end_time
except ValueError:
return Response({"detail": INVALID_DATE_FORMAT_MESSAGE}, status=400)
- kwargs = {}
+ kwargs: dict[Any, Any] = {}
if event_type:
if event_type not in EXTENDED_VALID_EVENTS:
return Response({"detail": "Invalid event type."}, status=400)
@@ -95,7 +99,9 @@ def get(self, request: Request, sentry_app) -> Response:
filtered_requests = []
for i, req in enumerate(buffer.get_requests(**kwargs)):
- if filter_by_date(req, start, end) and filter_by_organization(req, organization):
+ if filter_by_date(req, start_time, end_time) and filter_by_organization(
+ req, organization
+ ):
filtered_requests.append(BufferedRequest(id=i, data=req))
return Response(serialize(filtered_requests, request.user, RequestSerializer(sentry_app)))
diff --git a/src/sentry/api/endpoints/integrations/sentry_apps/rotate_secret.py b/src/sentry/sentry_apps/api/endpoints/sentry_app_rotate_secret.py
similarity index 100%
rename from src/sentry/api/endpoints/integrations/sentry_apps/rotate_secret.py
rename to src/sentry/sentry_apps/api/endpoints/sentry_app_rotate_secret.py
diff --git a/src/sentry/api/endpoints/integrations/sentry_apps/index.py b/src/sentry/sentry_apps/api/endpoints/sentry_apps.py
similarity index 96%
rename from src/sentry/api/endpoints/integrations/sentry_apps/index.py
rename to src/sentry/sentry_apps/api/endpoints/sentry_apps.py
index 976e85e89cd0ec..73582331055df1 100644
--- a/src/sentry/api/endpoints/integrations/sentry_apps/index.py
+++ b/src/sentry/sentry_apps/api/endpoints/sentry_apps.py
@@ -18,6 +18,8 @@
from sentry.constants import SentryAppStatus
from sentry.sentry_apps.logic import SentryAppCreator
from sentry.sentry_apps.models.sentry_app import SentryApp
+from sentry.users.models.user import User
+from sentry.users.services.user.model import RpcUser
from sentry.users.services.user.service import user_service
logger = logging.getLogger(__name__)
@@ -115,6 +117,9 @@ def post(self, request: Request, organization) -> Response:
data["author"] = data["author"] or organization.name
try:
+ assert isinstance(
+ request.user, (User, RpcUser)
+ ), "User must be authenticated to create a Sentry App"
sentry_app = SentryAppCreator(
name=data["name"],
author=data["author"],
diff --git a/src/sentry/sentry_apps/installations.py b/src/sentry/sentry_apps/installations.py
index 9cf122a680c301..b28a3aa5c7ddcb 100644
--- a/src/sentry/sentry_apps/installations.py
+++ b/src/sentry/sentry_apps/installations.py
@@ -29,7 +29,7 @@ class SentryAppInstallationTokenCreator:
expires_at: datetime.date | None = None
generate_audit: bool = False
- def run(self, user: User, request: HttpRequest | None = None) -> ApiToken:
+ def run(self, user: User | RpcUser, request: HttpRequest | None = None) -> ApiToken:
with transaction.atomic(router.db_for_write(ApiToken)):
self._check_token_limit()
api_token = self._create_api_token()
diff --git a/src/sentry/sentry_apps/logic.py b/src/sentry/sentry_apps/logic.py
index d4ef64b14b65d8..f99226d4b4b5e9 100644
--- a/src/sentry/sentry_apps/logic.py
+++ b/src/sentry/sentry_apps/logic.py
@@ -101,7 +101,7 @@ class SentryAppUpdater:
popularity: int | None = None
features: list[int] | None = None
- def run(self, user: User) -> SentryApp:
+ def run(self, user: User | RpcUser) -> SentryApp:
with transaction.atomic(router.db_for_write(User)):
self._update_name()
self._update_author()
@@ -122,7 +122,7 @@ def run(self, user: User) -> SentryApp:
self.record_analytics(user, new_schema_elements)
return self.sentry_app
- def _update_features(self, user: User) -> None:
+ def _update_features(self, user: User | RpcUser) -> None:
if self.features is not None:
if not _is_elevated_user(user) and self.sentry_app.status == SentryAppStatus.PUBLISHED:
raise APIError("Cannot update features on a published integration.")
@@ -141,7 +141,7 @@ def _update_author(self) -> None:
if self.author is not None:
self.sentry_app.author = self.author
- def _update_status(self, user: User) -> None:
+ def _update_status(self, user: User | RpcUser) -> None:
if self.status is not None:
if _is_elevated_user(user):
if self.status == SentryAppStatus.PUBLISHED_STR:
@@ -239,7 +239,7 @@ def _update_allowed_origins(self) -> None:
self.sentry_app.application.allowed_origins = "\n".join(self.allowed_origins)
self.sentry_app.application.save()
- def _update_popularity(self, user: User) -> None:
+ def _update_popularity(self, user: User | RpcUser) -> None:
if self.popularity is not None:
if _is_elevated_user(user):
self.sentry_app.popularity = self.popularity
@@ -269,7 +269,7 @@ def _create_ui_components(self) -> None:
type=element["type"], sentry_app_id=self.sentry_app.id, schema=element
)
- def record_analytics(self, user: User, new_schema_elements: set[str] | None) -> None:
+ def record_analytics(self, user: User | RpcUser, new_schema_elements: set[str] | None) -> None:
analytics.record(
"sentry_app.updated",
user_id=user.id,
@@ -306,7 +306,7 @@ def __post_init__(self) -> None:
def run(
self,
*,
- user: User,
+ user: User | RpcUser,
request: HttpRequest | None = None,
skip_default_auth_token: bool = False,
) -> SentryApp:
@@ -407,7 +407,7 @@ def _create_integration_feature(self, sentry_app: SentryApp) -> None:
sentry_sdk.capture_message("IntegrityError while creating IntegrationFeature")
def _install(
- self, *, slug: str, user: User, request: HttpRequest | None
+ self, *, slug: str, user: User | RpcUser, request: HttpRequest | None
) -> SentryAppInstallation:
return SentryAppInstallationCreator(
organization_id=self.organization_id,
@@ -416,7 +416,7 @@ def _install(
).run(user=user, request=request)
def _create_access_token(
- self, user: User, install: SentryAppInstallation, request: HttpRequest | None
+ self, user: User | RpcUser, install: SentryAppInstallation, request: HttpRequest | None
) -> None:
install.api_token = SentryAppInstallationTokenCreator(sentry_app_installation=install).run(
request=request, user=user
@@ -444,7 +444,7 @@ def audit(self, request: HttpRequest | None, sentry_app: SentryApp) -> None:
data={"name": sentry_app.name},
)
- def record_analytics(self, user: User, sentry_app: SentryApp) -> None:
+ def record_analytics(self, user: User | RpcUser, sentry_app: SentryApp) -> None:
analytics.record(
"sentry_app.created",
user_id=user.id,
diff --git a/tests/sentry/sentry_apps/api/endpoints/__init__.py b/tests/sentry/sentry_apps/api/endpoints/__init__.py
new file mode 100644
index 00000000000000..e69de29bb2d1d6
diff --git a/tests/sentry/api/endpoints/test_organization_sentry_apps.py b/tests/sentry/sentry_apps/api/endpoints/test_organization_sentry_apps.py
similarity index 100%
rename from tests/sentry/api/endpoints/test_organization_sentry_apps.py
rename to tests/sentry/sentry_apps/api/endpoints/test_organization_sentry_apps.py
diff --git a/tests/sentry/api/endpoints/test_sentry_app_authorizations.py b/tests/sentry/sentry_apps/api/endpoints/test_sentry_app_authorizations.py
similarity index 100%
rename from tests/sentry/api/endpoints/test_sentry_app_authorizations.py
rename to tests/sentry/sentry_apps/api/endpoints/test_sentry_app_authorizations.py
diff --git a/tests/sentry/api/endpoints/test_sentry_app_avatar.py b/tests/sentry/sentry_apps/api/endpoints/test_sentry_app_avatar.py
similarity index 100%
rename from tests/sentry/api/endpoints/test_sentry_app_avatar.py
rename to tests/sentry/sentry_apps/api/endpoints/test_sentry_app_avatar.py
diff --git a/tests/sentry/api/endpoints/test_sentry_app_components.py b/tests/sentry/sentry_apps/api/endpoints/test_sentry_app_components.py
similarity index 100%
rename from tests/sentry/api/endpoints/test_sentry_app_components.py
rename to tests/sentry/sentry_apps/api/endpoints/test_sentry_app_components.py
diff --git a/tests/sentry/api/endpoints/test_sentry_app_details.py b/tests/sentry/sentry_apps/api/endpoints/test_sentry_app_details.py
similarity index 99%
rename from tests/sentry/api/endpoints/test_sentry_app_details.py
rename to tests/sentry/sentry_apps/api/endpoints/test_sentry_app_details.py
index f12855ac8844a3..bef1fcd53d2639 100644
--- a/tests/sentry/api/endpoints/test_sentry_app_details.py
+++ b/tests/sentry/sentry_apps/api/endpoints/test_sentry_app_details.py
@@ -3,12 +3,10 @@
import orjson
from sentry import audit_log, deletions
-from sentry.api.endpoints.integrations.sentry_apps.details import (
- PARTNERSHIP_RESTRICTED_ERROR_MESSAGE,
-)
from sentry.constants import SentryAppStatus
from sentry.models.auditlogentry import AuditLogEntry
from sentry.models.organizationmember import OrganizationMember
+from sentry.sentry_apps.api.endpoints.sentry_app_details import PARTNERSHIP_RESTRICTED_ERROR_MESSAGE
from sentry.sentry_apps.models.sentry_app import SentryApp
from sentry.sentry_apps.models.sentry_app_installation import SentryAppInstallation
from sentry.sentry_apps.models.servicehook import ServiceHook
diff --git a/tests/sentry/api/endpoints/test_sentry_app_features.py b/tests/sentry/sentry_apps/api/endpoints/test_sentry_app_features.py
similarity index 100%
rename from tests/sentry/api/endpoints/test_sentry_app_features.py
rename to tests/sentry/sentry_apps/api/endpoints/test_sentry_app_features.py
diff --git a/tests/sentry/api/endpoints/sentry_apps/test_interaction.py b/tests/sentry/sentry_apps/api/endpoints/test_sentry_app_interaction.py
similarity index 100%
rename from tests/sentry/api/endpoints/sentry_apps/test_interaction.py
rename to tests/sentry/sentry_apps/api/endpoints/test_sentry_app_interaction.py
diff --git a/tests/sentry/api/endpoints/test_sentry_app_publish_request.py b/tests/sentry/sentry_apps/api/endpoints/test_sentry_app_publish_request.py
similarity index 100%
rename from tests/sentry/api/endpoints/test_sentry_app_publish_request.py
rename to tests/sentry/sentry_apps/api/endpoints/test_sentry_app_publish_request.py
diff --git a/tests/sentry/api/endpoints/test_sentry_app_requests.py b/tests/sentry/sentry_apps/api/endpoints/test_sentry_app_requests.py
similarity index 99%
rename from tests/sentry/api/endpoints/test_sentry_app_requests.py
rename to tests/sentry/sentry_apps/api/endpoints/test_sentry_app_requests.py
index c19316808bd340..c72303be78f208 100644
--- a/tests/sentry/api/endpoints/test_sentry_app_requests.py
+++ b/tests/sentry/sentry_apps/api/endpoints/test_sentry_app_requests.py
@@ -2,7 +2,7 @@
from django.urls import reverse
-from sentry.api.endpoints.integrations.sentry_apps.requests import INVALID_DATE_FORMAT_MESSAGE
+from sentry.sentry_apps.api.endpoints.sentry_app_requests import INVALID_DATE_FORMAT_MESSAGE
from sentry.testutils.cases import APITestCase
from sentry.testutils.helpers.datetime import before_now, freeze_time, iso_format
from sentry.testutils.skips import requires_snuba
diff --git a/tests/sentry/api/endpoints/test_sentry_app_rotate_secret.py b/tests/sentry/sentry_apps/api/endpoints/test_sentry_app_rotate_secret.py
similarity index 100%
rename from tests/sentry/api/endpoints/test_sentry_app_rotate_secret.py
rename to tests/sentry/sentry_apps/api/endpoints/test_sentry_app_rotate_secret.py
diff --git a/tests/sentry/api/endpoints/test_sentry_apps.py b/tests/sentry/sentry_apps/api/endpoints/test_sentry_apps.py
similarity index 100%
rename from tests/sentry/api/endpoints/test_sentry_apps.py
rename to tests/sentry/sentry_apps/api/endpoints/test_sentry_apps.py
|
a594acd4b430802efa9b8e029fc373ec273fe6aa
|
2024-05-10 20:42:58
|
Evan Purkhiser
|
ref(deps): Run yarn-deduplicate (#70654)
| false
|
Run yarn-deduplicate (#70654)
|
ref
|
diff --git a/yarn.lock b/yarn.lock
index 2f0b8f337e5969..a943cbf82d241a 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -2019,13 +2019,6 @@
dependencies:
"@opentelemetry/api" "^1.0.0"
-"@opentelemetry/[email protected]":
- version "0.51.0"
- resolved "https://registry.yarnpkg.com/@opentelemetry/api-logs/-/api-logs-0.51.0.tgz#71f296661d2215167c748ca044ff184a65d9426b"
- integrity sha512-m/jtfBPEIXS1asltl8fPQtO3Sb1qMpuL61unQajUmM8zIxeMF1AlqzWXM3QedcYgTTFiJCew5uJjyhpmqhc0+g==
- dependencies:
- "@opentelemetry/api" "^1.0.0"
-
"@opentelemetry/[email protected]":
version "0.51.1"
resolved "https://registry.yarnpkg.com/@opentelemetry/api-logs/-/api-logs-0.51.1.tgz#ded1874c04516c2b8cb24828eef3d6c3d1f75343"
@@ -2050,20 +2043,13 @@
dependencies:
"@opentelemetry/semantic-conventions" "1.23.0"
-"@opentelemetry/[email protected]", "@opentelemetry/core@^1.24.1":
+"@opentelemetry/[email protected]", "@opentelemetry/core@^1.1.0", "@opentelemetry/core@^1.24.1", "@opentelemetry/core@^1.8.0":
version "1.24.1"
resolved "https://registry.yarnpkg.com/@opentelemetry/core/-/core-1.24.1.tgz#35ab9d2ac9ca938e0ffbdfa40c49c169ac8ba80d"
integrity sha512-wMSGfsdmibI88K9wB498zXY04yThPexo8jvwNNlm542HZB7XrrMRBbAyKJqG8qDRJwIBdBrPMi4V9ZPW/sqrcg==
dependencies:
"@opentelemetry/semantic-conventions" "1.24.1"
-"@opentelemetry/core@^1.1.0", "@opentelemetry/core@^1.8.0":
- version "1.24.0"
- resolved "https://registry.yarnpkg.com/@opentelemetry/core/-/core-1.24.0.tgz#5568b6c1328a6b9c94a77f9b2c7f872b852bba40"
- integrity sha512-FP2oN7mVPqcdxJDTTnKExj4mi91EH+DNuArKfHTjPuJWe2K1JfMIVXNfahw1h3onJxQnxS8K0stKkogX05s+Aw==
- dependencies:
- "@opentelemetry/semantic-conventions" "1.24.0"
-
"@opentelemetry/[email protected]":
version "0.35.0"
resolved "https://registry.yarnpkg.com/@opentelemetry/instrumentation-connect/-/instrumentation-connect-0.35.0.tgz#d7c68f46ab04f10dc8792ef1fd023eb01748d8db"
@@ -2205,7 +2191,7 @@
semver "^7.5.2"
shimmer "^1.2.1"
-"@opentelemetry/[email protected]", "@opentelemetry/instrumentation@^0.51.1":
+"@opentelemetry/[email protected]", "@opentelemetry/instrumentation@^0.51.0", "@opentelemetry/instrumentation@^0.51.1":
version "0.51.1"
resolved "https://registry.yarnpkg.com/@opentelemetry/instrumentation/-/instrumentation-0.51.1.tgz#46fb2291150ec6923e50b2f094b9407bc726ca9b"
integrity sha512-JIrvhpgqY6437QIqToyozrUG1h5UhwHkaGK/WAX+fkrpyPtc+RO5FkRtUd9BH0MibabHHvqsnBGKfKVijbmp8w==
@@ -2239,18 +2225,6 @@
semver "^7.5.2"
shimmer "^1.2.1"
-"@opentelemetry/instrumentation@^0.51.0":
- version "0.51.0"
- resolved "https://registry.yarnpkg.com/@opentelemetry/instrumentation/-/instrumentation-0.51.0.tgz#93dbe96c87da539081d0ccd07475cfc0b0c61233"
- integrity sha512-Eg/+Od5bEvzpvZQGhvMyKIkrzB9S7jW+6z9LHEI2VXhl/GrqQ3oBqlzJt4tA6pGtxRmqQWKWGM1wAbwDdW/gUA==
- dependencies:
- "@opentelemetry/api-logs" "0.51.0"
- "@types/shimmer" "^1.0.2"
- import-in-the-middle "1.7.1"
- require-in-the-middle "^7.1.1"
- semver "^7.5.2"
- shimmer "^1.2.1"
-
"@opentelemetry/redis-common@^0.36.2":
version "0.36.2"
resolved "https://registry.yarnpkg.com/@opentelemetry/redis-common/-/redis-common-0.36.2.tgz#906ac8e4d804d4109f3ebd5c224ac988276fdc47"
@@ -2287,12 +2261,7 @@
resolved "https://registry.yarnpkg.com/@opentelemetry/semantic-conventions/-/semantic-conventions-1.23.0.tgz#627f2721b960fe586b7f72a07912cb7699f06eef"
integrity sha512-MiqFvfOzfR31t8cc74CTP1OZfz7MbqpAnLCra8NqQoaHJX6ncIRTdYOQYBDQ2uFISDq0WY8Y9dDTWvsgzzBYRg==
-"@opentelemetry/[email protected]", "@opentelemetry/semantic-conventions@^1.0.0", "@opentelemetry/semantic-conventions@^1.17.0", "@opentelemetry/semantic-conventions@^1.22.0", "@opentelemetry/semantic-conventions@^1.23.0":
- version "1.24.0"
- resolved "https://registry.yarnpkg.com/@opentelemetry/semantic-conventions/-/semantic-conventions-1.24.0.tgz#f074db930a7feb4d64103a9a576c5fbad046fcac"
- integrity sha512-yL0jI6Ltuz8R+Opj7jClGrul6pOoYrdfVmzQS4SITXRPH7I5IRZbrwe/6/v8v4WYMa6MYZG480S1+uc/IGfqsA==
-
-"@opentelemetry/[email protected]":
+"@opentelemetry/[email protected]", "@opentelemetry/semantic-conventions@^1.0.0", "@opentelemetry/semantic-conventions@^1.17.0", "@opentelemetry/semantic-conventions@^1.22.0", "@opentelemetry/semantic-conventions@^1.23.0":
version "1.24.1"
resolved "https://registry.yarnpkg.com/@opentelemetry/semantic-conventions/-/semantic-conventions-1.24.1.tgz#d4bcebda1cb5146d47a2a53daaa7922f8e084dfb"
integrity sha512-VkliWlS4/+GHLLW7J/rVBA00uXus1SWvwFvcUDxDwmFxYfg/2VI6ekwdXS28cjI8Qz2ky2BzG8OUHo+WeYIWqw==
|
979d976f16bf6ebb3508f1628f2946d36c537835
|
2020-06-30 17:45:14
|
Priscila Oliveira
|
ref(relay): Remove relay-config feature flag (#19631)
| false
|
Remove relay-config feature flag (#19631)
|
ref
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index b3f9177477fd89..1cd9f15f1b0105 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -875,8 +875,6 @@ def create_partitioned_queues(name):
"organizations:datascrubbers-v2": True,
# Enable the new version of interface/breadcrumbs
"organizations:breadcrumbs-v2": False,
- # Enable Relay config feature
- "organizations:relay-config": False,
# Enable usage of external relays, for use with Relay. See
# https://github.com/getsentry/relay.
"organizations:relay": False,
diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py
index 07637dec9f350f..8da6b4a074d2d2 100644
--- a/src/sentry/features/__init__.py
+++ b/src/sentry/features/__init__.py
@@ -87,7 +87,6 @@
default_manager.add("organizations:org-subdomains", OrganizationFeature) # NOQA
default_manager.add("organizations:performance-view", OrganizationFeature) # NOQA
default_manager.add("organizations:relay", OrganizationFeature) # NOQA
-default_manager.add("organizations:relay-config", OrganizationFeature) # NOQA
default_manager.add("organizations:releases-v2", OrganizationFeature) # NOQA
default_manager.add("organizations:rule-page", OrganizationFeature) # NOQA
default_manager.add("organizations:set-grouping-config", OrganizationFeature) # NOQA
diff --git a/src/sentry/static/sentry/app/views/settings/organization/navigationConfiguration.tsx b/src/sentry/static/sentry/app/views/settings/organization/navigationConfiguration.tsx
index 395c691bd8f97f..0d0a0055de7a2c 100644
--- a/src/sentry/static/sentry/app/views/settings/organization/navigationConfiguration.tsx
+++ b/src/sentry/static/sentry/app/views/settings/organization/navigationConfiguration.tsx
@@ -74,8 +74,7 @@ const organizationNavigation: NavigationSection[] = [
{
path: `${pathPrefix}/relays/`,
title: t('Relays'),
- show: ({access, features}) =>
- features!.has('relay-config') && access!.has('org:write'),
+ show: ({access, features}) => features!.has('relay') && access!.has('org:write'),
description: t('Manage relays connected to the organization'),
id: 'relays',
badge: () => 'new',
|
f2d48feebecfabfa7b66a6c58e4fb8807217dcb7
|
2023-01-10 03:13:49
|
George Gritsouk
|
feat(perf-issues): Add UI for N+1 API Calls rollout rate project option (#42967)
| false
|
Add UI for N+1 API Calls rollout rate project option (#42967)
|
feat
|
diff --git a/static/app/views/settings/projectPerformance/projectPerformance.tsx b/static/app/views/settings/projectPerformance/projectPerformance.tsx
index a3010163ed4767..83cbb39b222bbf 100644
--- a/static/app/views/settings/projectPerformance/projectPerformance.tsx
+++ b/static/app/views/settings/projectPerformance/projectPerformance.tsx
@@ -200,6 +200,15 @@ class ProjectPerformance extends AsyncView<Props, State> {
max: 1000000.0,
defaultValue: 500,
},
+ {
+ name: 'n_plus_one_api_calls_detection_rate',
+ type: 'range',
+ label: t('N+1 API Calls Detection Rate'),
+ min: 0.0,
+ max: 1.0,
+ step: 0.01,
+ defaultValue: 0,
+ },
];
}
|
49727106682e0b9037b1a415d2f60f18c812afcd
|
2024-07-11 01:55:19
|
Shruthi
|
feat(discover): Optionally pass dataset to mini card queries (#74091)
| false
|
Optionally pass dataset to mini card queries (#74091)
|
feat
|
diff --git a/static/app/views/discover/miniGraph.tsx b/static/app/views/discover/miniGraph.tsx
index e05f512c84f184..2a21e9f9bae09c 100644
--- a/static/app/views/discover/miniGraph.tsx
+++ b/static/app/views/discover/miniGraph.tsx
@@ -91,6 +91,7 @@ class MiniGraph extends Component<Props> {
expired: eventView.expired,
name: eventView.name,
display,
+ dataset: eventView.dataset,
};
}
@@ -141,6 +142,7 @@ class MiniGraph extends Component<Props> {
expired,
name,
display,
+ dataset,
} = this.getRefreshProps(this.props);
return (
@@ -162,6 +164,7 @@ class MiniGraph extends Component<Props> {
expired={expired}
name={name}
referrer={referrer}
+ dataset={dataset}
hideError
partial
>
diff --git a/static/app/views/discover/queryList.spec.tsx b/static/app/views/discover/queryList.spec.tsx
index 2daed4f0f57e0e..362da83f76e620 100644
--- a/static/app/views/discover/queryList.spec.tsx
+++ b/static/app/views/discover/queryList.spec.tsx
@@ -121,6 +121,65 @@ describe('Discover > QueryList', function () {
await waitFor(() => {
expect(screen.getAllByTestId(/card-.*/)).toHaveLength(5);
});
+
+ expect(eventsStatsMock).toHaveBeenCalledWith(
+ '/organizations/org-slug/events-stats/',
+ expect.objectContaining({
+ query: {
+ environment: [],
+ interval: '30m',
+ partial: '1',
+ project: [],
+ query: '',
+ referrer: 'api.discover.default-chart',
+ statsPeriod: '14d',
+ yAxis: ['count()'],
+ },
+ })
+ );
+ });
+
+ it('passes dataset to the query if flag is enabled', async function () {
+ const org = OrganizationFixture({
+ features: [
+ 'discover-basic',
+ 'discover-query',
+ 'performance-discover-dataset-selector',
+ ],
+ });
+ render(
+ <QueryList
+ savedQuerySearchQuery=""
+ router={RouterFixture()}
+ organization={org}
+ savedQueries={savedQueries}
+ renderPrebuilt
+ pageLinks=""
+ onQueryChange={queryChangeMock}
+ location={location}
+ />
+ );
+
+ await waitFor(() => {
+ expect(screen.getAllByTestId(/card-.*/)).toHaveLength(5);
+ });
+
+ expect(eventsStatsMock).toHaveBeenCalledWith(
+ '/organizations/org-slug/events-stats/',
+ expect.objectContaining({
+ query: {
+ environment: [],
+ interval: '30m',
+ partial: '1',
+ project: [],
+ query: '',
+ referrer: 'api.discover.default-chart',
+ statsPeriod: '14d',
+ yAxis: ['count()'],
+ dataset: 'transactions',
+ },
+ })
+ );
});
it('can duplicate and trigger change callback', async function () {
diff --git a/static/app/views/discover/queryList.tsx b/static/app/views/discover/queryList.tsx
index 88526ea65af1a7..e7589bfc6c1ed6 100644
--- a/static/app/views/discover/queryList.tsx
+++ b/static/app/views/discover/queryList.tsx
@@ -25,6 +25,7 @@ import {decodeList} from 'sentry/utils/queryString';
import withApi from 'sentry/utils/withApi';
import {
+ getSavedQueryWithDataset,
handleCreateQuery,
handleDeleteQuery,
handleUpdateHomepageQuery,
@@ -233,7 +234,12 @@ class QueryList extends Component<Props> {
return [];
}
- return savedQueries.map((savedQuery, index) => {
+ return savedQueries.map((query, index) => {
+ const savedQuery = organization.features.includes(
+ 'performance-discover-dataset-selector'
+ )
+ ? (getSavedQueryWithDataset(query) as SavedQuery)
+ : query;
const eventView = EventView.fromSavedQuery(savedQuery);
const recentTimeline = t('Last ') + eventView.statsPeriod;
const customTimeline =
diff --git a/tests/js/fixtures/discover.ts b/tests/js/fixtures/discover.ts
index 1e695b7fc1036e..9481a08e6450db 100644
--- a/tests/js/fixtures/discover.ts
+++ b/tests/js/fixtures/discover.ts
@@ -1,4 +1,5 @@
import type {SavedQuery} from 'sentry/types/organization';
+import { SavedQueryDatasets } from 'sentry/utils/discover/types';
export function DiscoverSavedQueryFixture(params = {}): SavedQuery {
return {
@@ -8,6 +9,7 @@ export function DiscoverSavedQueryFixture(params = {}): SavedQuery {
dateUpdated: '2018-09-24T00:00:00.000Z',
fields: ['test'],
version: 2,
+ queryDataset: SavedQueryDatasets.TRANSACTIONS,
...params,
};
}
|
8f629548dc359defd5a447f758b01dd12a66ad6c
|
2021-03-02 01:29:06
|
Stephen Cefali
|
feat(sentry-demo): starts hiding elements in demo mode (#24114)
| false
|
starts hiding elements in demo mode (#24114)
|
feat
|
diff --git a/src/sentry/api/endpoints/prompts_activity.py b/src/sentry/api/endpoints/prompts_activity.py
index 20ef1298025321..b87cbbb38852a9 100644
--- a/src/sentry/api/endpoints/prompts_activity.py
+++ b/src/sentry/api/endpoints/prompts_activity.py
@@ -1,4 +1,5 @@
import calendar
+from django.conf import settings
from django.db import IntegrityError, transaction
from django.http import HttpResponse
from django.utils import timezone
@@ -32,6 +33,10 @@ class PromptsActivityEndpoint(Endpoint):
def get(self, request):
""" Return feature prompt status if dismissed or in snoozed period"""
+ # always return dismissed if we are in demo mode
+ if settings.DEMO_MODE:
+ return Response({"dismissed_ts": 1})
+
feature = request.GET.get("feature")
if not prompt_config.has(feature):
diff --git a/src/sentry/static/sentry/app/components/acl/demoModeGate.tsx b/src/sentry/static/sentry/app/components/acl/demoModeGate.tsx
new file mode 100644
index 00000000000000..9c58e24830701d
--- /dev/null
+++ b/src/sentry/static/sentry/app/components/acl/demoModeGate.tsx
@@ -0,0 +1,38 @@
+import React from 'react';
+
+import ConfigStore from 'app/stores/configStore';
+import {Organization} from 'app/types';
+import withOrganization from 'app/utils/withOrganization';
+
+type Props = {
+ /**
+ * Current Organization
+ */
+ organization: Organization;
+
+ /**
+ * Children can be a node or a function as child.
+ */
+ children?: React.ReactNode;
+
+ demoComponent?:
+ | React.ReactNode
+ | ((props: {children?: React.ReactNode}) => React.ReactNode);
+};
+
+/**
+ * Component to handle demo mode switches
+ */
+function DemoModeGate(props: Props) {
+ const {organization, children, demoComponent = null} = props;
+
+ if (organization?.role === 'member' && ConfigStore.get('demoMode')) {
+ if (typeof demoComponent === 'function') {
+ return demoComponent({children});
+ }
+ return demoComponent;
+ }
+ return children;
+}
+
+export default withOrganization(DemoModeGate);
diff --git a/src/sentry/static/sentry/app/components/sidebar/broadcasts.tsx b/src/sentry/static/sentry/app/components/sidebar/broadcasts.tsx
index 7676dd4540bb2b..d766bfd31b3328 100644
--- a/src/sentry/static/sentry/app/components/sidebar/broadcasts.tsx
+++ b/src/sentry/static/sentry/app/components/sidebar/broadcasts.tsx
@@ -2,6 +2,7 @@ import React from 'react';
import {getAllBroadcasts, markBroadcastsAsSeen} from 'app/actionCreators/broadcasts';
import {Client} from 'app/api';
+import DemoModeGate from 'app/components/acl/demoModeGate';
import LoadingIndicator from 'app/components/loadingIndicator';
import BroadcastSdkUpdates from 'app/components/sidebar/broadcastSdkUpdates';
import SidebarItem from 'app/components/sidebar/sidebarItem';
@@ -121,49 +122,51 @@ class Broadcasts extends React.Component<Props, State> {
const unseenPosts = this.unseenIds;
return (
- <React.Fragment>
- <SidebarItem
- data-test-id="sidebar-broadcasts"
- orientation={orientation}
- collapsed={collapsed}
- active={currentPanel === SidebarPanelKey.Broadcasts}
- badge={unseenPosts.length}
- icon={<IconBroadcast size="md" />}
- label={t("What's new")}
- onClick={this.handleShowPanel}
- id="broadcasts"
- />
-
- {currentPanel === SidebarPanelKey.Broadcasts && (
- <SidebarPanel
- data-test-id="sidebar-broadcasts-panel"
+ <DemoModeGate>
+ <React.Fragment>
+ <SidebarItem
+ data-test-id="sidebar-broadcasts"
orientation={orientation}
collapsed={collapsed}
- title={t("What's new in Sentry")}
- hidePanel={hidePanel}
- >
- <BroadcastSdkUpdates />
- {loading ? (
- <LoadingIndicator />
- ) : broadcasts.length === 0 ? (
- <SidebarPanelEmpty>
- {t('No recent updates from the Sentry team.')}
- </SidebarPanelEmpty>
- ) : (
- broadcasts.map(item => (
- <SidebarPanelItem
- key={item.id}
- hasSeen={item.hasSeen}
- title={item.title}
- message={item.message}
- link={item.link}
- cta={item.cta}
- />
- ))
- )}
- </SidebarPanel>
- )}
- </React.Fragment>
+ active={currentPanel === SidebarPanelKey.Broadcasts}
+ badge={unseenPosts.length}
+ icon={<IconBroadcast size="md" />}
+ label={t("What's new")}
+ onClick={this.handleShowPanel}
+ id="broadcasts"
+ />
+
+ {currentPanel === SidebarPanelKey.Broadcasts && (
+ <SidebarPanel
+ data-test-id="sidebar-broadcasts-panel"
+ orientation={orientation}
+ collapsed={collapsed}
+ title={t("What's new in Sentry")}
+ hidePanel={hidePanel}
+ >
+ <BroadcastSdkUpdates />
+ {loading ? (
+ <LoadingIndicator />
+ ) : broadcasts.length === 0 ? (
+ <SidebarPanelEmpty>
+ {t('No recent updates from the Sentry team.')}
+ </SidebarPanelEmpty>
+ ) : (
+ broadcasts.map(item => (
+ <SidebarPanelItem
+ key={item.id}
+ hasSeen={item.hasSeen}
+ title={item.title}
+ message={item.message}
+ link={item.link}
+ cta={item.cta}
+ />
+ ))
+ )}
+ </SidebarPanel>
+ )}
+ </React.Fragment>
+ </DemoModeGate>
);
}
}
diff --git a/src/sentry/static/sentry/app/components/sidebar/sidebarDropdown/index.tsx b/src/sentry/static/sentry/app/components/sidebar/sidebarDropdown/index.tsx
index 4e5d36e695687c..3eba5967277a86 100644
--- a/src/sentry/static/sentry/app/components/sidebar/sidebarDropdown/index.tsx
+++ b/src/sentry/static/sentry/app/components/sidebar/sidebarDropdown/index.tsx
@@ -3,6 +3,7 @@ import styled from '@emotion/styled';
import {logout} from 'app/actionCreators/account';
import {Client} from 'app/api';
+import DemoModeGate from 'app/components/acl/demoModeGate';
import Feature from 'app/components/acl/feature';
import Avatar from 'app/components/avatar';
import DropdownMenu from 'app/components/dropdownMenu';
@@ -116,38 +117,42 @@ const SidebarDropdown = ({api, org, orientation, collapsed, config, user}: Props
<SwitchOrganization canCreateOrganization={canCreateOrg} />
</SidebarMenuItem>
)}
-
- <Divider />
</React.Fragment>
)}
- {!!user && (
- <React.Fragment>
- <UserSummary to="/settings/account/details/">
- <UserBadgeNoOverflow user={user} avatarSize={32} />
- </UserSummary>
-
- <div>
- <SidebarMenuItem to="/settings/account/">
- {t('User settings')}
- </SidebarMenuItem>
- <SidebarMenuItem to="/settings/account/api/">
- {t('API keys')}
- </SidebarMenuItem>
- <Feature features={['mobile-app']} organization={org}>
- <SidebarMenuItem to="/settings/account/api/mobile-app/">
- {t('Mobile app')}
+ <DemoModeGate>
+ {!!user && (
+ <React.Fragment>
+ <Divider />
+ <UserSummary to="/settings/account/details/">
+ <UserBadgeNoOverflow user={user} avatarSize={32} />
+ </UserSummary>
+
+ <div>
+ <SidebarMenuItem to="/settings/account/">
+ {t('User settings')}
</SidebarMenuItem>
- </Feature>
- {user.isSuperuser && (
- <SidebarMenuItem to="/manage/">{t('Admin')}</SidebarMenuItem>
- )}
- <SidebarMenuItem data-test-id="sidebarSignout" onClick={handleLogout}>
- {t('Sign out')}
- </SidebarMenuItem>
- </div>
- </React.Fragment>
- )}
+ <SidebarMenuItem to="/settings/account/api/">
+ {t('API keys')}
+ </SidebarMenuItem>
+ <Feature features={['mobile-app']} organization={org}>
+ <SidebarMenuItem to="/settings/account/api/mobile-app/">
+ {t('Mobile app')}
+ </SidebarMenuItem>
+ </Feature>
+ {user.isSuperuser && (
+ <SidebarMenuItem to="/manage/">{t('Admin')}</SidebarMenuItem>
+ )}
+ <SidebarMenuItem
+ data-test-id="sidebarSignout"
+ onClick={handleLogout}
+ >
+ {t('Sign out')}
+ </SidebarMenuItem>
+ </div>
+ </React.Fragment>
+ )}
+ </DemoModeGate>
</OrgAndUserMenu>
)}
</SidebarDropdownRoot>
diff --git a/src/sentry/static/sentry/app/types/index.tsx b/src/sentry/static/sentry/app/types/index.tsx
index 33aa72644747af..b8d3d287abe610 100644
--- a/src/sentry/static/sentry/app/types/index.tsx
+++ b/src/sentry/static/sentry/app/types/index.tsx
@@ -683,6 +683,7 @@ export interface Config {
distPrefix: string;
apmSampling: number;
dsn_requests: string;
+ demoMode: boolean;
}
export type EventOrGroupType =
diff --git a/src/sentry/static/sentry/app/views/settings/settingsIndex.tsx b/src/sentry/static/sentry/app/views/settings/settingsIndex.tsx
index a69cdfc8910163..14e98af625732a 100644
--- a/src/sentry/static/sentry/app/views/settings/settingsIndex.tsx
+++ b/src/sentry/static/sentry/app/views/settings/settingsIndex.tsx
@@ -6,6 +6,7 @@ import styled from '@emotion/styled';
import omit from 'lodash/omit';
import {fetchOrganizationDetails} from 'app/actionCreators/organizations';
+import DemoModeGate from 'app/components/acl/demoModeGate';
import OrganizationAvatar from 'app/components/avatar/organizationAvatar';
import UserAvatar from 'app/components/avatar/userAvatar';
import ExternalLink from 'app/components/links/externalLink';
@@ -82,35 +83,37 @@ class SettingsIndex extends React.Component<Props> {
<DocumentTitle title={organization ? `${organization.slug} Settings` : 'Settings'}>
<SettingsLayout {...this.props}>
<GridLayout>
- <GridPanel>
- <HomePanelHeader>
- <HomeLinkIcon to="/settings/account/">
- <AvatarContainer>
- <UserAvatar user={user} size={HOME_ICON_SIZE} />
- </AvatarContainer>
- {t('My Account')}
- </HomeLinkIcon>
- </HomePanelHeader>
-
- <HomePanelBody>
- <h3>{t('Quick links')}:</h3>
- <ul>
- <li>
- <HomeLink to="/settings/account/security/">
- {t('Change my password')}
- </HomeLink>
- </li>
- <li>
- <HomeLink to="/settings/account/notifications/">
- {t('Notification Preferences')}
- </HomeLink>
- </li>
- <li>
- <HomeLink to="/settings/account/">{t('Change my avatar')}</HomeLink>
- </li>
- </ul>
- </HomePanelBody>
- </GridPanel>
+ <DemoModeGate>
+ <GridPanel>
+ <HomePanelHeader>
+ <HomeLinkIcon to="/settings/account/">
+ <AvatarContainer>
+ <UserAvatar user={user} size={HOME_ICON_SIZE} />
+ </AvatarContainer>
+ {t('My Account')}
+ </HomeLinkIcon>
+ </HomePanelHeader>
+
+ <HomePanelBody>
+ <h3>{t('Quick links')}:</h3>
+ <ul>
+ <li>
+ <HomeLink to="/settings/account/security/">
+ {t('Change my password')}
+ </HomeLink>
+ </li>
+ <li>
+ <HomeLink to="/settings/account/notifications/">
+ {t('Notification Preferences')}
+ </HomeLink>
+ </li>
+ <li>
+ <HomeLink to="/settings/account/">{t('Change my avatar')}</HomeLink>
+ </li>
+ </ul>
+ </HomePanelBody>
+ </GridPanel>
+ </DemoModeGate>
{/* if admin */}
<GridPanel>
@@ -222,35 +225,37 @@ class SettingsIndex extends React.Component<Props> {
</HomePanelBody>
</GridPanel>
- <GridPanel>
- <HomePanelHeader>
- <HomeLinkIcon to={LINKS.API}>
- <HomeIcon>
- <IconLock size="lg" />
- </HomeIcon>
- {t('API Keys')}
- </HomeLinkIcon>
- </HomePanelHeader>
-
- <HomePanelBody>
- <h3>{t('Quick links')}:</h3>
- <ul>
- <li>
- <HomeLink to={LINKS.API}>{t('Auth Tokens')}</HomeLink>
- </li>
- <li>
- <HomeLink to={`${organizationSettingsUrl}developer-settings/`}>
- {t('Your Integrations')}
- </HomeLink>
- </li>
- <li>
- <ExternalHomeLink href={LINKS.DOCUMENTATION_API}>
- {t('Documentation')}
- </ExternalHomeLink>
- </li>
- </ul>
- </HomePanelBody>
- </GridPanel>
+ <DemoModeGate>
+ <GridPanel>
+ <HomePanelHeader>
+ <HomeLinkIcon to={LINKS.API}>
+ <HomeIcon>
+ <IconLock size="lg" />
+ </HomeIcon>
+ {t('API Keys')}
+ </HomeLinkIcon>
+ </HomePanelHeader>
+
+ <HomePanelBody>
+ <h3>{t('Quick links')}:</h3>
+ <ul>
+ <li>
+ <HomeLink to={LINKS.API}>{t('Auth Tokens')}</HomeLink>
+ </li>
+ <li>
+ <HomeLink to={`${organizationSettingsUrl}developer-settings/`}>
+ {t('Your Integrations')}
+ </HomeLink>
+ </li>
+ <li>
+ <ExternalHomeLink href={LINKS.DOCUMENTATION_API}>
+ {t('Documentation')}
+ </ExternalHomeLink>
+ </li>
+ </ul>
+ </HomePanelBody>
+ </GridPanel>
+ </DemoModeGate>
</GridLayout>
</SettingsLayout>
</DocumentTitle>
diff --git a/src/sentry/web/client_config.py b/src/sentry/web/client_config.py
index 103dc6b23cdc4b..e4bdb970e91711 100644
--- a/src/sentry/web/client_config.py
+++ b/src/sentry/web/client_config.py
@@ -177,6 +177,7 @@ def get_client_config(request=None):
else list("" if settings.ALLOWED_HOSTS == ["*"] else settings.ALLOWED_HOSTS)
),
},
+ "demoMode": settings.DEMO_MODE,
}
if user and user.is_authenticated():
context.update(
diff --git a/tests/sentry/api/endpoints/test_prompts_activity.py b/tests/sentry/api/endpoints/test_prompts_activity.py
index 67cd07402d4aec..b3d5ed6b9e7918 100644
--- a/tests/sentry/api/endpoints/test_prompts_activity.py
+++ b/tests/sentry/api/endpoints/test_prompts_activity.py
@@ -1,4 +1,5 @@
from django.core.urlresolvers import reverse
+from django.test.utils import override_settings
from sentry.testutils import APITestCase
@@ -20,6 +21,7 @@ def setUp(self):
)
self.path = reverse("sentry-api-0-prompts-activity")
+ @override_settings(DEMO_MODE=False)
def test_invalid_feature(self):
# Invalid feature prompt name
resp = self.client.put(
@@ -34,6 +36,7 @@ def test_invalid_feature(self):
assert resp.status_code == 400
+ @override_settings(DEMO_MODE=False)
def test_invalid_project(self):
# Invalid project id
data = {
@@ -56,6 +59,7 @@ def test_invalid_project(self):
)
assert resp.status_code == 400
+ @override_settings(DEMO_MODE=False)
def test_dismiss(self):
data = {
"organization_id": self.org.id,
@@ -81,6 +85,7 @@ def test_dismiss(self):
assert "data" in resp.data
assert "dismissed_ts" in resp.data["data"]
+ @override_settings(DEMO_MODE=False)
def test_snooze(self):
data = {
"organization_id": self.org.id,
|
482b5da5f61d26091cc98136ee8be84f05a281fc
|
2021-11-23 05:58:11
|
Leander Rodrigues
|
ref(sentryapps): Change API behavior for logo-upload prep (#30151)
| false
|
Change API behavior for logo-upload prep (#30151)
|
ref
|
diff --git a/src/sentry/api/endpoints/sentry_apps.py b/src/sentry/api/endpoints/sentry_apps.py
index 0c1dce891210ab..aacb495bad07ff 100644
--- a/src/sentry/api/endpoints/sentry_apps.py
+++ b/src/sentry/api/endpoints/sentry_apps.py
@@ -11,7 +11,7 @@
from sentry.auth.superuser import is_active_superuser
from sentry.constants import SentryAppStatus
from sentry.mediators.sentry_apps import Creator, InternalCreator
-from sentry.models import SentryApp, SentryAppAvatar
+from sentry.models import SentryApp
from sentry.utils import json
logger = logging.getLogger(__name__)
@@ -107,10 +107,6 @@ def post(self, request, organization):
# we generate and validate the slug here instead of the serializer since the slug never changes
return Response(e.detail, status=400)
- if features.has("organizations:sentry-app-logo-upload", sentry_app.owner):
- SentryAppAvatar.objects.create(sentry_app=sentry_app, color=True, avatar_type=0)
- SentryAppAvatar.objects.create(sentry_app=sentry_app, color=False, avatar_type=0)
-
return Response(serialize(sentry_app, access=request.access), status=201)
# log any errors with schema
diff --git a/src/sentry/api/serializers/models/sentry_app.py b/src/sentry/api/serializers/models/sentry_app.py
index fa824f16bb3e43..07f4905f39a57a 100644
--- a/src/sentry/api/serializers/models/sentry_app.py
+++ b/src/sentry/api/serializers/models/sentry_app.py
@@ -57,7 +57,7 @@ def serialize(self, obj, attrs, user, access):
{
"avatars": [
{
- "avatarType": img.avatar_type,
+ "avatarType": img.get_avatar_type_display(),
"avatarUuid": img.ident,
"color": img.color,
}
diff --git a/tests/sentry/api/endpoints/test_sentry_app_avatar.py b/tests/sentry/api/endpoints/test_sentry_app_avatar.py
index 3158bf8cfa5919..e05fc4da887820 100644
--- a/tests/sentry/api/endpoints/test_sentry_app_avatar.py
+++ b/tests/sentry/api/endpoints/test_sentry_app_avatar.py
@@ -13,19 +13,28 @@ def setUp(self):
self.endpoint = "sentry-api-0-sentry-app-avatar"
self.login_as(self.user)
+ def get_avatar(self, resp, is_color=True):
+ avatars = resp.data["avatars"]
+ for avatar in avatars:
+ if avatar.get("color") == is_color:
+ return avatar
+
class SentryAppAvatarTest(SentryAppAvatarTestBase):
def test_get(self):
with self.feature("organizations:sentry-app-logo-upload"):
response = self.get_success_response(self.unpublished_app.slug)
- assert response.data["avatars"][0]["avatarType"] == 0
- assert response.data["avatars"][0]["avatarUuid"] is not None
- assert response.data["avatars"][0]["color"] is True
+ color_avatar = self.get_avatar(response)
+ simple_avatar = self.get_avatar(response, False)
+
+ assert color_avatar["avatarType"] == "default"
+ assert color_avatar["avatarUuid"] is not None
+ assert color_avatar["color"] is True
- assert response.data["avatars"][1]["avatarType"] == 0
- assert response.data["avatars"][1]["avatarUuid"] is not None
- assert response.data["avatars"][1]["color"] is False
+ assert simple_avatar["avatarType"] == "default"
+ assert simple_avatar["avatarUuid"] is not None
+ assert simple_avatar["color"] is False
assert response.data["uuid"] == str(self.unpublished_app.uuid)
@@ -35,7 +44,7 @@ class SentryAppAvatarPutTest(SentryAppAvatarTestBase):
def test_upload(self):
with self.feature("organizations:sentry-app-logo-upload"):
data = {
- "color": 1,
+ "color": True,
"avatar_type": "upload",
"avatar_photo": b64encode(self.load_fixture("avatar.jpg")),
}
@@ -44,9 +53,10 @@ def test_upload(self):
avatar = SentryAppAvatar.objects.get(sentry_app=self.unpublished_app, color=True)
assert avatar.file_id
assert avatar.get_avatar_type_display() == "upload"
- assert resp.data["avatars"][1]["avatarType"] == 1
- assert resp.data["avatars"][1]["avatarUuid"] is not None
- assert resp.data["avatars"][1]["color"] is True
+ color_avatar = self.get_avatar(resp)
+ assert color_avatar["avatarType"] == "upload"
+ assert color_avatar["avatarUuid"] is not None
+ assert color_avatar["color"] is True
def test_upload_both(self):
with self.feature("organizations:sentry-app-logo-upload"):
@@ -71,15 +81,17 @@ def test_upload_both(self):
assert len(avatars) == 2
assert avatars[0].file_id
assert avatars[0].get_avatar_type_display() == "upload"
- assert resp.data["avatars"][0]["color"] is True
- assert resp.data["avatars"][0]["avatarType"] == 1
- assert resp.data["avatars"][0]["avatarUuid"] is not None
+ color_avatar = self.get_avatar(resp)
+ assert color_avatar["color"] is True
+ assert color_avatar["avatarType"] == "upload"
+ assert color_avatar["avatarUuid"] is not None
assert avatars[1].file_id
assert avatars[1].get_avatar_type_display() == "upload"
- assert resp.data["avatars"][1]["color"] is False
- assert resp.data["avatars"][1]["avatarType"] == 1
- assert resp.data["avatars"][1]["avatarUuid"] is not None
+ simple_avatar = self.get_avatar(resp, False)
+ assert simple_avatar["color"] is False
+ assert simple_avatar["avatarType"] == "upload"
+ assert simple_avatar["avatarUuid"] is not None
def test_revert_to_default(self):
"""Test that a user can go back to the default avatars after having uploaded one"""
@@ -114,13 +126,16 @@ def test_revert_to_default(self):
}
response = self.get_success_response(self.unpublished_app.slug, **data2)
- assert response.data["avatars"][0]["avatarType"] == 0
- assert response.data["avatars"][0]["avatarUuid"] is not None
- assert response.data["avatars"][0]["color"] is True
+ color_avatar = self.get_avatar(response)
+ simple_avatar = self.get_avatar(response, False)
+
+ assert color_avatar["avatarType"] == "default"
+ assert color_avatar["avatarUuid"] is not None
+ assert color_avatar["color"] is True
- assert response.data["avatars"][1]["avatarType"] == 0
- assert response.data["avatars"][1]["avatarUuid"] is not None
- assert response.data["avatars"][1]["color"] is False
+ assert simple_avatar["avatarType"] == "default"
+ assert simple_avatar["avatarUuid"] is not None
+ assert simple_avatar["color"] is False
def test_put_bad(self):
SentryAppAvatar.objects.create(sentry_app=self.unpublished_app)
|
3c79ea6ec487f140ee4c95220fd39529d9c6d559
|
2024-04-11 23:35:03
|
anthony sottile
|
ref: enable optional redundant-self mypy code (#68718)
| false
|
enable optional redundant-self mypy code (#68718)
|
ref
|
diff --git a/pyproject.toml b/pyproject.toml
index 255adebc0106a6..f0683c54a78504 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -64,7 +64,7 @@ warn_unreachable = true
warn_unused_configs = true
warn_unused_ignores = true
warn_redundant_casts = true
-enable_error_code = ["ignore-without-code"]
+enable_error_code = ["ignore-without-code", "redundant-self"]
[tool.django-stubs]
django_settings_module = "sentry.conf.server_mypy"
|
04a5b08556c01f851e95d8b8173cc39b918f58f8
|
2023-05-11 23:20:53
|
Richard Ortenberg
|
feat(crons): Backend for auto-creation of monitor alert rule (#48451)
| false
|
Backend for auto-creation of monitor alert rule (#48451)
|
feat
|
diff --git a/src/sentry/monitors/endpoints/organization_monitor_details.py b/src/sentry/monitors/endpoints/organization_monitor_details.py
index 0ad349fafbca73..0a4b9f2efecac9 100644
--- a/src/sentry/monitors/endpoints/organization_monitor_details.py
+++ b/src/sentry/monitors/endpoints/organization_monitor_details.py
@@ -20,7 +20,7 @@
from sentry.apidocs.parameters import GLOBAL_PARAMS, MONITOR_PARAMS
from sentry.apidocs.utils import inline_sentry_response_serializer
from sentry.constants import ObjectStatus
-from sentry.models import ScheduledDeletion
+from sentry.models import Rule, RuleActivity, RuleActivityType, RuleStatus, ScheduledDeletion
from sentry.monitors.models import Monitor, MonitorEnvironment, MonitorStatus
from sentry.monitors.serializers import MonitorSerializer, MonitorSerializerResponse
from sentry.monitors.validators import MonitorValidator
@@ -170,6 +170,16 @@ def delete(self, request: Request, organization, project, monitor) -> Response:
)
.first()
)
+ alert_rule_id = monitor_object.config.get("alert_rule_id")
+ if alert_rule_id:
+ rule = Rule.objects.filter(
+ project_id=monitor.project_id, id=alert_rule_id
+ ).first()
+ rule.update(status=RuleStatus.PENDING_DELETION)
+ RuleActivity.objects.create(
+ rule=rule, user_id=request.user.id, type=RuleActivityType.DELETED.value
+ )
+
if not monitor_object or not monitor_object.update(
status=ObjectStatus.PENDING_DELETION
):
diff --git a/src/sentry/monitors/endpoints/organization_monitors.py b/src/sentry/monitors/endpoints/organization_monitors.py
index 4b4ea2c5b4a0ac..8fdc3842acd4ce 100644
--- a/src/sentry/monitors/endpoints/organization_monitors.py
+++ b/src/sentry/monitors/endpoints/organization_monitors.py
@@ -9,6 +9,7 @@
from sentry.api.bases.organization import OrganizationEndpoint
from sentry.api.paginator import OffsetPaginator
from sentry.api.serializers import serialize
+from sentry.api.serializers.rest_framework.rule import RuleSerializer
from sentry.apidocs.constants import (
RESPONSE_BAD_REQUEST,
RESPONSE_FORBIDDEN,
@@ -18,7 +19,8 @@
from sentry.apidocs.parameters import GLOBAL_PARAMS
from sentry.apidocs.utils import inline_sentry_response_serializer
from sentry.db.models.query import in_iexact
-from sentry.models import Environment, Organization
+from sentry.mediators import project_rules
+from sentry.models import Environment, Organization, RuleActivity, RuleActivityType, RuleSource
from sentry.monitors.models import (
Monitor,
MonitorEnvironment,
@@ -27,7 +29,7 @@
MonitorType,
)
from sentry.monitors.serializers import MonitorSerializer, MonitorSerializerResponse
-from sentry.monitors.utils import signal_first_monitor_created
+from sentry.monitors.utils import get_alert_rule, signal_first_monitor_created
from sentry.monitors.validators import MonitorValidator
from sentry.search.utils import tokenize_query
@@ -219,4 +221,41 @@ def post(self, request: Request, organization) -> Response:
project = result["project"]
signal_first_monitor_created(project, request.user, False)
+ validated_alert_rule = result.get("alert_rule")
+ if validated_alert_rule:
+ alert_rule_data = get_alert_rule(project, request.user, monitor, validated_alert_rule)
+ serializer = RuleSerializer(
+ context={"project": project, "organization": project.organization},
+ data=alert_rule_data,
+ )
+
+ 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:
+ conditions.extend(data["filters"])
+
+ kwargs = {
+ "name": data["name"],
+ "environment": data.get("environment"),
+ "project": project,
+ "action_match": data["actionMatch"],
+ "filter_match": data.get("filterMatch"),
+ "conditions": conditions,
+ "actions": data.get("actions", []),
+ "frequency": data.get("frequency"),
+ "user_id": request.user.id,
+ }
+
+ rule = project_rules.Creator.run(request=request, **kwargs)
+ rule.update(source=RuleSource.CRON_MONITOR)
+ RuleActivity.objects.create(
+ rule=rule, user_id=request.user.id, type=RuleActivityType.CREATED.value
+ )
+
+ config = monitor.config
+ config["alert_rule_id"] = rule.id
+ monitor.update(config=config)
+
return self.respond(serialize(monitor, request.user), status=201)
diff --git a/src/sentry/monitors/utils.py b/src/sentry/monitors/utils.py
index df7719d2f37c2f..3518859549ba4e 100644
--- a/src/sentry/monitors/utils.py
+++ b/src/sentry/monitors/utils.py
@@ -1,3 +1,6 @@
+from django.utils import timezone
+
+from sentry.models import User
from sentry.models.project import Project
from sentry.signals import first_cron_checkin_received, first_cron_monitor_created
@@ -18,3 +21,64 @@ def signal_first_monitor_created(project: Project, user, from_upsert: bool):
first_cron_monitor_created.send_robust(
project=project, user=user, from_upsert=from_upsert, sender=Project
)
+
+
+def get_alert_rule(project: Project, user: User, monitor: Monitor, alert_rule: dict):
+ """
+ Gets a dict formatted alert rule to create alongside the monitor
+ :param project: Project object
+ :param user: User object that made the request
+ :param monitor: Monitor object being created
+ :param alert_rule: Dictionary of configurations for an associated Rule
+ :return: dict
+ """
+ alert_rule_data = {
+ "actionMatch": "any",
+ "actions": [],
+ "conditions": [
+ {
+ "id": "sentry.rules.conditions.first_seen_event.FirstSeenEventCondition",
+ "name": "A new issue is created",
+ },
+ {
+ "id": "sentry.rules.conditions.regression_event.RegressionEventCondition",
+ "name": "The issue changes state from resolved to unresolved",
+ },
+ ],
+ "createdBy": {
+ "email": user.email,
+ "id": user.id,
+ "name": user.email,
+ },
+ "dateCreated": timezone.now().strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
+ "environment": None,
+ "filterMatch": "all",
+ "filters": [
+ {
+ "id": "sentry.rules.filters.tagged_event.TaggedEventFilter",
+ "key": "monitor.slug",
+ "match": "eq",
+ "name": f"The event's tags match monitor.slug contains {monitor.slug}",
+ "value": monitor.slug,
+ }
+ ],
+ "frequency": 1440,
+ "name": f"{monitor.name} Monitor Alert (All environments) - All members",
+ "owner": None,
+ "projects": [project.slug],
+ "snooze": False,
+ }
+
+ for target in alert_rule.get("targets", []):
+ target_identifier = target["target_identifier"]
+ target_type = target["target_type"]
+
+ action = {
+ "id": "sentry.mail.actions.NotifyEmailAction",
+ "name": f"Send a notification to {target_type}",
+ "targetIdentifier": target_identifier,
+ "targetType": target_type,
+ }
+ alert_rule_data["actions"].append(action)
+
+ return alert_rule_data
diff --git a/src/sentry/monitors/validators.py b/src/sentry/monitors/validators.py
index 81d86e19d1a6ff..c2cc950ac54894 100644
--- a/src/sentry/monitors/validators.py
+++ b/src/sentry/monitors/validators.py
@@ -7,6 +7,7 @@
from rest_framework import serializers
from sentry.api.fields.empty_integer import EmptyIntegerField
+from sentry.api.serializers.rest_framework import CamelSnakeSerializer
from sentry.api.serializers.rest_framework.project import ProjectField
from sentry.monitors.models import CheckInStatus, Monitor, MonitorStatus, MonitorType, ScheduleType
@@ -41,6 +42,18 @@ def to_internal_value(self, data):
return data
+class MonitorAlertRuleTargetValidator(serializers.Serializer):
+ target_identifier = serializers.IntegerField(help_text="ID of target object")
+ target_type = serializers.CharField(help_text="One of [Member, Team]")
+
+
+class MonitorAlertRuleValidator(serializers.Serializer):
+ targets = MonitorAlertRuleTargetValidator(
+ many=True,
+ help_text="Array of dictionaries with information of the user or team to be notified",
+ )
+
+
class ConfigValidator(serializers.Serializer):
schedule_type = serializers.ChoiceField(
choices=list(zip(SCHEDULE_TYPES.keys(), SCHEDULE_TYPES.keys())),
@@ -152,7 +165,7 @@ def validate(self, attrs):
return attrs
-class MonitorValidator(serializers.Serializer):
+class MonitorValidator(CamelSnakeSerializer):
project = ProjectField(scope="project:read")
name = serializers.CharField()
slug = serializers.RegexField(
@@ -169,6 +182,7 @@ class MonitorValidator(serializers.Serializer):
)
type = serializers.ChoiceField(choices=list(zip(MONITOR_TYPES.keys(), MONITOR_TYPES.keys())))
config = ConfigValidator()
+ alert_rule = MonitorAlertRuleValidator(required=False)
def validate_status(self, value):
return MONITOR_STATUSES.get(value, value)
diff --git a/tests/sentry/monitors/endpoints/test_organization_monitor_details.py b/tests/sentry/monitors/endpoints/test_organization_monitor_details.py
index f257133e53bc3b..8091456ba9dddb 100644
--- a/tests/sentry/monitors/endpoints/test_organization_monitor_details.py
+++ b/tests/sentry/monitors/endpoints/test_organization_monitor_details.py
@@ -1,5 +1,6 @@
from sentry.constants import ObjectStatus
-from sentry.models import ScheduledDeletion
+from sentry.mediators.project_rules import Creator
+from sentry.models import Rule, RuleActivity, RuleActivityType, RuleStatus, ScheduledDeletion
from sentry.monitors.models import Monitor, MonitorEnvironment, ScheduleType
from sentry.testutils import MonitorTestCase
from sentry.testutils.silo import region_silo_test
@@ -398,3 +399,28 @@ def test_bad_environment(self):
status_code=404,
qs_params={"environment": "jungle"},
)
+
+ def test_simple_with_alert_rule(self):
+ monitor = self._create_monitor()
+ rule = Creator(
+ name="New Cool Rule",
+ owner=None,
+ project=self.project,
+ action_match="all",
+ filter_match="any",
+ conditions=[],
+ actions=[],
+ frequency=5,
+ ).call()
+ config = monitor.config
+ config["alert_rule_id"] = rule.id
+ monitor.config = config
+ monitor.save()
+
+ self.get_success_response(
+ self.organization.slug, monitor.slug, method="DELETE", status_code=202
+ )
+
+ rule = Rule.objects.get(project_id=monitor.project_id, id=monitor.config["alert_rule_id"])
+ assert rule.status == RuleStatus.PENDING_DELETION
+ assert RuleActivity.objects.filter(rule=rule, type=RuleActivityType.DELETED.value).exists()
diff --git a/tests/sentry/monitors/endpoints/test_organization_monitors.py b/tests/sentry/monitors/endpoints/test_organization_monitors.py
index b2ec9545dca2cf..38b0e9701cc65f 100644
--- a/tests/sentry/monitors/endpoints/test_organization_monitors.py
+++ b/tests/sentry/monitors/endpoints/test_organization_monitors.py
@@ -7,6 +7,7 @@
from django.test.utils import override_settings
from sentry.constants import ObjectStatus
+from sentry.models import Rule, RuleSource
from sentry.monitors.models import Monitor, MonitorStatus, MonitorType, ScheduleType
from sentry.testutils import MonitorTestCase
from sentry.testutils.silo import region_silo_test
@@ -226,3 +227,20 @@ def test_monitor_organization_limit(self):
"config": {"schedule_type": "crontab", "schedule": "@daily"},
}
self.get_error_response(self.organization.slug, status_code=403, **data)
+
+ @patch("sentry.analytics.record")
+ def test_simple_with_alert_rule(self, mock_record):
+ data = {
+ "project": self.project.slug,
+ "name": "My Monitor",
+ "type": "cron_job",
+ "config": {"schedule_type": "crontab", "schedule": "@daily"},
+ "alert_rule": {"targets": [{"targetIdentifier": self.user.id, "targetType": "Member"}]},
+ }
+ response = self.get_success_response(self.organization.slug, **data)
+
+ monitor = Monitor.objects.get(slug=response.data["slug"])
+ alert_rule_id = monitor.config.get("alert_rule_id")
+ assert Rule.objects.filter(
+ project_id=monitor.project_id, id=alert_rule_id, source=RuleSource.CRON_MONITOR
+ ).exists()
|
2bb360347b1c44a506c14e03380f4e5f1a21a70a
|
2018-04-10 03:42:04
|
Jess MacQueen
|
feat(api): Make accept project transfer endpoint accept organization (#7909)
| false
|
Make accept project transfer endpoint accept organization (#7909)
|
feat
|
diff --git a/src/sentry/api/endpoints/accept_project_transfer.py b/src/sentry/api/endpoints/accept_project_transfer.py
index 0dcd0a9c42c8c1..5e570621670c4e 100644
--- a/src/sentry/api/endpoints/accept_project_transfer.py
+++ b/src/sentry/api/endpoints/accept_project_transfer.py
@@ -88,29 +88,60 @@ def post(self, request):
transaction_id = data['transaction_id']
+ org_slug = request.DATA.get('organization')
team_id = request.DATA.get('team')
- if team_id is None:
- return Response({'detail': 'Choose a team to transfer the project to'}, status=400)
- try:
- team = Team.objects.get(
- id=team_id,
- )
- except Team.DoesNotExist:
- return Response({'detail': 'Invalid team'}, status=400)
+ if org_slug is not None and team_id is not None:
+ return Response({
+ 'detail': 'Choose either a team or an organization, not both'
+ }, status=400)
+
+ if org_slug is None and team_id is None:
+ return Response({
+ 'detail': 'Choose either a team or an organization to transfer the project to'
+ }, status=400)
+
+ if team_id:
+ try:
+ team = Team.objects.get(
+ id=team_id,
+ )
+ except Team.DoesNotExist:
+ return Response({'detail': 'Invalid team'}, status=400)
+
+ # check if user is an owner of the team's org
+ is_team_org_owner = OrganizationMember.objects.filter(
+ user__is_active=True,
+ user=request.user,
+ role=roles.get_top_dog().id,
+ organization_id=team.organization_id,
+ ).exists()
+
+ if not is_team_org_owner:
+ return Response({'detail': 'Invalid team'}, status=400)
- # check if user is an owner of the team's org
- is_team_org_owner = OrganizationMember.objects.filter(
- user__is_active=True,
- user=request.user,
- role=roles.get_top_dog().id,
- organization_id=team.organization_id,
- ).exists()
+ project.transfer_to(team=team)
+
+ if org_slug:
+ try:
+ organization = Organization.objects.get(
+ slug=org_slug,
+ )
+ except Organization.DoesNotExist:
+ return Response({'detail': 'Invalid organization'}, status=400)
+
+ # check if user is an owner of the organization
+ is_org_owner = OrganizationMember.objects.filter(
+ user__is_active=True,
+ user=request.user,
+ role=roles.get_top_dog().id,
+ organization_id=organization.id,
+ ).exists()
- if not is_team_org_owner:
- return Response({'detail': 'Invalid team'}, status=400)
+ if not is_org_owner:
+ return Response({'detail': 'Invalid organization'}, status=400)
- project.transfer_to(team)
+ project.transfer_to(organization=organization)
self.create_audit_entry(
request=request,
diff --git a/src/sentry/models/project.py b/src/sentry/models/project.py
index a7a729bf27d496..871504a827fa67 100644
--- a/src/sentry/models/project.py
+++ b/src/sentry/models/project.py
@@ -280,7 +280,12 @@ def is_user_subscribed_to_mail_alerts(self, user):
is_enabled = bool(is_enabled)
return is_enabled
- def transfer_to(self, team):
+ def transfer_to(self, team=None, organization=None):
+
+ # TODO(jess): remove this when new-teams is live for everyone
+ # only support passing team or org not both
+ assert not (team and organization)
+
# NOTE: this will only work properly if the new team is in a different
# org than the existing one, which is currently the only use case in
# production
@@ -294,7 +299,8 @@ def transfer_to(self, team):
Rule,
)
- organization = team.organization
+ if organization is None:
+ organization = team.organization
old_org_id = self.organization_id
org_changed = old_org_id != organization.id
@@ -354,7 +360,8 @@ def transfer_to(self, team):
)
# ensure this actually exists in case from team was null
- self.add_team(team)
+ if team is not None:
+ self.add_team(team)
def add_team(self, team):
try:
diff --git a/tests/sentry/api/endpoints/test_accept_project_transfer.py b/tests/sentry/api/endpoints/test_accept_project_transfer.py
index 3f1ad37679b132..146c7ede1ad086 100644
--- a/tests/sentry/api/endpoints/test_accept_project_transfer.py
+++ b/tests/sentry/api/endpoints/test_accept_project_transfer.py
@@ -76,7 +76,7 @@ def test_returns_org_options_with_signed_link(self):
assert self.from_organization.slug in org_slugs
assert self.to_organization.slug in org_slugs
- def test_transfers_project_to_correct_organization(self):
+ def test_transfers_project_to_correct_team(self):
self.login_as(self.owner)
url_data = sign(
actor_id=self.member.user_id,
@@ -120,3 +120,44 @@ def test_cannot_transfer_project_twice_from_same_org(self):
resp = self.client.post(self.path, data={'team': self.to_team.id, 'data': url_data})
resp = self.client.get(self.path + '?' + urlencode({'data': url_data}))
assert resp.status_code == 400
+
+ def test_transfers_project_to_correct_organization(self):
+ self.login_as(self.owner)
+ url_data = sign(
+ actor_id=self.member.user_id,
+ from_organization_id=self.from_organization.id,
+ project_id=self.project.id,
+ user_id=self.owner.id,
+ transaction_id=self.transaction_id,
+ )
+
+ resp = self.client.post(
+ self.path,
+ data={'organization': self.to_organization.slug, 'data': url_data}
+ )
+ assert resp.status_code == 204
+ p = Project.objects.get(id=self.project.id)
+ assert p.organization_id == self.to_organization.id
+
+ def test_errors_when_team_and_org_provided(self):
+ self.login_as(self.owner)
+ url_data = sign(
+ actor_id=self.member.user_id,
+ from_organization_id=self.from_organization.id,
+ project_id=self.project.id,
+ user_id=self.owner.id,
+ transaction_id=self.transaction_id,
+ )
+
+ resp = self.client.post(
+ self.path,
+ data={
+ 'organization': self.to_organization.slug,
+ 'team': self.to_team.id,
+ 'data': url_data,
+ },
+ )
+ assert resp.status_code == 400
+ assert resp.data == {'detail': 'Choose either a team or an organization, not both'}
+ p = Project.objects.get(id=self.project.id)
+ assert p.organization_id == self.from_organization.id
diff --git a/tests/sentry/models/test_project.py b/tests/sentry/models/test_project.py
index f43d3633fc710e..90a684a70d2f2f 100644
--- a/tests/sentry/models/test_project.py
+++ b/tests/sentry/models/test_project.py
@@ -35,7 +35,7 @@ def test_inactive_global_member(self):
assert list(project.member_set.all()) == []
- def test_transfer_to(self):
+ def test_transfer_to_team(self):
from_org = self.create_organization()
from_team = self.create_team(organization=from_org)
to_org = self.create_organization()
@@ -50,7 +50,7 @@ def test_transfer_to(self):
data={},
)
- project.transfer_to(to_team)
+ project.transfer_to(team=to_team)
project = Project.objects.get(id=project.id)
@@ -63,7 +63,7 @@ def test_transfer_to(self):
assert updated_rule.environment_id != rule.environment_id
assert updated_rule.environment_id == Environment.get_or_create(project, 'production').id
- def test_transfer_to_slug_collision(self):
+ def test_transfer_to_team_slug_collision(self):
from_org = self.create_organization()
from_team = self.create_team(organization=from_org)
project = self.create_project(teams=[from_team], slug='matt')
@@ -74,7 +74,7 @@ def test_transfer_to_slug_collision(self):
assert Project.objects.filter(organization=to_org).count() == 1
- project.transfer_to(to_team)
+ project.transfer_to(team=to_team)
project = Project.objects.get(id=project.id)
@@ -85,7 +85,7 @@ def test_transfer_to_slug_collision(self):
assert Project.objects.filter(organization=to_org).count() == 2
assert Project.objects.filter(organization=from_org).count() == 0
- def test_transfer_to_releases(self):
+ def test_transfer_to_team_releases(self):
from_org = self.create_organization()
from_team = self.create_team(organization=from_org)
to_org = self.create_organization()
@@ -112,7 +112,7 @@ def test_transfer_to_releases(self):
release=release,
).exists()
- project.transfer_to(to_team)
+ project.transfer_to(team=to_team)
project = Project.objects.get(id=project.id)
@@ -129,3 +129,92 @@ def test_transfer_to_releases(self):
project=project,
release=release,
).exists()
+
+ def test_transfer_to_organization(self):
+ from_org = self.create_organization()
+ team = self.create_team(organization=from_org)
+ to_org = self.create_organization()
+
+ project = self.create_project(teams=[team])
+
+ rule = Rule.objects.create(
+ project=project,
+ environment_id=Environment.get_or_create(project, 'production').id,
+ label='Golden Rule',
+ data={},
+ )
+
+ project.transfer_to(organization=to_org)
+
+ project = Project.objects.get(id=project.id)
+
+ assert project.teams.count() == 0
+ assert project.organization_id == to_org.id
+
+ updated_rule = project.rule_set.get(label='Golden Rule')
+ assert updated_rule.id == rule.id
+ assert updated_rule.environment_id != rule.environment_id
+ assert updated_rule.environment_id == Environment.get_or_create(project, 'production').id
+
+ def test_transfer_to_organization_slug_collision(self):
+ from_org = self.create_organization()
+ team = self.create_team(organization=from_org)
+ project = self.create_project(teams=[team], slug='matt')
+ to_org = self.create_organization()
+ # conflicting project slug
+ self.create_project(slug='matt', organization=to_org)
+
+ assert Project.objects.filter(organization=to_org).count() == 1
+
+ project.transfer_to(organization=to_org)
+
+ project = Project.objects.get(id=project.id)
+
+ assert project.teams.count() == 0
+ assert project.organization_id == to_org.id
+ assert project.slug != 'matt'
+ assert Project.objects.filter(organization=to_org).count() == 2
+ assert Project.objects.filter(organization=from_org).count() == 0
+
+ def test_transfer_to_organization_releases(self):
+ from_org = self.create_organization()
+ team = self.create_team(organization=from_org)
+ to_org = self.create_organization()
+
+ project = self.create_project(teams=[team])
+
+ environment = Environment.get_or_create(project, 'production')
+ release = Release.get_or_create(project=project, version='1.0')
+
+ ReleaseProjectEnvironment.objects.create(
+ project=project,
+ release=release,
+ environment=environment,
+ )
+
+ assert ReleaseProjectEnvironment.objects.filter(
+ project=project,
+ release=release,
+ environment=environment,
+ ).exists()
+ assert ReleaseProject.objects.filter(
+ project=project,
+ release=release,
+ ).exists()
+
+ project.transfer_to(organization=to_org)
+
+ project = Project.objects.get(id=project.id)
+
+ assert project.teams.count() == 0
+ assert project.organization_id == to_org.id
+
+ assert not ReleaseProjectEnvironment.objects.filter(
+ project=project,
+ release=release,
+ environment=environment,
+ ).exists()
+ assert not ReleaseProject.objects.filter(
+ project=project,
+ release=release,
+ ).exists()
|
ed29d77191a0f46cffe4decb18dc1d682e079b50
|
2024-01-22 22:36:48
|
Julia Hoge
|
fix(discord): Fix 400 error from bad user id request (#63362)
| false
|
Fix 400 error from bad user id request (#63362)
|
fix
|
diff --git a/src/sentry/integrations/discord/integration.py b/src/sentry/integrations/discord/integration.py
index 6df907a5984fbb..1204c70fde8a02 100644
--- a/src/sentry/integrations/discord/integration.py
+++ b/src/sentry/integrations/discord/integration.py
@@ -172,7 +172,12 @@ def build_integration(self, state: Mapping[str, object]) -> Mapping[str, object]
else:
use_configure = False
url = self.configure_url if use_configure else self.setup_url
- discord_user_id = self._get_discord_user_id(str(state.get("code")), url)
+
+ auth_code = str(state.get("code"))
+ if auth_code:
+ discord_user_id = self._get_discord_user_id(auth_code, url)
+ else:
+ raise IntegrationError("Missing code from state.")
return {
"name": guild_name,
diff --git a/tests/sentry/integrations/discord/test_integration.py b/tests/sentry/integrations/discord/test_integration.py
index d8ce0204795495..91b4de4bf1adf2 100644
--- a/tests/sentry/integrations/discord/test_integration.py
+++ b/tests/sentry/integrations/discord/test_integration.py
@@ -259,6 +259,23 @@ def test_get_guild_name(self):
result = provider.build_integration({"guild_id": "guild_id", "code": user_id})
assert result["name"] == guild_name
+ @responses.activate
+ def test_build_integration_no_code_in_state(self):
+ provider = self.provider()
+ guild_id = "guild_id"
+ guild_name = "guild_name"
+ responses.add(
+ responses.GET,
+ url=f"{DiscordClient.base_url}{GUILD_URL.format(guild_id=guild_id)}",
+ match=[header_matcher({"Authorization": f"Bot {self.bot_token}"})],
+ json={
+ "id": guild_id,
+ "name": guild_name,
+ },
+ )
+ with pytest.raises(IntegrationError):
+ provider.build_integration({"guild_id": "guild_id", "code": ""})
+
@responses.activate
def test_get_guild_name_failure(self):
provider = self.provider()
|
d7b19d630c3826ccf36023745fbd7248a8cc58c3
|
2025-01-07 02:48:53
|
Scott Cooper
|
feat(settings): Convert team notifications to FC (#82894)
| false
|
Convert team notifications to FC (#82894)
|
feat
|
diff --git a/static/app/views/settings/organizationTeams/teamNotifications.spec.tsx b/static/app/views/settings/organizationTeams/teamNotifications.spec.tsx
index 04239b7a5ecf18..adf7b97c741a31 100644
--- a/static/app/views/settings/organizationTeams/teamNotifications.spec.tsx
+++ b/static/app/views/settings/organizationTeams/teamNotifications.spec.tsx
@@ -8,14 +8,16 @@ import {
userEvent,
} from 'sentry-test/reactTestingLibrary';
+import type {ExternalTeam} from 'sentry/types/integrations';
import TeamNotificationSettings from 'sentry/views/settings/organizationTeams/teamNotifications';
const EXTERNAL_NAME = 'marcos';
-const EXAMPLE_EXTERNAL_TEAM = {
+const EXAMPLE_EXTERNAL_TEAM: ExternalTeam = {
externalName: EXTERNAL_NAME,
id: '1',
integrationId: '1',
provider: 'slack',
+ teamId: '1',
};
const EXAMPLE_INTEGRATION = {
id: '1',
@@ -25,19 +27,22 @@ const EXAMPLE_INTEGRATION = {
};
describe('TeamNotificationSettings', () => {
- const {organization, router, routerProps} = initializeOrg();
- const team = TeamFixture();
+ const teamWithExternalTeam = TeamFixture({
+ externalTeams: [EXAMPLE_EXTERNAL_TEAM],
+ });
+ const teamWithoutExternalTeam = TeamFixture();
+ const {organization, router} = initializeOrg({
+ router: {params: {teamId: teamWithExternalTeam.slug}},
+ });
beforeEach(() => {
MockApiClient.clearMockResponses();
});
- it('should render empty message when there are no integrations', () => {
+ it('should render empty message when there are no integrations', async () => {
MockApiClient.addMockResponse({
- url: `/teams/${organization.slug}/${team.slug}/`,
- body: {
- externalTeams: [EXAMPLE_EXTERNAL_TEAM],
- },
+ url: `/teams/${organization.slug}/${teamWithExternalTeam.slug}/`,
+ body: teamWithExternalTeam,
});
MockApiClient.addMockResponse({
@@ -45,27 +50,17 @@ describe('TeamNotificationSettings', () => {
body: [],
});
- render(
- <TeamNotificationSettings
- {...routerProps}
- team={team}
- params={{teamId: team.id}}
- organization={organization}
- />,
- {router}
- );
+ render(<TeamNotificationSettings />, {router, organization});
expect(
- screen.getByText('No Notification Integrations have been installed yet.')
+ await screen.findByText('No Notification Integrations have been installed yet.')
).toBeInTheDocument();
});
- it('should render empty message when there are no externalTeams', () => {
+ it('should render empty message when there are no externalTeams', async () => {
MockApiClient.addMockResponse({
- url: `/teams/${organization.slug}/${team.slug}/`,
- body: {
- externalTeams: [],
- },
+ url: `/teams/${organization.slug}/${teamWithExternalTeam.slug}/`,
+ body: teamWithoutExternalTeam,
});
MockApiClient.addMockResponse({
@@ -73,27 +68,15 @@ describe('TeamNotificationSettings', () => {
body: [EXAMPLE_INTEGRATION],
});
- render(
- <TeamNotificationSettings
- {...routerProps}
- team={team}
- params={{teamId: team.id}}
- organization={organization}
- />,
- {
- router,
- }
- );
-
- expect(screen.getByText('No teams have been linked yet.')).toBeInTheDocument();
+ render(<TeamNotificationSettings />, {router, organization});
+
+ expect(await screen.findByText('No teams have been linked yet.')).toBeInTheDocument();
});
- it('should render each externalTeam', () => {
+ it('should render each externalTeam', async () => {
MockApiClient.addMockResponse({
- url: `/teams/${organization.slug}/${team.slug}/`,
- body: {
- externalTeams: [EXAMPLE_EXTERNAL_TEAM],
- },
+ url: `/teams/${organization.slug}/${teamWithExternalTeam.slug}/`,
+ body: teamWithExternalTeam,
});
MockApiClient.addMockResponse({
@@ -101,33 +84,21 @@ describe('TeamNotificationSettings', () => {
body: [EXAMPLE_INTEGRATION],
});
- render(
- <TeamNotificationSettings
- {...routerProps}
- team={team}
- params={{teamId: team.id}}
- organization={organization}
- />,
- {
- router,
- }
- );
-
- const input = screen.getByRole('textbox', {
+ render(<TeamNotificationSettings />, {router, organization});
+
+ const input = await screen.findByRole('textbox', {
name: 'Unlink this channel in slack with `/slack unlink team`',
});
expect(input).toBeDisabled();
expect(input).toHaveValue(EXTERNAL_NAME);
- expect(screen.getByRole('button', {name: 'delete'})).toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'Unlink'})).toBeInTheDocument();
});
it('should delete be able to delete the externalTeam', async () => {
MockApiClient.addMockResponse({
- url: `/teams/${organization.slug}/${team.slug}/`,
- body: {
- externalTeams: [EXAMPLE_EXTERNAL_TEAM],
- },
+ url: `/teams/${organization.slug}/${teamWithExternalTeam.slug}/`,
+ body: teamWithExternalTeam,
});
MockApiClient.addMockResponse({
@@ -136,24 +107,14 @@ describe('TeamNotificationSettings', () => {
});
const deleteMock = MockApiClient.addMockResponse({
- url: `/teams/${organization.slug}/${team.slug}/external-teams/${EXAMPLE_EXTERNAL_TEAM.id}/`,
+ url: `/teams/${organization.slug}/${teamWithExternalTeam.slug}/external-teams/${EXAMPLE_EXTERNAL_TEAM.id}/`,
status: 204,
method: 'DELETE',
});
- render(
- <TeamNotificationSettings
- {...routerProps}
- team={team}
- params={{teamId: team.id}}
- organization={organization}
- />,
- {
- router,
- }
- );
-
- await userEvent.click(screen.getByRole('button', {name: 'delete'}));
+ render(<TeamNotificationSettings />, {router, organization});
+
+ await userEvent.click(await screen.findByRole('button', {name: 'Unlink'}));
renderGlobalModal();
await userEvent.click(screen.getByTestId('confirm-button'));
diff --git a/static/app/views/settings/organizationTeams/teamNotifications.tsx b/static/app/views/settings/organizationTeams/teamNotifications.tsx
index 8db75569c90475..a5541d7f423925 100644
--- a/static/app/views/settings/organizationTeams/teamNotifications.tsx
+++ b/static/app/views/settings/organizationTeams/teamNotifications.tsx
@@ -5,10 +5,11 @@ import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicato
import {hasEveryAccess} from 'sentry/components/acl/access';
import {Button} from 'sentry/components/button';
import Confirm from 'sentry/components/confirm';
-import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
import EmptyMessage from 'sentry/components/emptyMessage';
import TextField from 'sentry/components/forms/fields/textField';
import ExternalLink from 'sentry/components/links/externalLink';
+import LoadingError from 'sentry/components/loadingError';
+import LoadingIndicator from 'sentry/components/loadingIndicator';
import Panel from 'sentry/components/panels/panel';
import PanelBody from 'sentry/components/panels/panelBody';
import PanelHeader from 'sentry/components/panels/panelHeader';
@@ -18,160 +19,201 @@ import {IconDelete} from 'sentry/icons';
import {t, tct} from 'sentry/locale';
import {space} from 'sentry/styles/space';
import type {ExternalTeam, Integration} from 'sentry/types/integrations';
-import type {RouteComponentProps} from 'sentry/types/legacyReactRouter';
-import type {Organization, Team} from 'sentry/types/organization';
+import type {Team} from 'sentry/types/organization';
+import {useApiQuery} from 'sentry/utils/queryClient';
import {toTitleCase} from 'sentry/utils/string/toTitleCase';
-import withOrganization from 'sentry/utils/withOrganization';
+import useApi from 'sentry/utils/useApi';
+import useOrganization from 'sentry/utils/useOrganization';
+import {useParams} from 'sentry/utils/useParams';
import PermissionAlert from 'sentry/views/settings/project/permissionAlert';
-type Props = RouteComponentProps<{teamId: string}, {}> & {
- organization: Organization;
- team: Team;
-};
-
-type State = DeprecatedAsyncComponent['state'] & {
- integrations: Integration[];
- teamDetails: Team;
-};
-
const DOCS_LINK =
'https://docs.sentry.io/product/integrations/notification-incidents/slack/#team-notifications';
const NOTIFICATION_PROVIDERS = ['slack'];
-class TeamNotificationSettings extends DeprecatedAsyncComponent<Props, State> {
- getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
- const {organization, team} = this.props;
- return [
- [
- 'teamDetails',
- `/teams/${organization.slug}/${team.slug}/`,
- {query: {expand: ['externalTeams']}},
- ],
- [
- 'integrations',
- `/organizations/${organization.slug}/integrations/`,
- {query: {includeConfig: 0}},
- ],
- ];
+function TeamNotificationSettingsPanel({
+ team,
+ integrations,
+ onDelete,
+}: {
+ integrations: Integration[];
+ onDelete: (externalTeam: ExternalTeam) => void;
+ team: Team;
+}) {
+ const organization = useOrganization();
+
+ const notificationIntegrations = integrations.filter(integration =>
+ NOTIFICATION_PROVIDERS.includes(integration.provider.key)
+ );
+ if (!notificationIntegrations.length) {
+ return (
+ <EmptyMessage>
+ {t('No Notification Integrations have been installed yet.')}
+ </EmptyMessage>
+ );
}
- handleDelete = async (mapping: ExternalTeam) => {
- try {
- const {organization, team} = this.props;
- const endpoint = `/teams/${organization.slug}/${team.slug}/external-teams/${mapping.id}/`;
- await this.api.requestPromise(endpoint, {
- method: 'DELETE',
- });
- addSuccessMessage(t('Deletion successful'));
- this.fetchData();
- } catch {
- addErrorMessage(t('An error occurred'));
- }
- };
+ const externalTeams = (team.externalTeams ?? []).filter(externalTeam =>
+ NOTIFICATION_PROVIDERS.includes(externalTeam.provider)
+ );
- renderBody() {
- const {team} = this.props;
+ if (!externalTeams.length) {
return (
- <Fragment>
- <SentryDocumentTitle title={t('Team Notification Settings')} />
- <PermissionAlert access={['team:write']} team={team} />
-
- <Panel>
- <PanelHeader>{t('Notifications')}</PanelHeader>
- <PanelBody>{this.renderPanelBody()}</PanelBody>
- </Panel>
- </Fragment>
+ <EmptyMessage>
+ <div>{t('No teams have been linked yet.')}</div>
+ <NotDisabledSubText>
+ {tct('Head over to Slack and type [code] to get started. [link].', {
+ code: <code>/sentry link team</code>,
+ link: <ExternalLink href={DOCS_LINK}>{t('Learn more')}</ExternalLink>,
+ })}
+ </NotDisabledSubText>
+ </EmptyMessage>
);
}
- renderPanelBody() {
- const {organization, team} = this.props;
- const {teamDetails, integrations} = this.state;
+ const integrationsById = Object.fromEntries(
+ notificationIntegrations.map(integration => [integration.id, integration])
+ );
+
+ const hasWriteAccess = hasEveryAccess(['team:write'], {organization, team});
+
+ return externalTeams.map(externalTeam => (
+ <FormFieldWrapper key={externalTeam.id}>
+ <StyledFormField
+ disabled
+ label={
+ <div>
+ <NotDisabledText>
+ {toTitleCase(externalTeam.provider)}:
+ {integrationsById[externalTeam.integrationId]!.name}
+ </NotDisabledText>
+ <NotDisabledSubText>
+ {tct('Unlink this channel in Slack with [code]. [link].', {
+ code: <code>/sentry unlink team</code>,
+ link: <ExternalLink href={DOCS_LINK}>{t('Learn more')}</ExternalLink>,
+ })}
+ </NotDisabledSubText>
+ </div>
+ }
+ labelText={t('Unlink this channel in slack with `/slack unlink team`')}
+ name="externalName"
+ value={externalTeam.externalName}
+ />
+
+ <DeleteButtonWrapper>
+ <Tooltip
+ title={t(
+ 'You must be an organization owner, manager or admin to remove a Slack team link'
+ )}
+ disabled={hasWriteAccess}
+ >
+ <Confirm
+ disabled={!hasWriteAccess}
+ onConfirm={() => onDelete(externalTeam)}
+ message={t('Are you sure you want to remove this Slack team link?')}
+ >
+ <Button icon={<IconDelete />} disabled={!hasWriteAccess}>
+ {t('Unlink')}
+ </Button>
+ </Confirm>
+ </Tooltip>
+ </DeleteButtonWrapper>
+ </FormFieldWrapper>
+ ));
+}
- const notificationIntegrations = integrations.filter(integration =>
- NOTIFICATION_PROVIDERS.includes(integration.provider.key)
- );
- if (!notificationIntegrations.length) {
- return (
- <EmptyMessage>
- {t('No Notification Integrations have been installed yet.')}
- </EmptyMessage>
- );
+function TeamNotificationSettings() {
+ const api = useApi();
+ const params = useParams<{teamId: string}>();
+ const organization = useOrganization();
+
+ const {
+ data: team,
+ isPending: isTeamPending,
+ isError: isTeamError,
+ refetch: refetchTeam,
+ } = useApiQuery<Team>(
+ [
+ `/teams/${organization.slug}/${params.teamId}/`,
+ {
+ query: {expand: ['externalTeams']},
+ },
+ ],
+ {
+ staleTime: 0,
}
+ );
+
+ const {
+ data: integrations,
+ isPending: isIntegrationsPending,
+ isError: isIntegrationsError,
+ refetch: refetchIntegrations,
+ } = useApiQuery<Integration[]>(
+ [
+ `/organizations/${organization.slug}/integrations/`,
+ {
+ query: {includeConfig: '0'},
+ },
+ ],
+ {
+ staleTime: 0,
+ }
+ );
+
+ if (isTeamPending || isIntegrationsPending) {
+ return <LoadingIndicator />;
+ }
- const externalTeams = (teamDetails.externalTeams || []).filter(externalTeam =>
- NOTIFICATION_PROVIDERS.includes(externalTeam.provider)
+ if (isTeamError || isIntegrationsError) {
+ return (
+ <LoadingError
+ onRetry={() => {
+ refetchTeam();
+ refetchIntegrations();
+ }}
+ />
);
+ }
- if (!externalTeams.length) {
- return (
- <EmptyMessage>
- <div>{t('No teams have been linked yet.')}</div>
- <NotDisabledSubText>
- {tct('Head over to Slack and type [code] to get started. [link].', {
- code: <code>/sentry link team</code>,
- link: <ExternalLink href={DOCS_LINK}>{t('Learn more')}</ExternalLink>,
- })}
- </NotDisabledSubText>
- </EmptyMessage>
+ const handleDelete = async (externalTeam: ExternalTeam) => {
+ try {
+ await api.requestPromise(
+ `/teams/${organization.slug}/${team.slug}/external-teams/${externalTeam.id}/`,
+ {
+ method: 'DELETE',
+ }
);
+ addSuccessMessage(t('Deletion successful'));
+ } catch {
+ addErrorMessage(t('An error occurred'));
}
- const integrationsById = Object.fromEntries(
- notificationIntegrations.map(integration => [integration.id, integration])
- );
+ refetchTeam();
+ refetchIntegrations();
+ };
- const hasWriteAccess = hasEveryAccess(['team:write'], {organization, team});
-
- return externalTeams.map(externalTeam => (
- <FormFieldWrapper key={externalTeam.id}>
- <StyledFormField
- disabled
- label={
- <div>
- <NotDisabledText>
- {toTitleCase(externalTeam.provider)}:
- {integrationsById[externalTeam.integrationId]!.name}
- </NotDisabledText>
- <NotDisabledSubText>
- {tct('Unlink this channel in Slack with [code]. [link].', {
- code: <code>/sentry unlink team</code>,
- link: <ExternalLink href={DOCS_LINK}>{t('Learn more')}</ExternalLink>,
- })}
- </NotDisabledSubText>
- </div>
- }
- labelText={t('Unlink this channel in slack with `/slack unlink team`')}
- name="externalName"
- value={externalTeam.externalName}
- />
-
- <DeleteButtonWrapper>
- <Tooltip
- title={t(
- 'You must be an organization owner, manager or admin to remove a Slack team link'
- )}
- disabled={hasWriteAccess}
- >
- <Confirm
- disabled={!hasWriteAccess}
- onConfirm={() => this.handleDelete(externalTeam)}
- message={t('Are you sure you want to remove this Slack team link?')}
- >
- <Button
- size="sm"
- icon={<IconDelete size="md" />}
- aria-label={t('delete')}
- disabled={!hasWriteAccess}
- />
- </Confirm>
- </Tooltip>
- </DeleteButtonWrapper>
- </FormFieldWrapper>
- ));
- }
+ return (
+ <Fragment>
+ <SentryDocumentTitle
+ title={t('%s Team Notification Settings', `#${params.teamId}`)}
+ />
+ <PermissionAlert access={['team:write']} team={team} />
+ <Panel>
+ <PanelHeader>{t('Notifications')}</PanelHeader>
+ <PanelBody>
+ <TeamNotificationSettingsPanel
+ team={team}
+ integrations={integrations}
+ onDelete={handleDelete}
+ />
+ </PanelBody>
+ </Panel>
+ </Fragment>
+ );
}
-export default withOrganization(TeamNotificationSettings);
+
+export default TeamNotificationSettings;
const NotDisabledText = styled('div')`
color: ${p => p.theme.textColor};
@@ -192,6 +234,5 @@ const StyledFormField = styled(TextField)`
flex: 1;
`;
const DeleteButtonWrapper = styled('div')`
- margin-right: ${space(4)};
- padding-right: ${space(0.5)};
+ margin-right: ${space(2)};
`;
|
325a0960fc7d1c173db9cd8185cef44c4196a03a
|
2024-02-15 23:51:32
|
Malachi Willey
|
feat(suggested-fix): New banner design (#65206)
| false
|
New banner design (#65206)
|
feat
|
diff --git a/static/app/components/events/aiAutofix/banner.spec.tsx b/static/app/components/events/aiAutofix/banner.spec.tsx
index 7473b8cdbe7358..44d6892c889942 100644
--- a/static/app/components/events/aiAutofix/banner.spec.tsx
+++ b/static/app/components/events/aiAutofix/banner.spec.tsx
@@ -23,7 +23,11 @@ describe('PII Certification Check', () => {
setAdditionalContext={() => {}}
/>
);
- expect(getByText('Certify No PII')).toBeInTheDocument();
+ expect(
+ getByText(
+ 'By clicking the button above, you confirm that there is no PII in this event.'
+ )
+ ).toBeInTheDocument();
});
it('does not show PII check for non sentry employee users', () => {
@@ -36,6 +40,10 @@ describe('PII Certification Check', () => {
setAdditionalContext={() => {}}
/>
);
- expect(queryByText('Certify No PII')).not.toBeInTheDocument();
+ expect(
+ queryByText(
+ 'By clicking the button above, you confirm that there is no PII in this event.'
+ )
+ ).not.toBeInTheDocument();
});
});
diff --git a/static/app/components/events/aiAutofix/banner.tsx b/static/app/components/events/aiAutofix/banner.tsx
index c938956b6777d5..3805e7a92f8c2d 100644
--- a/static/app/components/events/aiAutofix/banner.tsx
+++ b/static/app/components/events/aiAutofix/banner.tsx
@@ -1,4 +1,4 @@
-import {useState} from 'react';
+import {Fragment} from 'react';
import styled from '@emotion/styled';
import bannerBackground from 'sentry-images/spot/ai-suggestion-banner-background.svg';
@@ -6,20 +6,12 @@ import bannerSentaur from 'sentry-images/spot/ai-suggestion-banner-sentaur.svg';
import bannerStars from 'sentry-images/spot/ai-suggestion-banner-stars.svg';
import {Button} from 'sentry/components/button';
-import ButtonBar from 'sentry/components/buttonBar';
-import EmptyMessage from 'sentry/components/emptyMessage';
-import TextArea from 'sentry/components/forms/controls/textarea';
-import ExternalLink from 'sentry/components/links/externalLink';
+import Input from 'sentry/components/input';
import Panel from 'sentry/components/panels/panel';
import PanelBody from 'sentry/components/panels/panelBody';
-import QuestionTooltip from 'sentry/components/questionTooltip';
-import {IconFlag} from 'sentry/icons';
-import {t, tct} from 'sentry/locale';
+import {t} from 'sentry/locale';
import {space} from 'sentry/styles/space';
import {useIsSentryEmployee} from 'sentry/utils/useIsSentryEmployee';
-import TextBlock from 'sentry/views/settings/components/text/textBlock';
-
-import {ExperimentalFeatureBadge} from '../aiSuggestedSolution/experimentalFeatureBadge';
type Props = {
additionalContext: string;
@@ -29,78 +21,45 @@ type Props = {
export function Banner({onButtonClick, additionalContext, setAdditionalContext}: Props) {
const isSentryEmployee = useIsSentryEmployee();
- const [piiCertified, setPiiCertified] = useState(false);
-
- const showPiiMessage = isSentryEmployee && !piiCertified;
return (
<Wrapper>
+ <IllustrationContainer>
+ <Background src={bannerBackground} />
+ <Stars src={bannerStars} />
+ <Sentaur src={bannerSentaur} />
+ </IllustrationContainer>
<Body>
- <Header>
- <TitleContent>
- <Title>
- {t('AI Autofix')}
- <MoreInfoTooltip
- isHoverable
- size="sm"
- title={tct(
- 'This is an OpenAI generated solution that automatically creates a pull request for this issue. Be aware that this may not be accurate. [learnMore:Learn more]',
- {
- learnMore: (
- <ExternalLink href="https://docs.sentry.io/product/issues/issue-details/ai-suggested-solution/" />
- ),
- }
- )}
- />
- <ExperimentalFeatureBadge />
- </Title>
- <Description>
- {t('You might get lucky, but again, maybe not\u2026')}
- </Description>
- </TitleContent>
- <Action>
- <Background src={bannerBackground} />
- <Stars src={bannerStars} />
- <Sentaur src={bannerSentaur} />
- <ViewSuggestionButton
- size="xs"
- onClick={onButtonClick}
- disabled={showPiiMessage}
- >
- {t('Try your luck')}
- </ViewSuggestionButton>
- </Action>
- </Header>
- {showPiiMessage ? (
- <PiiArea>
- <EmptyMessage
- icon={<IconFlag size="xl" />}
- title={t('PII Certification Required')}
- description={t(
- 'Before using this feature, please confirm that there is no personally identifiable information in this event.'
- )}
- action={
- <ButtonBar gap={2}>
- <Button priority="primary" onClick={() => setPiiCertified(true)}>
- {t('Certify No PII')}
- </Button>
- </ButtonBar>
+ <div>
+ <Title>{t('Try AI Autofix')}</Title>
+ <SubTitle>{t('You might get lucky, but then again, maybe not...')}</SubTitle>
+ </div>
+ <ContextArea>
+ <Button onClick={onButtonClick} size="sm">
+ {t('Gimme Fix')}
+ </Button>
+ <Input
+ aria-label={t('Provide additional context (optional)')}
+ value={additionalContext}
+ placeholder={t('Add context (optional)...')}
+ onChange={e => setAdditionalContext(e.target.value)}
+ onKeyDown={e => {
+ if (e.key === 'Enter') {
+ onButtonClick();
}
- />
- </PiiArea>
- ) : (
- <AdditionalContextArea>
- <AdditionalContextLabel>
- {t('Additional Context (Optional)')}
- </AdditionalContextLabel>
- <StyledTextArea
- value={additionalContext}
- placeholder={t(
- 'Add additional context to help the AI find a better solution'
+ }}
+ size="sm"
+ />
+ </ContextArea>
+ {isSentryEmployee && (
+ <Fragment>
+ <Separator />
+ <PiiMessage>
+ {t(
+ 'By clicking the button above, you confirm that there is no PII in this event.'
)}
- onChange={e => setAdditionalContext(e.target.value)}
- />
- </AdditionalContextArea>
+ </PiiMessage>
+ </Fragment>
)}
</Body>
</Wrapper>
@@ -109,133 +68,80 @@ export function Banner({onButtonClick, additionalContext, setAdditionalContext}:
const Wrapper = styled(Panel)`
margin-bottom: 0;
+ background: linear-gradient(269.35deg, ${p => p.theme.backgroundTertiary} 0.32%, rgba(245, 243, 247, 0) 99.69%);
`;
const Body = styled(PanelBody)`
- display: flex;
- flex-direction: column;
-`;
-
-const Header = styled('div')`
- display: flex;
- align-items: center;
- flex-wrap: wrap;
- gap: ${space(1)};
-
- > *:first-child {
- flex: 1;
- }
+ padding: ${space(2)} ${space(3)};
@media (min-width: ${p => p.theme.breakpoints.xlarge}) {
- display: grid;
- grid-template-columns: 42% 1fr;
- height: 80px;
- position: relative;
+ max-width: calc(100% - 400px);
}
`;
const Title = styled('div')`
- font-size: ${p => p.theme.fontSizeSmall};
- text-transform: uppercase;
- color: ${p => p.theme.gray300};
- display: flex;
- align-items: center;
- /* to be consistent with the feature badge size */
- height: ${space(2)};
- line-height: ${space(2)};
- white-space: nowrap;
-`;
-
-const TitleContent = styled('div')`
- display: flex;
- flex-direction: column;
- padding-left: ${space(2)};
+ font-size: ${p => p.theme.fontSizeExtraLarge};
+ font-weight: bold;
+ margin-bottom: ${space(1)};
`;
-const Description = styled(TextBlock)`
- margin: ${space(1)} 0 0 0;
+const SubTitle = styled('p')`
+ margin: ${space(1)} 0;
`;
-const Action = styled('div')`
- display: flex;
- justify-content: flex-end;
- align-items: center;
+const ContextArea = styled('div')`
+ display: grid;
+ gap: ${space(1)};
+ grid-template-columns: auto 1fr;
+ margin-top: ${space(1)};
`;
-const Sentaur = styled('img')`
+const IllustrationContainer = styled('div')`
display: none;
- @media (min-width: ${p => p.theme.breakpoints.xlarge}) {
- display: block;
- height: 8.563rem;
- position: absolute;
- bottom: 0;
- right: 6.608rem;
- object-fit: cover;
- z-index: 1;
- pointer-events: none;
- }
-`;
-const Background = styled('img')`
- display: none;
@media (min-width: ${p => p.theme.breakpoints.xlarge}) {
display: block;
position: absolute;
- top: 0;
+ bottom: 0;
right: 0;
- object-fit: cover;
- max-width: 100%;
- height: 100%;
- border-top-right-radius: ${p => p.theme.panelBorderRadius};
+ top: 0;
+ width: 400px;
+ overflow: hidden;
+ border-radius: 0 ${p => p.theme.borderRadius} ${p => p.theme.borderRadius} 0;
}
`;
-const Stars = styled('img')`
- display: none;
- @media (min-width: ${p => p.theme.breakpoints.xlarge}) {
- display: block;
- height: 8.563rem;
- position: absolute;
- right: -1rem;
- bottom: -0.125rem;
- object-fit: cover;
- /* workaround to remove a extra svg on the bottom right */
- border-radius: ${p => p.theme.panelBorderRadius};
- }
+const Sentaur = styled('img')`
+ height: 125px;
+ position: absolute;
+ bottom: 0;
+ right: 185px;
+ z-index: 1;
+ pointer-events: none;
`;
-const ViewSuggestionButton = styled(Button)`
- @media (min-width: ${p => p.theme.breakpoints.xlarge}) {
- position: absolute;
- right: 1rem;
- top: 1.5rem;
- }
+const Background = styled('img')`
+ position: absolute;
+ bottom: 0;
+ right: 0;
+ max-width: 100%;
`;
-const MoreInfoTooltip = styled(QuestionTooltip)`
- margin-left: ${space(0.5)};
+const Stars = styled('img')`
+ pointer-events: none;
+ position: absolute;
+ right: -140px;
+ bottom: 40px;
+ height: 120px;
`;
-const AdditionalContextLabel = styled('label')`
- font-size: ${p => p.theme.fontSizeSmall};
- color: ${p => p.theme.gray300};
+const Separator = styled('hr')`
+ margin-top: ${space(2)};
margin-bottom: ${space(1)};
+ border-color: ${p => p.theme.translucentBorder};
`;
-const PiiArea = styled('div')`
- background-color: ${p => p.theme.backgroundSecondary};
- border-radius: ${p => p.theme.panelBorderRadius};
-`;
-
-const AdditionalContextArea = styled('div')`
- display: flex;
- flex-direction: column;
- padding: ${space(2)};
- background-color: ${p => p.theme.backgroundSecondary};
- border-radius: ${p => p.theme.panelBorderRadius};
-`;
-
-const StyledTextArea = styled(TextArea)`
- resize: vertical;
- min-height: 80px;
+const PiiMessage = styled('p')`
+ font-size: ${p => p.theme.fontSizeSmall};
+ color: ${p => p.theme.subText};
`;
diff --git a/static/app/components/events/aiAutofix/index.spec.tsx b/static/app/components/events/aiAutofix/index.spec.tsx
index 8c2ea0601c42d1..6167b62f1617c2 100644
--- a/static/app/components/events/aiAutofix/index.spec.tsx
+++ b/static/app/components/events/aiAutofix/index.spec.tsx
@@ -18,7 +18,7 @@ describe('AiAutofix', () => {
it('renders the Banner component when autofixData is null', () => {
render(<AiAutofix group={group} />);
- expect(screen.getByText('AI Autofix')).toBeInTheDocument();
+ expect(screen.getByText('Try AI Autofix')).toBeInTheDocument();
});
it('renders the FixResult component when autofixData is present', () => {
|
2b59a45fd58957eb1dd5a030af1ab37c1178448a
|
2024-05-21 06:44:13
|
Michael Sun
|
fix(issue-stream): Reduce font size of event status (#71209)
| false
|
Reduce font size of event status (#71209)
|
fix
|
diff --git a/static/app/components/charts/groupStatusChart.tsx b/static/app/components/charts/groupStatusChart.tsx
index dd602afa729ba1..52f52a2bd2d2b9 100644
--- a/static/app/components/charts/groupStatusChart.tsx
+++ b/static/app/components/charts/groupStatusChart.tsx
@@ -155,5 +155,6 @@ const ChartWrapper = styled('div')`
`;
const GraphText = styled('div')`
+ font-size: ${p => p.theme.fontSizeSmall};
color: ${p => p.theme.gray300};
`;
|
59e1c30636357685da5d9a03d6790b39ff0b9ad7
|
2025-01-03 22:59:29
|
anthony sottile
|
ref: another pass at deleting more dead test code (#82847)
| false
|
another pass at deleting more dead test code (#82847)
|
ref
|
diff --git a/src/sentry/testutils/helpers/slack.py b/src/sentry/testutils/helpers/slack.py
index 000a0155d50827..bb5d3458c242c0 100644
--- a/src/sentry/testutils/helpers/slack.py
+++ b/src/sentry/testutils/helpers/slack.py
@@ -57,17 +57,6 @@ def add_identity(
return idp
-def find_identity(idp: IdentityProvider, user: User) -> Identity | None:
- identities = Identity.objects.filter(
- idp=idp,
- user=user,
- status=IdentityStatus.VALID,
- )
- if not identities:
- return None
- return identities[0]
-
-
@assume_test_silo_mode(SiloMode.CONTROL)
def link_user(user: User, idp: IdentityProvider, slack_id: str) -> None:
Identity.objects.create(
diff --git a/tests/sentry/api/endpoints/notifications/test_notification_actions_details.py b/tests/sentry/api/endpoints/notifications/test_notification_actions_details.py
index 10c09f55151da0..482c6a81cfe5cf 100644
--- a/tests/sentry/api/endpoints/notifications/test_notification_actions_details.py
+++ b/tests/sentry/api/endpoints/notifications/test_notification_actions_details.py
@@ -50,14 +50,11 @@ def setUp(self):
self.login_as(user=self.user)
def mock_msg_schedule_response(self, channel_id, result_name="channel"):
- if channel_id == "channel_not_found":
- body = {"ok": False, "error": "channel_not_found"}
- else:
- body = {
- "ok": True,
- result_name: channel_id,
- "scheduled_message_id": "Q1298393284",
- }
+ body = {
+ "ok": True,
+ result_name: channel_id,
+ "scheduled_message_id": "Q1298393284",
+ }
return mock_slack_response("chat_scheduleMessage", body=body)
def mock_msg_delete_scheduled_response(self, channel_id, result_name="channel"):
diff --git a/tests/sentry/api/endpoints/test_organization_dashboard_details.py b/tests/sentry/api/endpoints/test_organization_dashboard_details.py
index 928f6d99b66c87..114e7cdd72ac28 100644
--- a/tests/sentry/api/endpoints/test_organization_dashboard_details.py
+++ b/tests/sentry/api/endpoints/test_organization_dashboard_details.py
@@ -2755,9 +2755,6 @@ def setUp(self):
)
self.widget_ids = [self.widget_1.id, self.widget_2.id, self.widget_3.id, self.widget_4.id]
- def get_widget_queries(self, widget):
- return DashboardWidgetQuery.objects.filter(widget=widget).order_by("order")
-
def test_ondemand_without_flags(self):
data: dict[str, Any] = {
"title": "First dashboard",
diff --git a/tests/sentry/api/endpoints/test_organization_metrics.py b/tests/sentry/api/endpoints/test_organization_metrics.py
index bfda3dbdc1d6d4..8e83c302750368 100644
--- a/tests/sentry/api/endpoints/test_organization_metrics.py
+++ b/tests/sentry/api/endpoints/test_organization_metrics.py
@@ -1,12 +1,9 @@
import copy
-from functools import partial
import pytest
from django.urls import reverse
from sentry.models.apitoken import ApiToken
-from sentry.sentry_metrics import indexer
-from sentry.sentry_metrics.use_case_id_registry import UseCaseID
from sentry.silo.base import SiloMode
from sentry.snuba.metrics import (
DERIVED_METRICS,
@@ -40,20 +37,6 @@
)
-def mocked_mri_resolver(metric_names, mri_func):
- return lambda x: x if x in metric_names else mri_func(x)
-
-
-def indexer_record(use_case_id: UseCaseID, org_id: int, string: str) -> int:
- ret = indexer.record(use_case_id=use_case_id, org_id=org_id, string=string)
- assert ret is not None
- return ret
-
-
-perf_indexer_record = partial(indexer_record, UseCaseID.TRANSACTIONS)
-rh_indexer_record = partial(indexer_record, UseCaseID.SESSIONS)
-
-
class OrganizationMetricsPermissionTest(APITestCase):
endpoints = (
(
diff --git a/tests/sentry/api/endpoints/test_organization_metrics_tag_details.py b/tests/sentry/api/endpoints/test_organization_metrics_tag_details.py
index 33beffe73442c3..7cc608e7916fce 100644
--- a/tests/sentry/api/endpoints/test_organization_metrics_tag_details.py
+++ b/tests/sentry/api/endpoints/test_organization_metrics_tag_details.py
@@ -4,7 +4,7 @@
from sentry.sentry_metrics import indexer
from sentry.sentry_metrics.use_case_id_registry import UseCaseID
-from sentry.testutils.cases import MetricsAPIBaseTestCase, OrganizationMetricsIntegrationTestCase
+from sentry.testutils.cases import OrganizationMetricsIntegrationTestCase
pytestmark = pytest.mark.sentry_metrics
@@ -17,10 +17,6 @@ class OrganizationMetricsTagDetailsTest(OrganizationMetricsIntegrationTestCase):
endpoint = "sentry-api-0-organization-metrics-tag-details"
- @property
- def now(self):
- return MetricsAPIBaseTestCase.MOCK_DATETIME
-
def test_unknown_tag(self):
_indexer_record(self.organization.id, "bar")
response = self.get_response(self.project.organization.slug, "bar")
diff --git a/tests/sentry/api/endpoints/test_organization_projects_experiment.py b/tests/sentry/api/endpoints/test_organization_projects_experiment.py
index 7040f65f47b0e3..c8d8e72e965195 100644
--- a/tests/sentry/api/endpoints/test_organization_projects_experiment.py
+++ b/tests/sentry/api/endpoints/test_organization_projects_experiment.py
@@ -1,8 +1,6 @@
import re
-from functools import cached_property
from unittest.mock import patch
-from django.urls import reverse
from django.utils.text import slugify
from sentry.api.endpoints.organization_projects_experiment import (
@@ -33,10 +31,6 @@ def setUp(self):
self.t1 = f"team-{self.email_username}"
self.mock_experiment_get = patch.object(ExperimentManager, "get", return_value=1).start()
- @cached_property
- def path(self):
- return reverse(self.endpoint, args=[self.organization.slug])
-
def validate_team_with_suffix(self, team: Team):
pattern = rf"^{self.t1}-[a-z]{{3}}$"
return bool(re.match(pattern, team.slug)) and bool(re.match(pattern, team.name))
diff --git a/tests/sentry/api/endpoints/test_organization_root_cause_analysis.py b/tests/sentry/api/endpoints/test_organization_root_cause_analysis.py
index 72150e606e10ff..2eec2caf725eae 100644
--- a/tests/sentry/api/endpoints/test_organization_root_cause_analysis.py
+++ b/tests/sentry/api/endpoints/test_organization_root_cause_analysis.py
@@ -44,7 +44,6 @@ def create_transaction(
project_id,
start_timestamp,
duration,
- transaction_id=None,
):
timestamp = start_timestamp + timedelta(milliseconds=duration)
@@ -56,8 +55,6 @@ def create_transaction(
start_timestamp=start_timestamp,
timestamp=timestamp,
)
- if transaction_id is not None:
- data["event_id"] = transaction_id
data["transaction"] = transaction
data["contexts"]["trace"]["parent_span_id"] = parent_span_id
return self.store_event(data, project_id=project_id)
diff --git a/tests/sentry/api/endpoints/test_organization_teams.py b/tests/sentry/api/endpoints/test_organization_teams.py
index 2a73efe6d01448..834cf9913be7af 100644
--- a/tests/sentry/api/endpoints/test_organization_teams.py
+++ b/tests/sentry/api/endpoints/test_organization_teams.py
@@ -1,7 +1,3 @@
-from functools import cached_property
-
-from django.urls import reverse
-
from sentry.integrations.utils.providers import get_provider_string
from sentry.models.organizationmember import OrganizationMember
from sentry.models.organizationmemberteam import OrganizationMemberTeam
@@ -174,10 +170,6 @@ def setUp(self):
super().setUp()
self.login_as(user=self.user)
- @cached_property
- def path(self):
- return reverse("sentry-api-0-organization-teams", args=[self.organization.slug])
-
def test_missing_permission(self):
user = self.create_user()
self.login_as(user=user)
diff --git a/tests/sentry/api/endpoints/test_organization_traces.py b/tests/sentry/api/endpoints/test_organization_traces.py
index 1dbb69c357bef0..0758ca3ec60e41 100644
--- a/tests/sentry/api/endpoints/test_organization_traces.py
+++ b/tests/sentry/api/endpoints/test_organization_traces.py
@@ -281,8 +281,6 @@ def do_request(self, query, features=None, **kwargs):
]
if self.is_eap:
- if query is None:
- query = {}
query["dataset"] = "spans"
with self.feature(features):
@@ -816,8 +814,6 @@ def do_request(self, trace_id, query, features=None, **kwargs):
]
if self.is_eap:
- if query is None:
- query = {}
query["dataset"] = "spans"
with self.feature(features):
@@ -942,8 +938,6 @@ def do_request(self, query, features=None, **kwargs):
]
if self.is_eap:
- if query is None:
- query = {}
query["dataset"] = "spans"
with self.feature(features):
diff --git a/tests/sentry/api/endpoints/test_organization_user_rollback.py b/tests/sentry/api/endpoints/test_organization_user_rollback.py
index b79ae1fd05fbf5..047c3522d61af5 100644
--- a/tests/sentry/api/endpoints/test_organization_user_rollback.py
+++ b/tests/sentry/api/endpoints/test_organization_user_rollback.py
@@ -1,4 +1,3 @@
-from django.urls import reverse
from rest_framework import status
from sentry.models.organizationmember import OrganizationMember
@@ -18,9 +17,6 @@ def setUp(self):
super().setUp()
self.login_as(user=self.user)
- def _get_path(self) -> str:
- return reverse(self.endpoint)
-
@with_feature("organizations:sentry-rollback-2024")
def test_simple(self):
rollback_user = RollbackUser.objects.create(
diff --git a/tests/sentry/api/endpoints/test_project_details.py b/tests/sentry/api/endpoints/test_project_details.py
index fbee2be2f6f21c..08819b5f593ee1 100644
--- a/tests/sentry/api/endpoints/test_project_details.py
+++ b/tests/sentry/api/endpoints/test_project_details.py
@@ -39,72 +39,6 @@
from sentry.testutils.silo import assume_test_silo_mode
-def _dyn_sampling_data(multiple_uniform_rules=False, uniform_rule_last_position=True):
- rules = [
- {
- "sampleRate": 0.7,
- "type": "trace",
- "active": True,
- "condition": {
- "op": "and",
- "inner": [
- {"op": "eq", "name": "field1", "value": ["val"]},
- {"op": "glob", "name": "field1", "value": ["val"]},
- ],
- },
- "id": -1,
- },
- {
- "sampleRate": 0.8,
- "type": "trace",
- "active": True,
- "condition": {
- "op": "and",
- "inner": [
- {"op": "eq", "name": "field1", "value": ["val"]},
- ],
- },
- "id": -1,
- },
- ]
- if uniform_rule_last_position:
- rules.append(
- {
- "sampleRate": 0.8,
- "type": "trace",
- "active": True,
- "condition": {
- "op": "and",
- "inner": [],
- },
- "id": -1,
- },
- )
- if multiple_uniform_rules:
- new_rule_1 = {
- "sampleRate": 0.22,
- "type": "trace",
- "condition": {
- "op": "and",
- "inner": [],
- },
- "id": -1,
- }
- rules.insert(0, new_rule_1)
-
- return {
- "rules": rules,
- }
-
-
-def _remove_ids_from_dynamic_rules(dynamic_rules):
- if dynamic_rules.get("next_id") is not None:
- del dynamic_rules["next_id"]
- for rule in dynamic_rules["rules"]:
- del rule["id"]
- return dynamic_rules
-
-
def first_symbol_source_id(sources_json):
sources = orjson.loads(sources_json)
return sources[0]["id"]
diff --git a/tests/sentry/api/endpoints/test_project_filters.py b/tests/sentry/api/endpoints/test_project_filters.py
index efea077c4d836e..7c51530ef13051 100644
--- a/tests/sentry/api/endpoints/test_project_filters.py
+++ b/tests/sentry/api/endpoints/test_project_filters.py
@@ -15,7 +15,7 @@ def get_filter_spec(self, response_data, spec_id):
for spec in response_data:
if spec["id"] == spec_id:
return spec
- return None
+ raise AssertionError(f"spec not found: {spec_id}")
def test_get(self):
org = self.create_organization(name="baz", slug="1", owner=self.user)
@@ -38,11 +38,9 @@ def test_health_check_filter(self):
project.update_option("filters:filtered-transaction", "0")
response = self.get_success_response(org.slug, project.slug)
health_check = self.get_filter_spec(response.data, "filtered-transaction")
- assert health_check is not None
assert health_check["active"] is False
project.update_option("filters:filtered-transaction", "1")
response = self.get_success_response(org.slug, project.slug)
health_check = self.get_filter_spec(response.data, "filtered-transaction")
- assert health_check is not None
assert health_check["active"] is True
diff --git a/tests/sentry/api/endpoints/test_project_ownership.py b/tests/sentry/api/endpoints/test_project_ownership.py
index 78e48095b1ec85..367c78e422ea79 100644
--- a/tests/sentry/api/endpoints/test_project_ownership.py
+++ b/tests/sentry/api/endpoints/test_project_ownership.py
@@ -8,7 +8,6 @@
from sentry.models.projectownership import ProjectOwnership
from sentry.silo.base import SiloMode
from sentry.testutils.cases import APITestCase
-from sentry.testutils.helpers.datetime import before_now
from sentry.testutils.outbox import outbox_runner
from sentry.testutils.silo import assume_test_silo_mode
from sentry.testutils.skips import requires_snuba
@@ -44,26 +43,6 @@ def setUp(self):
},
)
- def python_event_data(self):
- return {
- "message": "Kaboom!",
- "platform": "python",
- "timestamp": before_now(seconds=10),
- "stacktrace": {
- "frames": [
- {
- "function": "handle_set_commits",
- "abs_path": "/usr/src/sentry/src/sentry/api/foo.py",
- "module": "sentry.api",
- "in_app": True,
- "lineno": 30,
- "filename": "sentry/api/foo.py",
- }
- ]
- },
- "tags": {"sentry:release": self.release.version},
- }
-
def test_empty_state(self):
resp = self.client.get(self.path)
assert resp.status_code == 200
diff --git a/tests/sentry/api/endpoints/test_project_rules.py b/tests/sentry/api/endpoints/test_project_rules.py
index 3f3772445a2018..70d7800295c10a 100644
--- a/tests/sentry/api/endpoints/test_project_rules.py
+++ b/tests/sentry/api/endpoints/test_project_rules.py
@@ -124,20 +124,6 @@ def test_get_max_alerts_slow_with_group_processing(self):
class CreateProjectRuleTest(ProjectRuleBaseTestCase):
method = "post"
- def mock_conversations_list(self, channels):
- return patch(
- "slack_sdk.web.client.WebClient.conversations_list",
- return_value=SlackResponse(
- client=None,
- http_verb="POST",
- api_url="https://slack.com/api/conversations.list",
- req_args={},
- data={"ok": True, "channels": channels},
- headers={},
- status_code=200,
- ),
- )
-
def mock_conversations_info(self, channel):
return patch(
"slack_sdk.web.client.WebClient.conversations_info",
diff --git a/tests/sentry/api/endpoints/test_relay_projectids.py b/tests/sentry/api/endpoints/test_relay_projectids.py
index a84552f40ee6d6..3d1ab0b2bd2795 100644
--- a/tests/sentry/api/endpoints/test_relay_projectids.py
+++ b/tests/sentry/api/endpoints/test_relay_projectids.py
@@ -19,14 +19,6 @@ def disable_internal_networks():
return mock.patch.object(system, "INTERNAL_NETWORKS", ())
-def _get_all_keys(config):
- for key in config:
- yield key
- if isinstance(config[key], dict):
- for key in _get_all_keys(config[key]):
- yield key
-
-
class RelayProjectIdsEndpointTest(APITestCase):
_date_regex = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z$")
diff --git a/tests/sentry/api/endpoints/test_relay_register.py b/tests/sentry/api/endpoints/test_relay_register.py
index 1f7e8696064e84..7ebc391c882cc3 100644
--- a/tests/sentry/api/endpoints/test_relay_register.py
+++ b/tests/sentry/api/endpoints/test_relay_register.py
@@ -25,10 +25,6 @@ def setUp(self):
self.path = reverse("sentry-api-0-relay-register-challenge")
- def add_internal_key(self, public_key):
- if public_key not in settings.SENTRY_RELAY_WHITELIST_PK:
- settings.SENTRY_RELAY_WHITELIST_PK.append(str(self.public_key))
-
def register_relay(self, key_pair, version, relay_id):
private_key = key_pair[0]
diff --git a/tests/sentry/auth/providers/test_oauth2.py b/tests/sentry/auth/providers/test_oauth2.py
index a89cbd43bfbe0a..a455fcfdbedf08 100644
--- a/tests/sentry/auth/providers/test_oauth2.py
+++ b/tests/sentry/auth/providers/test_oauth2.py
@@ -28,7 +28,7 @@ def build_identity(self, state: Mapping[str, Any]) -> Mapping[str, Any]:
raise NotImplementedError
def build_config(self, state):
- pass
+ raise NotImplementedError
@control_silo_test
diff --git a/tests/sentry/auth/providers/test_saml2.py b/tests/sentry/auth/providers/test_saml2.py
index 347ad09333f8e0..e260552983e987 100644
--- a/tests/sentry/auth/providers/test_saml2.py
+++ b/tests/sentry/auth/providers/test_saml2.py
@@ -25,7 +25,7 @@ class DummySAML2Provider(SAML2Provider):
name = "dummy"
def get_saml_setup_pipeline(self):
- pass
+ raise NotImplementedError
@control_silo_test
diff --git a/tests/sentry/auth/test_password_validation.py b/tests/sentry/auth/test_password_validation.py
index 42a24a1ade3a38..00339976a58fc6 100644
--- a/tests/sentry/auth/test_password_validation.py
+++ b/tests/sentry/auth/test_password_validation.py
@@ -84,10 +84,7 @@ def test_pwned_passwords_low_threshold(self):
"https://api.pwnedpasswords.com/range/74BA3",
body=PWNED_PASSWORDS_RESPONSE_MOCK,
)
- try:
- validate_password("hiphophouse")
- except ValidationError:
- assert False, "ValidationError was thrown"
+ validate_password("hiphophouse") # should not raise
@responses.activate
@override_settings(
@@ -101,7 +98,4 @@ def test_pwned_passwords_corrupted_content(self):
"https://api.pwnedpasswords.com/range/74BA3",
body="corrupted_content_with_no_colon",
)
- try:
- validate_password("hiphophouse")
- except ValidationError:
- assert False, "ValidationError was thrown"
+ validate_password("hiphophouse") # should not raise
diff --git a/tests/sentry/auth/test_superuser.py b/tests/sentry/auth/test_superuser.py
index 2965e91c36cabf..273859aa39f83e 100644
--- a/tests/sentry/auth/test_superuser.py
+++ b/tests/sentry/auth/test_superuser.py
@@ -207,7 +207,7 @@ def test_su_access_no_request(self):
with pytest.raises(SuperuserAccessFormInvalidJson):
superuser.set_logged_in(request.user)
- assert superuser.is_active is False
+ assert superuser.is_active is False
@freeze_time(BASETIME + OUTSIDE_PRIVILEGE_ACCESS_EXPIRE_TIME)
def test_not_expired_check_org_in_request(self):
@@ -271,7 +271,7 @@ def test_su_access_invalid_request_body(
with pytest.raises(SuperuserAccessFormInvalidJson):
superuser.set_logged_in(request.user)
- assert superuser.is_active is False
+ assert superuser.is_active is False
def test_login_saves_session(self):
user = self.create_user("[email protected]", is_superuser=True)
diff --git a/tests/sentry/consumers/test_synchronized.py b/tests/sentry/consumers/test_synchronized.py
index 53d5f590c004ab..112ff04e73d2da 100644
--- a/tests/sentry/consumers/test_synchronized.py
+++ b/tests/sentry/consumers/test_synchronized.py
@@ -67,7 +67,7 @@ def wait_for_consumer(consumer: Consumer[T], message: BrokerValue[T], attempts:
time.sleep(0.1)
- raise Exception(f"{message} was not received by {consumer} within {attempts} attempts")
+ raise AssertionError(f"{message} was not received by {consumer} within {attempts} attempts")
def test_synchronized_consumer() -> None:
diff --git a/tests/sentry/db/models/fields/bitfield/test_bitfield.py b/tests/sentry/db/models/fields/bitfield/test_bitfield.py
index 90703240872af7..aa8677a7749110 100644
--- a/tests/sentry/db/models/fields/bitfield/test_bitfield.py
+++ b/tests/sentry/db/models/fields/bitfield/test_bitfield.py
@@ -322,10 +322,7 @@ def test_binary_capacity(self):
# Big flags list
flags = ["f" + str(i) for i in range(100)]
- try:
- BitField(flags=flags[:MAX_COUNT])
- except ValueError:
- self.fail("It should work well with these flags")
+ BitField(flags=flags[:MAX_COUNT]) # should not raise
pytest.raises(ValueError, BitField, flags=flags[: (MAX_COUNT + 1)])
@@ -340,10 +337,7 @@ def test_dictionary_init(self):
-100: "smallkey",
}
- try:
- bf = BitField(flags)
- except ValueError:
- self.fail("It should work well with these flags")
+ bf = BitField(flags)
self.assertEqual(bf.flags, ["zero", "first", "second", "", "", "", "", "", "", "", "tenth"])
pytest.raises(ValueError, BitField, flags={})
diff --git a/tests/sentry/db/test_silo_models.py b/tests/sentry/db/test_silo_models.py
index 90866812e0d566..2a81fb339f1e08 100644
--- a/tests/sentry/db/test_silo_models.py
+++ b/tests/sentry/db/test_silo_models.py
@@ -36,6 +36,6 @@ def test_cross_silo_deletions():
def test_no_serializers_for_hybrid_cloud_dataclasses():
for type in registry.keys():
if "hybrid_cloud" in type.__module__:
- raise ValueError(
+ raise AssertionError(
f"{type!r} has a registered serializer, but we should not create serializers for hybrid cloud dataclasses."
)
diff --git a/tests/sentry/digests/backends/test_redis.py b/tests/sentry/digests/backends/test_redis.py
index 037be690db83e5..3aea756930ba60 100644
--- a/tests/sentry/digests/backends/test_redis.py
+++ b/tests/sentry/digests/backends/test_redis.py
@@ -73,8 +73,8 @@ def test_maintenance_failure_recovery(self):
# ...and you can't send a digest in the waiting state.
with pytest.raises(InvalidState):
- with backend.digest("timeline", 0) as records:
- pass
+ with backend.digest("timeline", 0):
+ raise AssertionError("unreachable")
record_2 = Record("record:2", self.notification, time.time())
backend.add("timeline", record_2)
@@ -127,8 +127,8 @@ def test_delete(self):
backend.delete("timeline")
with pytest.raises(InvalidState):
- with backend.digest("timeline", 0) as records:
- assert not records
+ with backend.digest("timeline", 0):
+ raise AssertionError("unreachable")
assert set(backend.schedule(time.time())) == set()
assert len(backend._get_connection("timeline").keys("d:*")) == 0
diff --git a/tests/sentry/dynamic_sampling/tasks/test_tasks.py b/tests/sentry/dynamic_sampling/tasks/test_tasks.py
index 9d8817375ed3f6..981149da1f9978 100644
--- a/tests/sentry/dynamic_sampling/tasks/test_tasks.py
+++ b/tests/sentry/dynamic_sampling/tasks/test_tasks.py
@@ -588,10 +588,6 @@ def add_metrics(self, org, project, sample_rate):
org_id=org.id,
)
- @staticmethod
- def flush_redis():
- get_redis_client_for_ds().flushdb()
-
@staticmethod
def set_sliding_window_org_cache_entry(org_id: int, value: str):
redis = get_redis_client_for_ds()
diff --git a/tests/sentry/event_manager/test_event_manager.py b/tests/sentry/event_manager/test_event_manager.py
index 78c2fa907b1528..9a2c80a4a79884 100644
--- a/tests/sentry/event_manager/test_event_manager.py
+++ b/tests/sentry/event_manager/test_event_manager.py
@@ -10,7 +10,6 @@
from unittest.mock import MagicMock, patch
import pytest
-import responses
from arroyo.backends.kafka.consumer import KafkaPayload
from arroyo.backends.local.backend import LocalBroker
from arroyo.backends.local.storages.memory import MemoryMessageStorage
@@ -19,14 +18,6 @@
from django.core.cache import cache
from django.utils import timezone
-from fixtures.github import (
- COMPARE_COMMITS_EXAMPLE_WITH_INTERMEDIATE,
- EARLIER_COMMIT_SHA,
- GET_COMMIT_EXAMPLE,
- GET_LAST_2_COMMITS_EXAMPLE,
- GET_PRIOR_COMMIT_EXAMPLE,
- LATER_COMMIT_SHA,
-)
from sentry import eventstore, nodestore, tsdb
from sentry.attachments import CachedAttachment, attachment_cache
from sentry.constants import MAX_VERSION_LENGTH, DataCategory
@@ -51,7 +42,6 @@
from sentry.ingest.inbound_filters import FilterStatKeys
from sentry.ingest.transaction_clusterer import ClustererNamespace
from sentry.integrations.models.external_issue import ExternalIssue
-from sentry.integrations.models.integration import Integration
from sentry.issues.grouptype import (
ErrorGroupType,
GroupCategory,
@@ -72,7 +62,6 @@
from sentry.models.pullrequest import PullRequest, PullRequestCommit
from sentry.models.release import Release
from sentry.models.releasecommit import ReleaseCommit
-from sentry.models.releaseheadcommit import ReleaseHeadCommit
from sentry.models.releaseprojectenvironment import ReleaseProjectEnvironment
from sentry.options import set
from sentry.projectoptions.defaults import DEFAULT_GROUPING_CONFIG
@@ -88,7 +77,6 @@
from sentry.testutils.helpers.datetime import before_now, freeze_time
from sentry.testutils.performance_issues.event_generators import get_event
from sentry.testutils.pytest.fixtures import django_db_all
-from sentry.testutils.silo import assume_test_silo_mode_of
from sentry.testutils.skips import requires_snuba
from sentry.tsdb.base import TSDBModel
from sentry.types.activity import ActivityType
@@ -2620,69 +2608,6 @@ def test_new_group_metrics_logging_without_frame_mix(self) -> None:
assert "grouping.in_app_frame_mix" not in metrics_logged
-class AutoAssociateCommitTest(TestCase, EventManagerTestMixin):
- def setUp(self) -> None:
- super().setUp()
- self.repo_name = "example"
- self.project = self.create_project(name="foo")
- with assume_test_silo_mode_of(Integration):
- self.org_integration = self.integration.add_organization(
- self.project.organization, self.user
- )
- self.repo = self.create_repo(
- project=self.project,
- name=self.repo_name,
- provider="integrations:github",
- integration_id=self.integration.id,
- )
- self.repo.update(config={"name": self.repo_name})
- self.create_code_mapping(
- project=self.project,
- repo=self.repo,
- organization_integration=self.org_integration,
- stack_root="/stack/root",
- source_root="/source/root",
- default_branch="main",
- )
- responses.add(
- "GET",
- f"https://api.github.com/repos/{self.repo_name}/commits/{LATER_COMMIT_SHA}",
- json=json.loads(GET_COMMIT_EXAMPLE),
- )
- responses.add(
- "GET",
- f"https://api.github.com/repos/{self.repo_name}/commits/{EARLIER_COMMIT_SHA}",
- json=json.loads(GET_PRIOR_COMMIT_EXAMPLE),
- )
- self.dummy_commit_sha = "a" * 40
- responses.add(
- responses.GET,
- f"https://api.github.com/repos/{self.repo_name}/compare/{self.dummy_commit_sha}...{LATER_COMMIT_SHA}",
- json=json.loads(COMPARE_COMMITS_EXAMPLE_WITH_INTERMEDIATE),
- )
- responses.add(
- responses.GET,
- f"https://api.github.com/repos/{self.repo_name}/commits?sha={LATER_COMMIT_SHA}",
- json=json.loads(GET_LAST_2_COMMITS_EXAMPLE),
- )
-
- def _create_first_release_commit(self) -> None:
- # Create a release
- release = self.create_release(project=self.project, version="abcabcabc")
- # Create a commit
- commit = self.create_commit(
- repo=self.repo,
- key=self.dummy_commit_sha,
- )
- # Make a release head commit
- ReleaseHeadCommit.objects.create(
- organization_id=self.project.organization.id,
- repository_id=self.repo.id,
- release=release,
- commit=commit,
- )
-
-
class ReleaseIssueTest(TestCase):
def setUp(self) -> None:
self.project = self.create_project()
@@ -2691,18 +2616,6 @@ def setUp(self) -> None:
self.environment2 = Environment.get_or_create(self.project, "staging")
self.timestamp = float(int(time() - 300))
- def make_event(self, **kwargs: Any) -> dict[str, Any]:
- result = {
- "event_id": "a" * 32,
- "message": "foo",
- "timestamp": self.timestamp + 0.23,
- "level": logging.ERROR,
- "logger": "default",
- "tags": [],
- }
- result.update(kwargs)
- return result
-
def make_release_event(
self,
release_version: str = "1.0",
diff --git a/tests/sentry/features/test_manager.py b/tests/sentry/features/test_manager.py
index 028d145497d8fa..605d0ef75efbff 100644
--- a/tests/sentry/features/test_manager.py
+++ b/tests/sentry/features/test_manager.py
@@ -33,9 +33,6 @@ def has(
return True
def batch_has(self, feature_names, *args: Any, projects=None, organization=None, **kwargs: Any):
- if isinstance(feature_names, str):
- feature_names = [feature_names]
-
feature_results = {
feature_name: True for feature_name in feature_names if feature_name in self.features
}
@@ -49,7 +46,7 @@ def batch_has(self, feature_names, *args: Any, projects=None, organization=None,
return {"unscoped": feature_results}
def _check_for_batch(self, feature_name, organization, actor):
- return True if feature_name in self.features else None
+ raise NotImplementedError
class MockUserBatchHandler(features.BatchFeatureHandler):
diff --git a/tests/sentry/grouping/__init__.py b/tests/sentry/grouping/__init__.py
index c24d6f245296fc..987e586f44e772 100644
--- a/tests/sentry/grouping/__init__.py
+++ b/tests/sentry/grouping/__init__.py
@@ -174,13 +174,10 @@ def to_json(value: Any, pretty_print: bool = False) -> str:
def dump_variant(
variant: BaseVariant,
- lines: list[str] | None = None,
+ lines: list[str],
indent: int = 0,
include_non_contributing: bool = True,
) -> list[str]:
- if lines is None:
- lines = []
-
def _dump_component(component: BaseGroupingComponent, indent: int) -> None:
if not component.hint and not component.values:
return
diff --git a/tests/sentry/grouping/test_components.py b/tests/sentry/grouping/test_components.py
index cd688968c01b89..589864eb887bc3 100644
--- a/tests/sentry/grouping/test_components.py
+++ b/tests/sentry/grouping/test_components.py
@@ -15,7 +15,7 @@
def find_given_child_component[
T
-](parent_component: BaseGroupingComponent[Any], child_component_type: type[T]) -> T | None:
+](parent_component: BaseGroupingComponent[Any], child_component_type: type[T]) -> T:
"""
Finds the first instance of the given type of child component in the parent component's `values`
list. Works best in cases where only one instance of the given type is expected.
@@ -23,8 +23,8 @@ def find_given_child_component[
for child_component in parent_component.values:
if isinstance(child_component, child_component_type):
return child_component
-
- return None
+ else:
+ raise AssertionError(f"component not found: {child_component_type}")
class ComponentTest(TestCase):
diff --git a/tests/sentry/hybridcloud/rpc/test_sig.py b/tests/sentry/hybridcloud/rpc/test_sig.py
index 9780d37dfbf0d5..4d70c6c346ac6d 100644
--- a/tests/sentry/hybridcloud/rpc/test_sig.py
+++ b/tests/sentry/hybridcloud/rpc/test_sig.py
@@ -11,7 +11,7 @@ class AnObject(pydantic.BaseModel):
b: str
def a_function(arg1: AnObject, arg2: AnObject) -> AnObject:
- return AnObject(a=arg1.a + arg2.a, b=".".join((arg1.b, arg2.b)))
+ raise NotImplementedError
sig = SerializableFunctionSignature(a_function)
arg_values = dict(arg1=AnObject(a=1, b="foo"), arg2=AnObject(a=2, b="bar"))
diff --git a/tests/sentry/incidents/endpoints/test_organization_alert_rule_details.py b/tests/sentry/incidents/endpoints/test_organization_alert_rule_details.py
index edf682e7591127..0c0810830d7dcc 100644
--- a/tests/sentry/incidents/endpoints/test_organization_alert_rule_details.py
+++ b/tests/sentry/incidents/endpoints/test_organization_alert_rule_details.py
@@ -2,7 +2,6 @@
from copy import deepcopy
from functools import cached_property
-from typing import Any
from unittest import mock
from unittest.mock import patch
@@ -56,7 +55,6 @@
from sentry.testutils.outbox import outbox_runner
from sentry.testutils.silo import assume_test_silo_mode
from sentry.testutils.skips import requires_snuba
-from sentry.utils import json
from tests.sentry.incidents.endpoints.test_organization_alert_rule_index import AlertRuleBase
pytestmark = [requires_snuba]
@@ -1132,20 +1130,6 @@ def test_change_name_of_existing_alert(self):
class AlertRuleDetailsSlackPutEndpointTest(AlertRuleDetailsBase):
method = "put"
- def mock_conversations_list(self, channels):
- return patch(
- "slack_sdk.web.client.WebClient.conversations_list",
- return_value=SlackResponse(
- client=None,
- http_verb="POST",
- api_url="https://slack.com/api/conversations.list",
- req_args={},
- data={"ok": True, "channels": channels},
- headers={},
- status_code=200,
- ),
- )
-
def mock_conversations_info(self, channel):
return patch(
"slack_sdk.web.client.WebClient.conversations_info",
@@ -1160,15 +1144,6 @@ def mock_conversations_info(self, channel):
),
)
- def _mock_slack_response(self, url: str, body: dict[str, Any], status: int = 200) -> None:
- responses.add(
- method=responses.GET,
- url=url,
- status=status,
- content_type="application/json",
- body=json.dumps(body),
- )
-
def _organization_alert_rule_api_call(
self,
channelName: str | None = None,
diff --git a/tests/sentry/incidents/endpoints/test_serializers.py b/tests/sentry/incidents/endpoints/test_serializers.py
index 6af03ad18e3477..180bf1de3f9968 100644
--- a/tests/sentry/incidents/endpoints/test_serializers.py
+++ b/tests/sentry/incidents/endpoints/test_serializers.py
@@ -866,16 +866,6 @@ def other_project(self):
def alert_rule(self):
return self.create_alert_rule(projects=[self.project, self.other_project])
- @cached_property
- def valid_params(self):
- return {
- "label": "something",
- "threshold_type": 0,
- "resolve_threshold": 1,
- "alert_threshold": 0,
- "actions": [{"type": "email", "targetType": "team", "targetIdentifier": self.team.id}],
- }
-
@cached_property
def access(self):
return from_user(self.user, self.organization)
@@ -888,13 +878,6 @@ def context(self):
"alert_rule": self.alert_rule,
}
- def run_fail_validation_test(self, params, errors):
- base_params = self.valid_params.copy()
- base_params.update(params)
- serializer = AlertRuleTriggerSerializer(context=self.context, data=base_params)
- assert not serializer.is_valid()
- assert serializer.errors == errors
-
def test_validation_no_params(self):
serializer = AlertRuleTriggerSerializer(context=self.context, data={})
assert not serializer.is_valid()
@@ -906,9 +889,6 @@ def test_validation_no_params(self):
class TestAlertRuleTriggerActionSerializer(TestAlertRuleSerializerBase):
- def mock_conversations_list(self, channels):
- return mock_slack_response("conversations_list", body={"ok": True, "channels": channels})
-
def mock_conversations_info(self, channel):
return mock_slack_response(
"conversations_info",
@@ -917,14 +897,11 @@ def mock_conversations_info(self, channel):
)
def patch_msg_schedule_response(self, channel_id, result_name="channel"):
- if channel_id == "channel_not_found":
- body = {"ok": False, "error": "channel_not_found"}
- else:
- body = {
- "ok": True,
- result_name: channel_id,
- "scheduled_message_id": "Q1298393284",
- }
+ body = {
+ "ok": True,
+ result_name: channel_id,
+ "scheduled_message_id": "Q1298393284",
+ }
return mock_slack_response("chat_scheduleMessage", body)
@cached_property
diff --git a/tests/sentry/incidents/test_logic.py b/tests/sentry/incidents/test_logic.py
index 5d6a2117555e85..c5e322d6d6c459 100644
--- a/tests/sentry/incidents/test_logic.py
+++ b/tests/sentry/incidents/test_logic.py
@@ -2372,12 +2372,6 @@ def patch_msg_schedule_response(self, channel_id, result_name="channel"):
)
def patch_msg_delete_scheduled_response(self, channel_id):
- if channel_id == "channel_not_found":
- bodydict = {"ok": False, "error": "channel_not_found"}
- else:
- bodydict = {
- "ok": True,
- }
return patch(
"slack_sdk.web.client.WebClient.chat_deleteScheduledMessage",
return_value=SlackResponse(
@@ -2385,7 +2379,7 @@ def patch_msg_delete_scheduled_response(self, channel_id):
http_verb="POST",
api_url="https://slack.com/api/chat.deleteScheduleMessage",
req_args={},
- data=bodydict,
+ data={"ok": True},
headers={},
status_code=200,
),
diff --git a/tests/sentry/ingest/ingest_consumer/test_ingest_consumer_kafka.py b/tests/sentry/ingest/ingest_consumer/test_ingest_consumer_kafka.py
index e795bf95b18a1a..c330efcf47aa20 100644
--- a/tests/sentry/ingest/ingest_consumer/test_ingest_consumer_kafka.py
+++ b/tests/sentry/ingest/ingest_consumer/test_ingest_consumer_kafka.py
@@ -49,7 +49,7 @@ def inner(type, project=default_project):
"event_id": event_id,
}
else:
- raise ValueError(type)
+ raise AssertionError(type)
em = EventManager(event, project=project)
em.normalize()
diff --git a/tests/sentry/integrations/bitbucket/test_repository.py b/tests/sentry/integrations/bitbucket/test_repository.py
index 0ef575bb54ea73..0e6f656573a9a5 100644
--- a/tests/sentry/integrations/bitbucket/test_repository.py
+++ b/tests/sentry/integrations/bitbucket/test_repository.py
@@ -135,7 +135,7 @@ def test_repository_external_slug(self):
def test_get_repository_data_no_installation_id(self):
with pytest.raises(IntegrationError) as e:
self.provider.get_repository_data(self.organization, {})
- assert "requires an integration id" in str(e)
+ assert "requires an integration id" in str(e.value)
class BitbucketCreateRepositoryTestCase(IntegrationRepositoryTestCase):
diff --git a/tests/sentry/integrations/bitbucket_server/test_repository.py b/tests/sentry/integrations/bitbucket_server/test_repository.py
index fe6c7708da8206..525d12360f8b11 100644
--- a/tests/sentry/integrations/bitbucket_server/test_repository.py
+++ b/tests/sentry/integrations/bitbucket_server/test_repository.py
@@ -253,4 +253,4 @@ def test_repository_external_slug(self):
def test_get_repository_data_no_installation_id(self):
with pytest.raises(IntegrationError) as e:
self.provider.get_repository_data(self.organization, {})
- assert "requires an integration id" in str(e)
+ assert "requires an integration id" in str(e.value)
diff --git a/tests/sentry/integrations/discord/test_uninstall.py b/tests/sentry/integrations/discord/test_uninstall.py
index 1ce4af5823b1ee..fa28cccc65973f 100644
--- a/tests/sentry/integrations/discord/test_uninstall.py
+++ b/tests/sentry/integrations/discord/test_uninstall.py
@@ -9,10 +9,9 @@
from sentry.integrations.models.integration import Integration
from sentry.integrations.models.organization_integration import OrganizationIntegration
from sentry.models.organization import Organization
-from sentry.silo.base import SiloMode
from sentry.testutils.cases import APITestCase
from sentry.testutils.factories import Factories
-from sentry.testutils.silo import assume_test_silo_mode, control_silo_test
+from sentry.testutils.silo import control_silo_test
from sentry.users.models.user import User
from sentry.users.services.user.model import RpcUser
@@ -28,19 +27,14 @@ class DiscordUninstallTest(APITestCase):
def setUp(self) -> None:
self.integration = self.create_discord_integration(self.organization, self.user)
self.login_as(self.user)
- return
def create_discord_integration(
self,
organization: Organization,
- user: RpcUser | User | None,
+ user: RpcUser | User,
guild_id: str = GUILD_ID,
**kwargs: Any,
):
- if user is None:
- with assume_test_silo_mode(SiloMode.REGION):
- user = organization.get_default_owner()
-
integration = Factories.create_integration(
provider="discord",
name="Cool server",
diff --git a/tests/sentry/integrations/jira/test_integration.py b/tests/sentry/integrations/jira/test_integration.py
index d60d28185e54be..5525728fdad5e2 100644
--- a/tests/sentry/integrations/jira/test_integration.py
+++ b/tests/sentry/integrations/jira/test_integration.py
@@ -725,21 +725,6 @@ def test_sync_assignee_outbound_use_email_api(self):
@control_silo_test
class JiraIntegrationTest(APITestCase):
- @cached_property
- def integration(self):
- integration = self.create_provider_integration(
- provider="jira",
- name="Jira Cloud",
- metadata={
- "oauth_client_id": "oauth-client-id",
- "shared_secret": "a-super-secret-key-from-atlassian",
- "base_url": "https://example.atlassian.net",
- "domain_name": "example.atlassian.net",
- },
- )
- integration.add_organization(self.organization, self.user)
- return integration
-
def setUp(self):
super().setUp()
self.min_ago = before_now(minutes=1)
diff --git a/tests/sentry/integrations/slack/service/test_slack_service.py b/tests/sentry/integrations/slack/service/test_slack_service.py
index 19957e8508f9a8..55c2cda9da3815 100644
--- a/tests/sentry/integrations/slack/service/test_slack_service.py
+++ b/tests/sentry/integrations/slack/service/test_slack_service.py
@@ -359,13 +359,13 @@ def test_raises_exception_when_rule_action_does_not_have_channel_id(self) -> Non
message_identifier="123abc",
)
parent_notification = IssueAlertNotificationMessage.from_model(parent_notification_message)
- with pytest.raises(RuleDataError) as err:
+ with pytest.raises(RuleDataError) as excinfo:
self.service._handle_parent_notification(
parent_notification=parent_notification,
notification_to_send="",
client=mock.MagicMock(),
)
- assert (
- err.value
- == f"failed to get channel_id for rule {self.rule.id} and rule action {parent_notification.rule_action_uuid}"
- )
+ assert (
+ str(excinfo.value)
+ == f"failed to get channel_id for rule {self.rule.id} and rule action {parent_notification.rule_action_uuid}"
+ )
diff --git a/tests/sentry/integrations/slack/test_message_builder.py b/tests/sentry/integrations/slack/test_message_builder.py
index 3830b4ff4dc29e..bca19c7326e028 100644
--- a/tests/sentry/integrations/slack/test_message_builder.py
+++ b/tests/sentry/integrations/slack/test_message_builder.py
@@ -228,72 +228,6 @@ def build_test_message_blocks(
}
-def build_test_message(
- teams: set[Team],
- users: set[User],
- timestamp: datetime,
- group: Group,
- event: Event | None = None,
- link_to_event: bool = False,
-) -> dict[str, Any]:
- project = group.project
-
- title = group.title
- title_link = f"http://testserver/organizations/{project.organization.slug}/issues/{group.id}"
- if event:
- title = event.title
- if link_to_event:
- title_link += f"/events/{event.event_id}"
- title_link += "/?referrer=slack"
-
- return {
- "text": "",
- "color": "#E03E2F", # red for error level
- "actions": [
- {"name": "status", "text": "Resolve", "type": "button", "value": "resolved"},
- {
- "name": "status",
- "text": "Archive",
- "type": "button",
- "value": "archived",
- },
- {
- "option_groups": [
- {
- "text": "Teams",
- "options": [
- {"text": f"#{team.slug}", "value": f"team:{team.id}"} for team in teams
- ],
- },
- {
- "text": "People",
- "options": [
- {
- "text": user.email,
- "value": f"user:{user.id}",
- }
- for user in users
- ],
- },
- ],
- "text": "Select Assignee...",
- "selected_options": [],
- "type": "select",
- "name": "assign",
- },
- ],
- "mrkdwn_in": ["text"],
- "title": title,
- "fields": [],
- "footer": f"{project.slug.upper()}-1",
- "ts": timestamp.timestamp(),
- "title_link": title_link,
- "callback_id": '{"issue":' + str(group.id) + "}",
- "fallback": f"[{project.slug}] {title}",
- "footer_icon": "http://testserver/_static/{version}/sentry/images/sentry-email-avatar.png",
- }
-
-
class BuildGroupAttachmentTest(TestCase, PerformanceIssueTestCase, OccurrenceTestMixin):
def test_build_group_block(self):
release = self.create_release(project=self.project)
diff --git a/tests/sentry/integrations/slack/test_notify_action.py b/tests/sentry/integrations/slack/test_notify_action.py
index 77784057b49c1a..96d235cf32642d 100644
--- a/tests/sentry/integrations/slack/test_notify_action.py
+++ b/tests/sentry/integrations/slack/test_notify_action.py
@@ -48,11 +48,7 @@ def mock_msg_schedule_response(self, channel_id, result_name="channel"):
return mock_slack_response("chat_scheduleMessage", body)
def mock_msg_delete_scheduled_response(self, channel_id, result_name="channel"):
- if channel_id == "channel_not_found":
- body = {"ok": False, "error": "channel_not_found"}
- else:
- body = {"ok": True}
- return mock_slack_response("chat_deleteScheduledMessage", body)
+ return mock_slack_response("chat_deleteScheduledMessage", {"ok": True})
def setUp(self):
self.organization = self.get_event().project.organization
diff --git a/tests/sentry/integrations/slack/test_unfurl.py b/tests/sentry/integrations/slack/test_unfurl.py
index 4bdf13a14e0cdc..d8d23c1b4ec280 100644
--- a/tests/sentry/integrations/slack/test_unfurl.py
+++ b/tests/sentry/integrations/slack/test_unfurl.py
@@ -577,7 +577,7 @@ def test_unfurl_discover(self, mock_generate_chart, _):
link_type, args = match_link(url)
if not args or not link_type:
- raise Exception("Missing link_type/args")
+ raise AssertionError("Missing link_type/args")
links = [
UnfurlableUrl(url=url, args=args),
@@ -614,7 +614,7 @@ def test_unfurl_discover_previous_period(self, mock_generate_chart, _):
link_type, args = match_link(url)
if not args or not link_type:
- raise Exception("Missing link_type/args")
+ raise AssertionError("Missing link_type/args")
links = [
UnfurlableUrl(url=url, args=args),
@@ -660,7 +660,7 @@ def test_unfurl_discover_multi_y_axis(self, mock_generate_chart, _):
link_type, args = match_link(url)
if not args or not link_type:
- raise Exception("Missing link_type/args")
+ raise AssertionError("Missing link_type/args")
links = [
UnfurlableUrl(url=url, args=args),
@@ -697,7 +697,7 @@ def test_unfurl_discover_html_escaped(self, mock_generate_chart, _):
link_type, args = match_link(url)
if not args or not link_type:
- raise Exception("Missing link_type/args")
+ raise AssertionError("Missing link_type/args")
links = [
UnfurlableUrl(url=url, args=args),
@@ -758,7 +758,7 @@ def test_unfurl_discover_short_url(self, mock_generate_chart, _):
link_type, args = match_link(url)
if not args or not link_type:
- raise Exception("Missing link_type/args")
+ raise AssertionError("Missing link_type/args")
links = [
UnfurlableUrl(url=url, args=args),
@@ -822,7 +822,7 @@ def test_unfurl_correct_y_axis_for_saved_query(self, mock_generate_chart, _):
link_type, args = match_link(url)
if not args or not link_type:
- raise Exception("Missing link_type/args")
+ raise AssertionError("Missing link_type/args")
links = [
UnfurlableUrl(url=url, args=args),
@@ -874,7 +874,7 @@ def test_top_events_url_param(self, mock_generate_chart, _):
link_type, args = match_link(url)
if not args or not link_type:
- raise Exception("Missing link_type/args")
+ raise AssertionError("Missing link_type/args")
links = [
UnfurlableUrl(url=url, args=args),
@@ -940,7 +940,7 @@ def test_top_daily_events_renders_bar_chart(self, mock_generate_chart, _):
link_type, args = match_link(url)
if not args or not link_type:
- raise Exception("Missing link_type/args")
+ raise AssertionError("Missing link_type/args")
links = [
UnfurlableUrl(url=url, args=args),
@@ -999,7 +999,7 @@ def test_unfurl_discover_short_url_without_project_ids(self, mock_generate_chart
link_type, args = match_link(url)
if not args or not link_type:
- raise Exception("Missing link_type/args")
+ raise AssertionError("Missing link_type/args")
links = [
UnfurlableUrl(url=url, args=args),
@@ -1043,7 +1043,7 @@ def test_unfurl_discover_without_project_ids(
link_type, args = match_link(url)
if not args or not link_type:
- raise Exception("Missing link_type/args")
+ raise AssertionError("Missing link_type/args")
links = [
UnfurlableUrl(url=url, args=args),
@@ -1099,7 +1099,7 @@ def test_bar_chart_display_renders_bar_chart(self, mock_generate_chart, _):
link_type, args = match_link(url)
if not args or not link_type:
- raise Exception("Missing link_type/args")
+ raise AssertionError("Missing link_type/args")
links = [
UnfurlableUrl(url=url, args=args),
@@ -1131,7 +1131,7 @@ def test_bar_chart_interval_with_absolute_date(self, mock_generate_chart, api_mo
link_type, args = match_link(url)
if not args or not link_type:
- raise Exception("Missing link_type/args")
+ raise AssertionError("Missing link_type/args")
links = [
UnfurlableUrl(url=url, args=args),
@@ -1166,7 +1166,7 @@ def test_bar_chart_interval_with_periodic_date(self, mock_generate_chart, api_mo
link_type, args = match_link(url)
if not args or not link_type:
- raise Exception("Missing link_type/args")
+ raise AssertionError("Missing link_type/args")
links = [
UnfurlableUrl(url=url, args=args),
@@ -1217,7 +1217,7 @@ def test_saved_query_with_interval(self, mock_generate_chart, api_mock):
link_type, args = match_link(url)
if not args or not link_type:
- raise Exception("Missing link_type/args")
+ raise AssertionError("Missing link_type/args")
links = [
UnfurlableUrl(url=url, args=args),
@@ -1270,7 +1270,7 @@ def test_saved_query_with_dataset(self, mock_generate_chart, mock_get_event_stat
link_type, args = match_link(url)
if not args or not link_type:
- raise Exception("Missing link_type/args")
+ raise AssertionError("Missing link_type/args")
links = [
UnfurlableUrl(url=url, args=args),
@@ -1312,7 +1312,7 @@ def test_unfurl_discover_homepage(self, mock_generate_chart, mock_get_event_stat
link_type, args = match_link(url)
if not args or not link_type:
- raise Exception("Missing link_type/args")
+ raise AssertionError("Missing link_type/args")
links = [
UnfurlableUrl(url=url, args=args),
diff --git a/tests/sentry/integrations/slack/test_utils.py b/tests/sentry/integrations/slack/test_utils.py
index 4b94da61f43c55..67816a737db636 100644
--- a/tests/sentry/integrations/slack/test_utils.py
+++ b/tests/sentry/integrations/slack/test_utils.py
@@ -68,15 +68,7 @@ def patch_mock_list(self, list_type, channels, result_name="channels"):
),
)
- def patch_msg_response(self, channel_id, result_name="channel"):
- if channel_id == "channel_not_found":
- bodydict = {"ok": False, "error": "channel_not_found"}
- else:
- bodydict = {
- "ok": True,
- result_name: channel_id,
- "scheduled_message_id": "Q1298393284",
- }
+ def patch_msg_response_not_found(self):
return patch(
"slack_sdk.web.client.WebClient.chat_scheduleMessage",
return_value=SlackResponse(
@@ -84,7 +76,7 @@ def patch_msg_response(self, channel_id, result_name="channel"):
http_verb="POST",
api_url="https://slack.com/api/chat.scheduleMessage",
req_args={},
- data=bodydict,
+ data={"ok": False, "error": "channel_not_found"},
headers={},
status_code=200,
),
@@ -142,7 +134,7 @@ def test_valid_member_selected_sdk_client(self):
{"name": "better_morty", "id": "bm", "profile": {"display_name": "Morty"}},
]
- with self.patch_msg_response("channel_not_found"):
+ with self.patch_msg_response_not_found():
with self.patch_mock_list("users", response_list, "members"):
self.run_valid_test("@first-morty", MEMBER_PREFIX, "m", False)
@@ -153,7 +145,7 @@ def test_valid_member_selected_display_name_sdk_client(self):
{"name": "better_morty", "id": "bm", "profile": {"display_name": "Morty"}},
]
- with self.patch_msg_response("channel_not_found"):
+ with self.patch_msg_response_not_found():
with self.patch_mock_list("users", response_list, "members"):
self.run_valid_test("@Jimbob", MEMBER_PREFIX, "o-u", False)
@@ -164,13 +156,13 @@ def test_invalid_member_selected_display_name_sdk_client(self):
{"name": "better_morty", "id": "bm", "profile": {"display_name": "Morty"}},
]
- with self.patch_msg_response("channel_not_found"):
+ with self.patch_msg_response_not_found():
with self.patch_mock_list("users", response_list, "members"):
with pytest.raises(DuplicateDisplayNameError):
get_channel_id(self.integration, "@Morty")
def test_invalid_channel_selected_sdk_client(self):
- with self.patch_msg_response("channel_not_found"):
+ with self.patch_msg_response_not_found():
assert get_channel_id(self.integration, "#fake-channel").channel_id is None
assert get_channel_id(self.integration, "@fake-user").channel_id is None
@@ -184,7 +176,7 @@ def test_rate_limiting_sdk_client(self, mock_api_call):
"status": 429,
}
- with self.patch_msg_response("channel_not_found"):
+ with self.patch_msg_response_not_found():
with pytest.raises(ApiRateLimitedError):
get_channel_id(self.integration, "@user")
diff --git a/tests/sentry/integrations/slack/webhooks/commands/__init__.py b/tests/sentry/integrations/slack/webhooks/commands/__init__.py
index 808a24873610b9..3a4d9b27dde0b7 100644
--- a/tests/sentry/integrations/slack/webhooks/commands/__init__.py
+++ b/tests/sentry/integrations/slack/webhooks/commands/__init__.py
@@ -19,9 +19,8 @@
from sentry.models.team import Team
from sentry.silo.base import SiloMode
from sentry.testutils.cases import APITestCase, TestCase
-from sentry.testutils.helpers import find_identity, install_slack, link_team, link_user
+from sentry.testutils.helpers import install_slack, link_team, link_user
from sentry.testutils.silo import assume_test_silo_mode
-from sentry.users.models.identity import Identity
class SlackCommandsTest(APITestCase, TestCase):
@@ -58,9 +57,6 @@ def send_slack_message(self, command: str, **kwargs: Any) -> dict[str, str]:
)
return orjson.loads(response.content)
- def find_identity(self) -> Identity | None:
- return find_identity(idp=self.idp, user=self.user)
-
def link_user(self) -> None:
return link_user(user=self.user, idp=self.idp, slack_id=self.slack_id)
diff --git a/tests/sentry/integrations/test_base.py b/tests/sentry/integrations/test_base.py
index ae848b65fdd5f6..7b78eb23692f72 100644
--- a/tests/sentry/integrations/test_base.py
+++ b/tests/sentry/integrations/test_base.py
@@ -9,7 +9,7 @@ class TestIntegration(IntegrationInstallation):
__test__ = False
def get_client(self):
- pass
+ raise NotImplementedError
@all_silo_test
diff --git a/tests/sentry/integrations/test_client.py b/tests/sentry/integrations/test_client.py
index d14f6406f6628a..7c0ea22dc49cb3 100644
--- a/tests/sentry/integrations/test_client.py
+++ b/tests/sentry/integrations/test_client.py
@@ -10,7 +10,6 @@
from urllib3.exceptions import InvalidChunkLength
from urllib3.response import HTTPResponse
-from sentry.identity.oauth2 import OAuth2Provider
from sentry.integrations.client import ApiClient
from sentry.shared_integrations.exceptions import (
ApiConnectionResetError,
@@ -320,17 +319,3 @@ def test_parameters_passed_correctly(self):
verify=False,
cert=None,
)
-
-
-class OAuthProvider(OAuth2Provider):
- key = "oauth"
- name = "OAuth Provider"
-
- def get_client_id(self):
- return "client_id"
-
- def get_client_secret(self):
- return "client_secret"
-
- def get_refresh_token_url(self):
- return "https://example.com"
diff --git a/tests/sentry/integrations/utils/test_sync.py b/tests/sentry/integrations/utils/test_sync.py
index 34b708cc912fe9..1a1044e8b986c8 100644
--- a/tests/sentry/integrations/utils/test_sync.py
+++ b/tests/sentry/integrations/utils/test_sync.py
@@ -39,22 +39,6 @@ def setUp(self):
user=self.test_user, email="[email protected]", is_verified=True
).exists()
- def create_example_integration(self, organization, external_id):
- self.example_integration = self.create_integration(
- organization=organization,
- external_id=external_id,
- provider="example",
- oi_params={
- "config": {
- "sync_comments": True,
- "sync_status_outbound": True,
- "sync_status_inbound": True,
- "sync_assignee_outbound": True,
- "sync_assignee_inbound": True,
- }
- },
- )
-
def assign_default_group_to_user(self, user: User, group: Group | None = None):
group_to_update: Group = group or self.group
GroupAssignee.objects.assign(group_to_update, serialize_rpc_user(user))
diff --git a/tests/sentry/integrations/vercel/test_uninstall.py b/tests/sentry/integrations/vercel/test_uninstall.py
index 88243290c1b39f..69f2e6e0b5586b 100644
--- a/tests/sentry/integrations/vercel/test_uninstall.py
+++ b/tests/sentry/integrations/vercel/test_uninstall.py
@@ -86,19 +86,6 @@ def setUp(self):
metadata=metadata,
)
- def _get_delete_response(self):
- # https://vercel.com/docs/integrations?query=event%20paylo#webhooks/events/integration-configuration-removed
- return """{
- "payload": {
- "configuration": {
- "id": "my_config_id",
- "projects": ["project_id1"]
- }
- },
- "teamId": "vercel_team_id",
- "userId": "vercel_user_id"
- }"""
-
def test_uninstall(self):
with override_options({"vercel.client-secret": SECRET}):
response = self.client.post(
diff --git a/tests/sentry/integrations/vsts/test_issues.py b/tests/sentry/integrations/vsts/test_issues.py
index 7643a538f9a81a..c9c251faf80872 100644
--- a/tests/sentry/integrations/vsts/test_issues.py
+++ b/tests/sentry/integrations/vsts/test_issues.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-from functools import cached_property
from time import time
from typing import Any
from unittest.mock import patch
@@ -8,7 +7,7 @@
import orjson
import pytest
import responses
-from django.test import RequestFactory, override_settings
+from django.test import override_settings
from responses import matchers
from fixtures.vsts import (
@@ -71,10 +70,6 @@ def assert_response_calls(expected_region_response, expected_non_region_response
class VstsIssueBase(TestCase):
- @cached_property
- def request(self):
- return RequestFactory()
-
def setUp(self):
with assume_test_silo_mode(SiloMode.CONTROL):
model = self.create_provider_integration(
diff --git a/tests/sentry/integrations/vsts/test_repository.py b/tests/sentry/integrations/vsts/test_repository.py
index 534ffca9bc4bf5..a1f0f8d744fc6c 100644
--- a/tests/sentry/integrations/vsts/test_repository.py
+++ b/tests/sentry/integrations/vsts/test_repository.py
@@ -170,10 +170,6 @@ def setUp(self):
}
self.login_as(self.user)
- @cached_property
- def provider(self):
- return VstsRepositoryProvider("integrations:vsts")
-
def tearDown(self):
super().tearDown()
responses.reset()
diff --git a/tests/sentry/issues/test_merge.py b/tests/sentry/issues/test_merge.py
index 6d2b915d898791..9918385f53ea1a 100644
--- a/tests/sentry/issues/test_merge.py
+++ b/tests/sentry/issues/test_merge.py
@@ -55,4 +55,4 @@ def test_handle_merge_performance_issues(self) -> None:
with pytest.raises(rest_framework.exceptions.ValidationError) as e:
handle_merge(self.groups, self.project_lookup, self.user)
- assert e.match("Only error issues can be merged.")
+ assert e.match("Only error issues can be merged.")
diff --git a/tests/sentry/middleware/integrations/parsers/test_bitbucket_server.py b/tests/sentry/middleware/integrations/parsers/test_bitbucket_server.py
index 6e0b86511ef6c4..7d0aa5fb315288 100644
--- a/tests/sentry/middleware/integrations/parsers/test_bitbucket_server.py
+++ b/tests/sentry/middleware/integrations/parsers/test_bitbucket_server.py
@@ -5,7 +5,6 @@
from django.test import RequestFactory, override_settings
from django.urls import reverse
-from sentry.integrations.models.integration import Integration
from sentry.middleware.integrations.parsers.bitbucket_server import BitbucketServerRequestParser
from sentry.models.organizationmapping import OrganizationMapping
from sentry.silo.base import SiloMode
@@ -23,13 +22,6 @@ class BitbucketServerRequestParserTest(TestCase):
region = Region("us", 1, "https://us.testserver", RegionCategory.MULTI_TENANT)
region_config = (region,)
- def get_integration(self) -> Integration:
- return self.create_integration(
- organization=self.organization,
- external_id="bitbucketserver:1",
- provider="bitbucket_server",
- )
-
@override_regions(region_config)
@override_settings(SILO_MODE=SiloMode.CONTROL)
def test_routing_webhook(self):
diff --git a/tests/sentry/middleware/integrations/parsers/test_slack.py b/tests/sentry/middleware/integrations/parsers/test_slack.py
index 260f2259a28928..3f039aa9d09845 100644
--- a/tests/sentry/middleware/integrations/parsers/test_slack.py
+++ b/tests/sentry/middleware/integrations/parsers/test_slack.py
@@ -97,7 +97,7 @@ def test_django_view(self):
parser = SlackRequestParser(request, self.get_response)
parser_integration = parser.get_integration_from_request()
if not parser_integration:
- raise ValueError("Parser could not identify an integration")
+ raise AssertionError("Parser could not identify an integration")
assert parser_integration.id == self.integration.id
# Passes through to control silo
diff --git a/tests/sentry/middleware/test_access_log_middleware.py b/tests/sentry/middleware/test_access_log_middleware.py
index c520bb1674d31f..46ec21299bde7c 100644
--- a/tests/sentry/middleware/test_access_log_middleware.py
+++ b/tests/sentry/middleware/test_access_log_middleware.py
@@ -47,7 +47,7 @@ class RateLimitedEndpoint(Endpoint):
)
def get(self, request):
- return Response({"ok": True})
+ raise NotImplementedError
class ConcurrentRateLimitedEndpoint(Endpoint):
diff --git a/tests/sentry/middleware/test_auth.py b/tests/sentry/middleware/test_auth.py
index ce6c3d6c16a736..5fd71dc65ecff3 100644
--- a/tests/sentry/middleware/test_auth.py
+++ b/tests/sentry/middleware/test_auth.py
@@ -23,13 +23,6 @@ class AuthenticationMiddlewareTestCase(TestCase):
def assert_user_equals(self, request):
assert request.user == user_service.get_user(user_id=self.user.id)
- def setUp(self):
- from django.core.cache import cache
-
- cache.clear()
- yield
- cache.clear()
-
@cached_property
def request(self):
rv = RequestFactory().get("/")
diff --git a/tests/sentry/middleware/test_ratelimit_middleware.py b/tests/sentry/middleware/test_ratelimit_middleware.py
index a4e396265a0d18..1941c9d1fc6680 100644
--- a/tests/sentry/middleware/test_ratelimit_middleware.py
+++ b/tests/sentry/middleware/test_ratelimit_middleware.py
@@ -33,13 +33,13 @@ class TestEndpoint(Endpoint):
enforce_rate_limit = True
def get(self):
- return Response({"ok": True})
+ raise NotImplementedError
class TestEndpointNoRateLimits(Endpoint):
enforce_rate_limit = False
def get(self):
- return Response({"ok": True})
+ raise NotImplementedError
_test_endpoint = TestEndpoint.as_view()
_test_endpoint_no_rate_limits = TestEndpointNoRateLimits.as_view()
diff --git a/tests/sentry/middleware/test_stats.py b/tests/sentry/middleware/test_stats.py
index afd5766589081a..43ee0700eb1de5 100644
--- a/tests/sentry/middleware/test_stats.py
+++ b/tests/sentry/middleware/test_stats.py
@@ -3,7 +3,6 @@
from django.test import RequestFactory, override_settings
from rest_framework.permissions import AllowAny
-from rest_framework.response import Response
from sentry.api.base import Endpoint
from sentry.middleware.ratelimit import RatelimitMiddleware
@@ -19,7 +18,7 @@ class RateLimitedEndpoint(Endpoint):
rate_limits = {"GET": {RateLimitCategory.IP: RateLimit(limit=0, window=10)}}
def get(self):
- return Response({"ok": True})
+ raise NotImplementedError
class RequestTimingMiddlewareTest(TestCase):
diff --git a/tests/sentry/models/test_organizationslugreservation.py b/tests/sentry/models/test_organizationslugreservation.py
index aacefe2443edf1..6a32739db62d52 100644
--- a/tests/sentry/models/test_organizationslugreservation.py
+++ b/tests/sentry/models/test_organizationslugreservation.py
@@ -69,7 +69,7 @@ def assert_all_replicas_match_slug_reservations(self):
or len(slug_reservations_missing_replicas) > 0
or len(extraneous_replicas) > 0
):
- raise Exception(
+ raise AssertionError(
"One or more org slug replicas did not match\n"
+ f"mismatched replicas: {mismatched_slug_res_replicas}\n"
+ f"extraneous replicas: {extraneous_replicas}\n"
diff --git a/tests/sentry/models/test_project.py b/tests/sentry/models/test_project.py
index 21431776a8dd27..307310ef5b881c 100644
--- a/tests/sentry/models/test_project.py
+++ b/tests/sentry/models/test_project.py
@@ -530,23 +530,6 @@ def assert_settings_copied(self, project):
for rule, other_rule in zip(rules, self.rules):
assert rule.label == other_rule.label
- def assert_settings_not_copied(self, project, teams=()):
- for key in self.options_dict.keys():
- assert project.get_option(key) is None
-
- project_teams = ProjectTeam.objects.filter(project_id=project.id, team__in=teams)
- assert len(project_teams) == len(teams)
-
- project_envs = EnvironmentProject.objects.filter(project_id=project.id)
- assert len(project_envs) == 0
-
- assert not ProjectOwnership.objects.filter(project_id=project.id).exists()
-
- # default rule
- rules = Rule.objects.filter(project_id=project.id)
- assert len(rules) == 1
- assert rules[0].label == "Send a notification for new issues"
-
def test_simple(self):
project = self.create_project(fire_project_created=True)
diff --git a/tests/sentry/monitors/consumers/test_incident_occurrence_consumer.py b/tests/sentry/monitors/consumers/test_incident_occurrence_consumer.py
index 49034336913d38..b43e421c754bd8 100644
--- a/tests/sentry/monitors/consumers/test_incident_occurrence_consumer.py
+++ b/tests/sentry/monitors/consumers/test_incident_occurrence_consumer.py
@@ -173,7 +173,7 @@ def test_delayed_decision_dispatch(
# Raises a message rejected and does not send the occurrence
with pytest.raises(MessageRejected):
send_incident_occurrence(consumer, ts, message)
- assert mock_send_incident_occurrence.call_count == 0
+ assert mock_send_incident_occurrence.call_count == 0
# Tick decision resolves to OK
mock_memoized_tick_decision.return_value = TickAnomalyDecision.NORMAL
diff --git a/tests/sentry/notifications/test_helpers.py b/tests/sentry/notifications/test_helpers.py
index 8e556abfb0aea6..33075e138c3fe1 100644
--- a/tests/sentry/notifications/test_helpers.py
+++ b/tests/sentry/notifications/test_helpers.py
@@ -1,4 +1,3 @@
-import types
from urllib.parse import parse_qs, urlparse
from sentry.integrations.models.external_actor import ExternalActor
@@ -24,10 +23,6 @@
from sentry.types.actor import Actor
-def mock_event(*, transaction, data=None):
- return types.SimpleNamespace(data=data or {}, transaction=transaction)
-
-
class NotificationHelpersTest(TestCase):
def setUp(self):
super().setUp()
diff --git a/tests/sentry/notifications/test_notifications.py b/tests/sentry/notifications/test_notifications.py
index 902f15941e5fe3..9c53c02de08d65 100644
--- a/tests/sentry/notifications/test_notifications.py
+++ b/tests/sentry/notifications/test_notifications.py
@@ -59,35 +59,6 @@ def get_attachment():
return attachments[0], data["text"][0]
-def get_blocks():
- assert len(responses.calls) >= 1
- data = parse_qs(responses.calls[0].request.body)
- assert "text" in data
- assert "blocks" in data
-
- blocks = json.loads(data["blocks"][0])
-
- # title with link, text, footer
- if blocks[1]["type"] == "context":
- title_block = blocks[1]["elements"][0]["text"]
- else:
- title_block = blocks[1]["text"]["text"]
-
- url_block = blocks[-1].get("elements")
- if url_block:
- url_block = url_block[0].get("url")
-
- # assume the divider is the last element
- footer = blocks[-2].get("elements")
- if footer:
- footer = footer[0].get("text")
- # otherwise try to get footer from the last element
- if not footer:
- footer = blocks[-1]["elements"][0]["text"]
-
- return title_block, data["text"][0], footer, url_block
-
-
def get_notification_uuid(url: str):
query_params = parse_qs(urlparse(url).query)
notification_uuid = query_params["notification_uuid"][0].split("|")[0]
diff --git a/tests/sentry/plugins/sentry_webhooks/test_plugin.py b/tests/sentry/plugins/sentry_webhooks/test_plugin.py
index 4eaaaf50548ff4..7d17165b037ea4 100644
--- a/tests/sentry/plugins/sentry_webhooks/test_plugin.py
+++ b/tests/sentry/plugins/sentry_webhooks/test_plugin.py
@@ -52,10 +52,7 @@ def test_unsupported_text_response(self):
content_type="application/json",
)
- try:
- self.plugin.notify(self.notification)
- except Exception as exc:
- assert False, f"'self.plugin.notify' raised an exception {exc}"
+ self.plugin.notify(self.notification) # does not raise!
assert len(responses.calls) == 1
assert responses.calls[0].response.status_code == 200
@@ -67,10 +64,7 @@ def test_unsupported_null_response(self):
responses.POST, "http://example.com", body="null", content_type="application/json"
)
- try:
- self.plugin.notify(self.notification)
- except Exception as exc:
- assert False, f"'self.plugin.notify' raised an exception {exc}"
+ self.plugin.notify(self.notification) # does not raise!
assert len(responses.calls) == 1
assert responses.calls[0].response.status_code == 200
@@ -82,10 +76,7 @@ def test_unsupported_int_response(self):
responses.POST, "http://example.com", body="1", content_type="application/json"
)
- try:
- self.plugin.notify(self.notification)
- except Exception as exc:
- assert False, f"'self.plugin.notify' raised an exception {exc}"
+ self.plugin.notify(self.notification) # does not raise!
assert len(responses.calls) == 1
assert responses.calls[0].response.status_code == 200
@@ -106,10 +97,7 @@ def test_moved_permanently(self):
responses.add(responses.POST, "http://example.com", body="<moved permanently", status=301)
- try:
- self.plugin.notify(self.notification)
- except Exception:
- assert False, "ValueError: Received unexpected plaintext response for code 301"
+ self.plugin.notify(self.notification) # does not raise!
assert len(responses.calls) == 1
assert responses.calls[0].response.status_code == 301
diff --git a/tests/sentry/profiles/test_task.py b/tests/sentry/profiles/test_task.py
index 0eef9c5805f1b8..b97385f266901c 100644
--- a/tests/sentry/profiles/test_task.py
+++ b/tests/sentry/profiles/test_task.py
@@ -3,7 +3,6 @@
import zipfile
from io import BytesIO
from os.path import join
-from tempfile import TemporaryFile
from typing import Any
from unittest.mock import patch
@@ -86,26 +85,6 @@ def load_profile(name):
return json.loads(f.read())
-def load_proguard(project, proguard_uuid, proguard_source):
- with TemporaryFile() as tf:
- tf.write(proguard_source)
- tf.seek(0)
- file = Factories.create_file(
- name=proguard_uuid,
- type="project.dif",
- headers={"Content-Type": "proguard"},
- )
- file.putfile(tf)
-
- return Factories.create_dif_file(
- project,
- file=file,
- debug_id=proguard_uuid,
- object_name="proguard-mapping",
- data={"features": ["mapping"]},
- )
-
-
@pytest.fixture
def owner():
return Factories.create_user()
@@ -288,21 +267,6 @@ def sample_v2_profile():
)
[email protected]
-def proguard_file_basic(project):
- return load_proguard(project, PROGUARD_UUID, PROGUARD_SOURCE)
-
-
[email protected]
-def proguard_file_inline(project):
- return load_proguard(project, PROGUARD_INLINE_UUID, PROGUARD_INLINE_SOURCE)
-
-
[email protected]
-def proguard_file_bug(project):
- return load_proguard(project, PROGUARD_BUG_UUID, PROGUARD_BUG_SOURCE)
-
-
@django_db_all
def test_normalize_sample_v1_profile(organization, sample_v1_profile):
sample_v1_profile["transaction_tags"] = {"device.class": "1"}
diff --git a/tests/sentry/ratelimits/utils/test_get_ratelimit_key.py b/tests/sentry/ratelimits/utils/test_get_ratelimit_key.py
index 38f61e52a38a84..a6b25c7d8d039f 100644
--- a/tests/sentry/ratelimits/utils/test_get_ratelimit_key.py
+++ b/tests/sentry/ratelimits/utils/test_get_ratelimit_key.py
@@ -2,7 +2,6 @@
from django.contrib.sessions.backends.base import SessionBase
from django.test import RequestFactory
from rest_framework.permissions import AllowAny
-from rest_framework.response import Response
from sentry.api.base import Endpoint
from sentry.auth.services.auth import AuthenticatedToken
@@ -35,7 +34,7 @@ class APITestEndpoint(Endpoint):
)
def get(self, request):
- return Response({"ok": True})
+ raise NotImplementedError
@all_silo_test
diff --git a/tests/sentry/release_health/test_metrics_sessions_v2.py b/tests/sentry/release_health/test_metrics_sessions_v2.py
index 0f68ae568ac9d9..1f12fd253cf56d 100644
--- a/tests/sentry/release_health/test_metrics_sessions_v2.py
+++ b/tests/sentry/release_health/test_metrics_sessions_v2.py
@@ -1,7 +1,6 @@
from datetime import timedelta
import pytest
-from django.urls import reverse
from django.utils import timezone
from snuba_sdk import Column, Condition, Function, Op
@@ -10,8 +9,6 @@
SessionStatus,
_extract_status_filter_from_conditions,
)
-from sentry.testutils.cases import APITestCase, SnubaTestCase
-from sentry.testutils.helpers.datetime import freeze_time
pytestmark = pytest.mark.sentry_metrics
@@ -19,49 +16,6 @@
MOCK_DATETIME = ONE_DAY_AGO.replace(hour=10, minute=0, second=0, microsecond=0)
-@freeze_time(MOCK_DATETIME)
-class MetricsSessionsV2Test(APITestCase, SnubaTestCase):
- def setUp(self):
- super().setUp()
- self.setup_fixture()
-
- def setup_fixture(self):
- self.organization1 = self.organization
- self.project1 = self.project
- self.project2 = self.create_project(
- name="teletubbies", slug="teletubbies", teams=[self.team], fire_project_created=True
- )
-
- self.release1 = self.create_release(project=self.project1, version="hello")
- self.release2 = self.create_release(project=self.project1, version="hola")
- self.release3 = self.create_release(project=self.project2, version="hallo")
-
- self.environment1 = self.create_environment(self.project1, name="development")
- self.environment2 = self.create_environment(self.project1, name="production")
- self.environment3 = self.create_environment(self.project2, name="testing")
-
- def do_request(self, query, user=None, org=None):
- self.login_as(user=user or self.user)
- url = reverse(
- "sentry-api-0-organization-sessions",
- kwargs={"organization_id_or_slug": (org or self.organization1).slug},
- )
- return self.client.get(url, query, format="json")
-
- def get_sessions_data(self, groupby: list[str], interval):
- response = self.do_request(
- {
- "organization_id_or_slug": [self.organization1],
- "project": [self.project1.id],
- "field": ["sum(session)"],
- "groupBy": groupby,
- "interval": interval,
- }
- )
- assert response.status_code == 200
- return response.data
-
-
@pytest.mark.parametrize(
"input, expected_output, expected_status_filter",
[
diff --git a/tests/sentry/replays/consumers/test_recording.py b/tests/sentry/replays/consumers/test_recording.py
index a685e7ba656d68..b54dbc86deacbd 100644
--- a/tests/sentry/replays/consumers/test_recording.py
+++ b/tests/sentry/replays/consumers/test_recording.py
@@ -37,7 +37,7 @@ def test_multiprocessing_strategy():
)
def _commit(offsets: Mapping[Partition, int], force: bool = False) -> None:
- return None
+ raise NotImplementedError
# Assert the multi-processing step does not fail to initialize.
task = factory.create_with_partitions(_commit, {})
diff --git a/tests/sentry/runner/commands/test_workstations.py b/tests/sentry/runner/commands/test_workstations.py
index 0fb80ac841f9f4..f6f41251c36d65 100644
--- a/tests/sentry/runner/commands/test_workstations.py
+++ b/tests/sentry/runner/commands/test_workstations.py
@@ -1,4 +1,3 @@
-import subprocess
from dataclasses import dataclass
from unittest.mock import MagicMock, Mock, patch
@@ -26,18 +25,6 @@ def __init__(self, cmd, *args, **kwargs):
self.stderr = ""
-class FakePopenFactory:
- pass
-
-
-def raise_error(*args, **kwargs):
- raise subprocess.CalledProcessError(returncode=123, cmd="foo")
-
-
-def raise_timeout(*args, **kwargs):
- raise subprocess.TimeoutExpired("Fake gcloud timeout", timeout=123)
-
-
class WorkstationsTestCase(CliTestCase):
command = workstations
diff --git a/tests/sentry/search/events/builder/test_metrics.py b/tests/sentry/search/events/builder/test_metrics.py
index 9073ae47dc5778..26b3b5752bbcb3 100644
--- a/tests/sentry/search/events/builder/test_metrics.py
+++ b/tests/sentry/search/events/builder/test_metrics.py
@@ -1208,7 +1208,7 @@ def test_multiple_entity_orderby_fails(self):
def test_multiple_entity_query_fails(self):
with pytest.raises(IncompatibleMetricsQuery):
- query = MetricsQueryBuilder(
+ MetricsQueryBuilder(
self.params,
query="p95(transaction.duration):>5s AND count_unique(user):>0",
dataset=Dataset.PerformanceMetrics,
@@ -1222,11 +1222,10 @@ def test_multiple_entity_query_fails(self):
use_aggregate_conditions=True,
),
)
- query.run_query("test_query")
def test_query_entity_does_not_match_orderby(self):
with pytest.raises(IncompatibleMetricsQuery):
- query = MetricsQueryBuilder(
+ MetricsQueryBuilder(
self.params,
query="count_unique(user):>0",
dataset=Dataset.PerformanceMetrics,
@@ -1241,7 +1240,6 @@ def test_query_entity_does_not_match_orderby(self):
use_aggregate_conditions=True,
),
)
- query.run_query("test_query")
def test_aggregate_query_with_multiple_entities_without_orderby(self):
self.store_transaction_metric(
diff --git a/tests/sentry/search/events/test_filter.py b/tests/sentry/search/events/test_filter.py
index 9519e222129815..8ca88fba347d65 100644
--- a/tests/sentry/search/events/test_filter.py
+++ b/tests/sentry/search/events/test_filter.py
@@ -28,53 +28,6 @@
from sentry.search.events.types import ParamsType, QueryBuilderConfig
from sentry.snuba.dataset import Dataset
from sentry.testutils.cases import TestCase
-from sentry.utils.snuba import OPERATOR_TO_FUNCTION
-
-
-# Helper functions to make reading the expected output from the boolean tests easier to read. #
-# a:b
-def _eq(xy):
- return ["equals", [["ifNull", [xy[0], "''"]], xy[1]]]
-
-
-# a:b but using operators instead of functions
-def _oeq(xy):
- return [["ifNull", [xy[0], "''"]], "=", xy[1]]
-
-
-# !a:b using operators instead of functions
-def _noeq(xy):
- return [["ifNull", [xy[0], "''"]], "!=", xy[1]]
-
-
-# message ("foo bar baz")
-def _m(x):
- return ["notEquals", [["positionCaseInsensitive", ["message", f"'{x}'"]], 0]]
-
-
-# message ("foo bar baz") using operators instead of functions
-def _om(x):
- return [["positionCaseInsensitive", ["message", f"'{x}'"]], "!=", 0]
-
-
-# x OR y
-def _or(x, y):
- return ["or", [x, y]]
-
-
-# x AND y
-def _and(x, y):
- return ["and", [x, y]]
-
-
-# count():>1
-def _c(op, val):
- return [OPERATOR_TO_FUNCTION[op], ["count", val]]
-
-
-# count():>1 using operators instead of functions
-def _oc(op, val):
- return ["count", op, val]
def with_type(type, argument):
diff --git a/tests/sentry/sentry_metrics/test_strings.py b/tests/sentry/sentry_metrics/test_strings.py
index ff4d94523fc350..86e83614ac9009 100644
--- a/tests/sentry/sentry_metrics/test_strings.py
+++ b/tests/sentry/sentry_metrics/test_strings.py
@@ -107,18 +107,15 @@ def test_reverse_resolve_reindexed():
def test_shared_mri_string_range(mri, id):
parsed_mri = parse_mri(mri)
assert parsed_mri is not None, mri
- try:
- start, end = {
- "sessions": (1, 99),
- "transactions": (100, 199),
- "spans": (400, 499),
- "escalating_issues": (500, 599),
- "profiles": (600, 699),
- "bundle_analysis": (700, 799),
- "metric_stats": (800, 899),
- }[parsed_mri.namespace]
- except KeyError:
- raise AssertionError(f"Unknown namespace: {parsed_mri.namespace}")
+ start, end = {
+ "sessions": (1, 99),
+ "transactions": (100, 199),
+ "spans": (400, 499),
+ "escalating_issues": (500, 599),
+ "profiles": (600, 699),
+ "bundle_analysis": (700, 799),
+ "metric_stats": (800, 899),
+ }[parsed_mri.namespace]
start += PREFIX
end += PREFIX
|
594eec1232b8dd9e4491f1275cdd1364a819e1ad
|
2021-11-30 05:21:19
|
NisanthanNanthakumar
|
feat(codeowners): Limit size of raw in ProjectCodeOwners (#30260)
| false
|
Limit size of raw in ProjectCodeOwners (#30260)
|
feat
|
diff --git a/src/sentry/api/endpoints/project_codeowners.py b/src/sentry/api/endpoints/project_codeowners.py
index 8b0c48d8733d11..fc33474e6b6de8 100644
--- a/src/sentry/api/endpoints/project_codeowners.py
+++ b/src/sentry/api/endpoints/project_codeowners.py
@@ -24,6 +24,9 @@
logger = logging.getLogger(__name__)
+# Max accepted string length of the CODEOWNERS file
+MAX_RAW_LENGTH = 100_000
+
def validate_association(
raw_items: Sequence[Union[UserEmail, ExternalActor]],
@@ -61,6 +64,16 @@ def validate(self, attrs: Mapping[str, Any]) -> Mapping[str, Any]:
if not attrs.get("raw", "").strip():
return attrs
+ # We want to limit `raw` to a reasonable length, so that people don't end up with values
+ # that are several megabytes large. To not break this functionality for existing customers
+ # we temporarily allow rows that already exceed this limit to still be updated.
+ # We do something similar with ProjectOwnership at the API level.
+ existing_raw = self.instance.raw if self.instance else ""
+ if len(attrs["raw"]) > MAX_RAW_LENGTH and len(existing_raw) <= MAX_RAW_LENGTH:
+ raise serializers.ValidationError(
+ {"raw": f"Raw needs to be <= {MAX_RAW_LENGTH} characters in length"}
+ )
+
# Ignore association errors and continue parsing CODEOWNERS for valid lines.
# Allow users to incrementally fix association errors; for CODEOWNERS with many external mappings.
associations, _ = ProjectCodeOwners.validate_codeowners_associations(
diff --git a/tests/sentry/api/endpoints/test_project_codeowners_details.py b/tests/sentry/api/endpoints/test_project_codeowners_details.py
index f498d10a0c65b1..07c42165f1ea84 100644
--- a/tests/sentry/api/endpoints/test_project_codeowners_details.py
+++ b/tests/sentry/api/endpoints/test_project_codeowners_details.py
@@ -1,4 +1,7 @@
+from unittest import mock
+
from django.urls import reverse
+from rest_framework.exceptions import ErrorDetail
from sentry.models import ProjectCodeOwners
from sentry.testutils import APITestCase
@@ -107,3 +110,43 @@ def test_codeowners_email_update(self):
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"
+
+ def test_codeowners_max_raw_length(self):
+ with mock.patch(
+ "sentry.api.endpoints.project_codeowners.MAX_RAW_LENGTH", len(self.data["raw"]) + 1
+ ):
+ data = {
+ "raw": f"# cool stuff comment\n*.js {self.user.email}\n# good comment"
+ }
+
+ with self.feature({"organizations:integrations-codeowners": True}):
+ response = self.client.put(self.url, data)
+ assert response.status_code == 400
+ assert response.data == {
+ "raw": [
+ ErrorDetail(
+ string=f"Raw needs to be <= {len(self.data['raw']) + 1} characters in length",
+ code="invalid",
+ )
+ ]
+ }
+
+ # Test that we allow this to be modified for existing large rows
+ code_mapping = self.create_code_mapping(project=self.project, stack_root="/")
+ codeowners = self.create_codeowners(
+ project=self.project,
+ code_mapping=code_mapping,
+ raw=f"*.py test@localhost #{self.team.slug}",
+ )
+ url = reverse(
+ "sentry-api-0-project-codeowners-details",
+ kwargs={
+ "organization_slug": self.organization.slug,
+ "project_slug": self.project.slug,
+ "codeowners_id": codeowners.id,
+ },
+ )
+ with self.feature({"organizations:integrations-codeowners": True}):
+ response = self.client.put(url, data)
+
+ assert ProjectCodeOwners.objects.get(id=codeowners.id).raw == data.get("raw")
|
6d04f63256cf9caf8be2de35f7b71771f8bb0add
|
2019-12-19 02:33:45
|
Alberto Leal
|
ref(apm): Remove Linked events tab (#16135)
| false
|
Remove Linked events tab (#16135)
|
ref
|
diff --git a/src/sentry/static/sentry/app/views/eventsV2/eventDetails/eventInterfaces.tsx b/src/sentry/static/sentry/app/views/eventsV2/eventDetails/eventInterfaces.tsx
index 7db2748b86a0a5..3eba62616a04fe 100644
--- a/src/sentry/static/sentry/app/views/eventsV2/eventDetails/eventInterfaces.tsx
+++ b/src/sentry/static/sentry/app/views/eventsV2/eventDetails/eventInterfaces.tsx
@@ -15,7 +15,6 @@ import NavTabs from 'app/components/navTabs';
import {objectIsEmpty, toTitleCase} from 'app/utils';
import {Event, Organization} from 'app/types';
-import LinkedEvents from './linkedEvents';
import EventView from '../eventView';
const OTHER_SECTIONS = {
@@ -68,15 +67,6 @@ const ActiveTab = (props: ActiveTabProps) => {
} else if (OTHER_SECTIONS[activeTab]) {
const Component = OTHER_SECTIONS[activeTab];
return <Component event={event} isShare={false} hideGuide />;
- } else if (activeTab === 'linked') {
- return (
- <LinkedEvents
- event={event}
- projectId={projectId}
- organization={organization}
- eventView={eventView}
- />
- );
} else {
/*eslint no-console:0*/
window.console &&
@@ -172,17 +162,6 @@ class EventInterfaces extends React.Component<
</li>
);
})}
- <li key="linked" className={activeTab === 'linked' ? 'active' : undefined}>
- <a
- href="#"
- onClick={evt => {
- evt.preventDefault();
- this.handleTabChange('linked');
- }}
- >
- {t('Linked')}
- </a>
- </li>
</NavTabs>
<ErrorBoundary message={t('Could not render event details')}>
<ActiveTab
diff --git a/src/sentry/static/sentry/app/views/eventsV2/eventDetails/linkedEvents.tsx b/src/sentry/static/sentry/app/views/eventsV2/eventDetails/linkedEvents.tsx
deleted file mode 100644
index 6eb5d364ab8eda..00000000000000
--- a/src/sentry/static/sentry/app/views/eventsV2/eventDetails/linkedEvents.tsx
+++ /dev/null
@@ -1,167 +0,0 @@
-import React from 'react';
-import styled from 'react-emotion';
-import get from 'lodash/get';
-
-import {getParams} from 'app/components/organizations/globalSelectionHeader/getParams';
-import {Organization, Event, Project} from 'app/types';
-import AsyncComponent from 'app/components/asyncComponent';
-import DateTime from 'app/components/dateTime';
-import Link from 'app/components/links/link';
-import ProjectBadge from 'app/components/idBadge/projectBadge';
-import {t} from 'app/locale';
-import space from 'app/styles/space';
-import theme from 'app/utils/theme';
-import withProjects from 'app/utils/withProjects';
-import {getTraceDateTimeRange} from 'app/components/events/interfaces/spans/utils.tsx';
-
-import {generateEventDetailsRoute, generateEventSlug} from './utils';
-import {SectionHeading} from '../styles';
-import EventView from '../eventView';
-
-type DiscoverResult = {
- id: string;
- 'project.name': string;
- 'event.type': string;
- title: string;
- transaction: string;
- timestamp: number;
-};
-
-type Props = {
- organization: Organization;
- projectId: string;
- projects: Project[];
- event: Event;
- eventView: EventView;
-} & AsyncComponent['props'];
-
-type State = {
- linkedEvents: {data: DiscoverResult[]};
-} & AsyncComponent['state'];
-
-class LinkedEvents extends AsyncComponent<Props, State> {
- getEndpoints(): [string, string, any][] {
- const {event, organization} = this.props;
- const endpoints: any = [];
-
- const trace = event.tags.find(tag => tag.key === 'trace');
- if (trace) {
- const {start, end} = getParams(
- getTraceDateTimeRange({
- start: get(event, 'startTimestamp', 0),
- end: get(event, 'endTimestamp', 0),
- })
- );
-
- endpoints.push([
- 'linkedEvents',
- `/organizations/${organization.slug}/eventsv2/`,
- {
- query: {
- field: [
- 'project.name',
- 'title',
- 'transaction',
- 'id',
- 'event.type',
- 'timestamp',
- ],
- sort: ['-timestamp'],
- query: `trace:${trace.value}`,
- start,
- end,
- },
- },
- ]);
- }
- return endpoints;
- }
-
- renderBody() {
- const {event, organization, projects, eventView} = this.props;
- const {linkedEvents} = this.state;
-
- const hasLinkedEvents =
- linkedEvents && linkedEvents.data && linkedEvents.data.length >= 1;
-
- return (
- <Section>
- <SectionHeading>{t('Linked Trace Events')}</SectionHeading>
- {!hasLinkedEvents ? (
- <StyledCard>{t('No linked events found.')}</StyledCard>
- ) : (
- linkedEvents.data.map((item: DiscoverResult) => {
- const eventSlug = generateEventSlug(item);
- const eventUrl = {
- pathname: generateEventDetailsRoute({
- eventSlug,
- orgSlug: organization.slug,
- }),
- query: eventView.generateQueryStringObject(),
- };
- const project = projects.find(p => p.slug === item['project.name']);
-
- return (
- <StyledCard key={item.id} isCurrent={event.id === item.id}>
- <StyledLink to={eventUrl} data-test-id="linked-event">
- <ProjectBadge project={project} avatarSize={14} />
- <div>{item.title ? item.title : item.transaction}</div>
- </StyledLink>
- <StyledDate>
- <DateTime date={item.timestamp} />
- </StyledDate>
- </StyledCard>
- );
- })
- )}
- </Section>
- );
- }
-}
-
-const Section = styled('div')`
- margin-bottom: ${space(2)};
-`;
-
-const StyledCard = styled('div')<{isCurrent?: boolean; theme?: any}>`
- display: flex;
- flex-direction: column;
- background: ${p => p.theme.white};
- align-items: center;
- font-size: ${p => p.theme.fontSizeMedium};
- border: 1px solid ${p => (p.isCurrent ? p.theme.purpleLight : p.theme.borderLight)};
- border-radius: ${p => p.theme.borderRadius};
- margin-bottom: ${space(1)};
- padding: ${space(1)} ${space(2)};
-
- @media (min-width: ${theme.breakpoints[3]}) {
- flex-direction: row;
- justify-content: space-between;
- }
-`;
-
-const StyledLink = styled(Link)`
- display: flex;
- flex-direction: column;
- width: 100%;
- overflow-wrap: break-word;
-
- @media (min-width: ${theme.breakpoints[3]}) {
- flex-direction: row;
- flex-grow: 1;
- }
-`;
-
-const StyledDate = styled('div')`
- width: 100%;
- color: ${p => p.theme.gray2};
- font-size: ${p => p.theme.fontSizeSmall};
-
- @media (min-width: ${theme.breakpoints[3]}) {
- width: auto;
- text-align: right;
- white-space: nowrap;
- }
-`;
-
-export default withProjects(LinkedEvents);
|
0c23014a554ddc59677cdaaad05f4dad826e9e56
|
2023-04-18 13:05:09
|
Priscila Oliveira
|
ref(source-maps): Remove old banner from issue details (#47387)
| false
|
Remove old banner from issue details (#47387)
|
ref
|
diff --git a/static/app/components/events/interfaces/crashContent/exception/content.tsx b/static/app/components/events/interfaces/crashContent/exception/content.tsx
index 70d6a6050b3a77..b89dd1045290e8 100644
--- a/static/app/components/events/interfaces/crashContent/exception/content.tsx
+++ b/static/app/components/events/interfaces/crashContent/exception/content.tsx
@@ -1,4 +1,4 @@
-import {Fragment, useContext} from 'react';
+import {useContext} from 'react';
import styled from '@emotion/styled';
import ErrorBoundary from 'sentry/components/errorBoundary';
@@ -13,7 +13,6 @@ import {defined} from 'sentry/utils';
import {OrganizationContext} from 'sentry/views/organizationContext';
import {Mechanism} from './mechanism';
-import {SetupSourceMapsAlert} from './setupSourceMapsAlert';
import {SourceMapDebug} from './sourceMapDebug';
import StackTrace from './stackTrace';
import {debugFramesEnabled, getUniqueFilesFromException} from './useSourceMapDebug';
@@ -92,12 +91,9 @@ export function Content({
<Mechanism data={exc.mechanism} meta={meta?.[excIdx]?.mechanism} />
)}
<ErrorBoundary mini>
- <Fragment>
- {!shouldDebugFrames && excIdx === 0 && <SetupSourceMapsAlert event={event} />}
- {hasSourcemapDebug && (
- <SourceMapDebug debugFrames={debugFrames} event={event} />
- )}
- </Fragment>
+ {hasSourcemapDebug && (
+ <SourceMapDebug debugFrames={debugFrames} event={event} />
+ )}
</ErrorBoundary>
<StackTrace
data={
diff --git a/static/app/components/events/interfaces/crashContent/exception/setupSourceMapsAlert.spec.tsx b/static/app/components/events/interfaces/crashContent/exception/setupSourceMapsAlert.spec.tsx
deleted file mode 100644
index ff969bd46ca226..00000000000000
--- a/static/app/components/events/interfaces/crashContent/exception/setupSourceMapsAlert.spec.tsx
+++ /dev/null
@@ -1,192 +0,0 @@
-import cloneDeep from 'lodash/cloneDeep';
-
-import {initializeOrg} from 'sentry-test/initializeOrg';
-import {render, screen} from 'sentry-test/reactTestingLibrary';
-
-import {Event} from 'sentry/types';
-
-import {SetupSourceMapsAlert} from './setupSourceMapsAlert';
-
-const alertText = 'Sentry can un-minify your code to show you more readable stack traces';
-
-function modifyEventFrames(event: Event, modify: any): Event {
- const modifiedEvent = cloneDeep(event);
- modifiedEvent.entries[0].data.values[0].stacktrace.frames =
- event.entries[0].data.values[0].stacktrace.frames.map(frame => ({
- ...frame,
- ...modify,
- }));
- return modifiedEvent;
-}
-
-describe('SetupSourceMapsAlert', function () {
- const {organization, router} = initializeOrg({
- ...initializeOrg(),
- organization: {...initializeOrg().organization, features: ['source-maps-cta']},
- router: {
- ...initializeOrg().router,
- location: {
- ...initializeOrg().router.location,
- query: {project: '1'},
- },
- },
- });
-
- it('does NOT show alert if javascript platform and source maps found', function () {
- const event = TestStubs.ExceptionWithRawStackTrace();
-
- render(<SetupSourceMapsAlert event={event} />, {
- organization,
- router,
- });
-
- expect(screen.queryByText(alertText)).not.toBeInTheDocument();
- });
-
- it('does NOT show alert if all filenames are anonymous', function () {
- const event = modifyEventFrames(
- TestStubs.EventStacktraceException({
- platform: 'javascript',
- }),
- {filename: '<anonymous>'}
- );
-
- render(<SetupSourceMapsAlert event={event} />, {
- organization,
- router,
- });
-
- expect(screen.queryByText(alertText)).not.toBeInTheDocument();
- });
-
- it('does NOT show alert if all function names are on the blocklist', function () {
- const event = modifyEventFrames(
- TestStubs.EventStacktraceException({
- platform: 'javascript',
- }),
- {function: '@webkit-masked-url'}
- );
-
- render(<SetupSourceMapsAlert event={event} />, {
- organization,
- router,
- });
-
- expect(screen.queryByText(alertText)).not.toBeInTheDocument();
- });
-
- it('does NOT show alert if all absolute paths do not have a file extension', function () {
- const event = modifyEventFrames(
- TestStubs.EventStacktraceException({
- platform: 'javascript',
- }),
- {absPath: 'https://sentry.io/'}
- );
-
- render(<SetupSourceMapsAlert event={event} />, {
- organization,
- router,
- });
-
- expect(screen.queryByText(alertText)).not.toBeInTheDocument();
- });
-
- it('shows alert if javascript platform and source maps not found', function () {
- const event = TestStubs.EventStacktraceException({platform: 'javascript'});
-
- render(<SetupSourceMapsAlert event={event} />, {
- organization,
- router,
- });
-
- expect(screen.getByText(alertText)).toBeInTheDocument();
-
- expect(screen.getByRole('link', {name: 'Upload Source Maps'})).toHaveAttribute(
- 'href',
- 'https://docs.sentry.io/platforms/javascript/sourcemaps/'
- );
- });
-
- it('show documentation for react according to the sdk name', function () {
- const event = TestStubs.EventStacktraceException({
- sdk: {name: 'sentry.javascript.react'},
- });
-
- render(<SetupSourceMapsAlert event={event} />, {
- organization,
- router,
- });
-
- expect(screen.getByText(alertText)).toBeInTheDocument();
-
- expect(screen.getByRole('link', {name: 'Upload Source Maps'})).toHaveAttribute(
- 'href',
- 'https://docs.sentry.io/platforms/javascript/guides/react/sourcemaps/'
- );
- });
-
- it('show documentation for react according to the event platform', function () {
- const event = TestStubs.EventStacktraceException({
- platform: 'react',
- sdk: {name: 'sentry.javascript.browser'},
- });
-
- render(<SetupSourceMapsAlert event={event} />, {
- organization,
- router,
- });
-
- expect(screen.getByText(alertText)).toBeInTheDocument();
-
- expect(screen.getByRole('link', {name: 'Upload Source Maps'})).toHaveAttribute(
- 'href',
- 'https://docs.sentry.io/platforms/javascript/guides/react/sourcemaps/'
- );
- });
-
- it('show generic documentation if doc link not available', function () {
- const event = TestStubs.EventStacktraceException({
- platform: 'unity',
- });
-
- render(<SetupSourceMapsAlert event={event} />, {
- organization,
- router,
- });
-
- expect(screen.getByText(alertText)).toBeInTheDocument();
-
- expect(screen.getByRole('link', {name: 'Upload Source Maps'})).toHaveAttribute(
- 'href',
- 'https://docs.sentry.io/platforms/javascript/sourcemaps/'
- );
- });
-
- it('show localhost copy', function () {
- const event = TestStubs.EventStacktraceException({
- platform: 'unity',
- tags: [
- {
- key: 'url',
- value: 'http://localhost:3000',
- },
- ],
- });
-
- render(<SetupSourceMapsAlert event={event} />, {
- organization,
- router,
- });
-
- expect(
- screen.getByText(
- 'In production, you might have minified JS code that makes stack traces hard to read. Sentry can un-minify it for you'
- )
- ).toBeInTheDocument();
-
- expect(screen.getByRole('link', {name: 'Upload Source Maps'})).toHaveAttribute(
- 'href',
- 'https://docs.sentry.io/platforms/javascript/sourcemaps/'
- );
- });
-});
diff --git a/static/app/components/events/interfaces/crashContent/exception/setupSourceMapsAlert.tsx b/static/app/components/events/interfaces/crashContent/exception/setupSourceMapsAlert.tsx
deleted file mode 100644
index de89b63800479e..00000000000000
--- a/static/app/components/events/interfaces/crashContent/exception/setupSourceMapsAlert.tsx
+++ /dev/null
@@ -1,183 +0,0 @@
-import {Alert} from 'sentry/components/alert';
-import {isEventFromBrowserJavaScriptSDK} from 'sentry/components/events/interfaces/spans/utils';
-import ExternalLink from 'sentry/components/links/externalLink';
-import {PlatformKey, sourceMaps} from 'sentry/data/platformCategories';
-import {t} from 'sentry/locale';
-import {
- EntryException,
- EntryType,
- Event,
- EventTransaction,
- Organization,
-} from 'sentry/types';
-import {defined} from 'sentry/utils';
-import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
-import {eventHasSourceMaps} from 'sentry/utils/events';
-import useOrganization from 'sentry/utils/useOrganization';
-import useRouter from 'sentry/utils/useRouter';
-
-import {isFrameFilenamePathlike} from './utils';
-
-// This list must always be updated with the documentation.
-// Ideally it would be nice if we could send a request validating that this URL exists,
-// but due to CORS this is not possible at the moment
-const sourceMapsDocLinksPerPlatform = {
- react: 'https://docs.sentry.io/platforms/javascript/guides/react/sourcemaps/',
- electron: 'https://docs.sentry.io/platforms/javascript/guides/electron/sourcemaps/',
- cordova: 'https://docs.sentry.io/platforms/javascript/guides/cordova/sourcemaps/',
- 'javascript-angularjs':
- 'https://docs.sentry.io/platforms/javascript/guides/angular/sourcemaps/',
- 'javascript-angular':
- 'https://docs.sentry.io/platforms/javascript/guides/angular/sourcemaps/',
- 'javascript-ember':
- 'https://docs.sentry.io/platforms/javascript/guides/ember/sourcemaps/',
- 'javascript-gatsby':
- 'https://docs.sentry.io/platforms/javascript/guides/gatsby/sourcemaps/',
- 'javascript-vue': 'https://docs.sentry.io/platforms/javascript/guides/vue/sourcemaps/',
- 'javascript-nextjs':
- 'https://docs.sentry.io/platforms/javascript/guides/nextjs/sourcemaps/',
- 'javascript-remix':
- 'https://docs.sentry.io/platforms/javascript/guides/remix/sourcemaps/',
- 'javascript-svelte':
- 'https://docs.sentry.io/platforms/javascript/guides/svelte/sourcemaps/',
-};
-
-function isLocalhost(url?: string) {
- if (!url) {
- return false;
- }
-
- return url.includes('localhost') || url.includes('127.0.0.1');
-}
-
-export function shouldDisplaySetupSourceMapsAlert(
- organization: Organization,
- projectId: string | undefined,
- event: Event | undefined
-): boolean {
- if (!defined(projectId) || !defined(event)) {
- return false;
- }
-
- if (!organization.features?.includes('source-maps-cta')) {
- return false;
- }
-
- const eventPlatform = event?.platform ?? 'other';
- const eventFromBrowserJavaScriptSDK = isEventFromBrowserJavaScriptSDK(
- event as EventTransaction
- );
- const exceptionEntry = event?.entries.find(
- entry => entry.type === EntryType.EXCEPTION
- ) as EntryException | undefined; // could there be more than one? handling only the first one for now
- const exceptionEntryValues = exceptionEntry?.data.values;
-
- // We would like to filter out all platforms that do not have the concept of source maps
- if (
- !eventFromBrowserJavaScriptSDK &&
- !sourceMaps.includes(eventPlatform as PlatformKey)
- ) {
- return false;
- }
-
- // If the event already has source maps, we do not want to show this alert
- if (eventHasSourceMaps(event)) {
- return false;
- }
-
- // If event has no exception, we do not want to show this alert
- if (!exceptionEntry || exceptionEntryValues?.length === 0) {
- return false;
- }
-
- // If the event does not have exception stacktrace, we do not want to show this alert
- if (
- exceptionEntryValues?.every(
- exception => !exception.stacktrace && !exception.rawStacktrace
- )
- ) {
- return false;
- }
-
- // If there are no in-app frames, we do not want to show this alert
- if (
- exceptionEntryValues?.every(exception =>
- exception.stacktrace?.frames?.every(frame => !frame.inApp)
- )
- ) {
- return false;
- }
-
- if (
- exceptionEntryValues?.every(exception =>
- exception.stacktrace?.frames?.every(frame => isFrameFilenamePathlike(frame))
- )
- ) {
- return false;
- }
-
- // Otherwise, show the alert
- return true;
-}
-
-type Props = {
- event: Event;
-};
-
-export function SetupSourceMapsAlert({event}: Props) {
- const organization = useOrganization();
- const router = useRouter();
- const projectId = router.location.query.project;
- const eventPlatform = event.platform ?? 'other';
- const eventFromBrowserJavaScriptSDK = isEventFromBrowserJavaScriptSDK(
- event as EventTransaction
- );
-
- if (!shouldDisplaySetupSourceMapsAlert(organization, projectId, event)) {
- return null;
- }
-
- const url =
- event.entries?.find(entry => entry.type === EntryType.REQUEST)?.data?.url ??
- event.tags.find(tag => tag.key === 'url')?.value;
-
- const platform = eventFromBrowserJavaScriptSDK
- ? event.sdk?.name?.substring('sentry.javascript.'.length) ?? 'other'
- : eventPlatform;
-
- // If there is no documentation defined for the sdk and platform, we fall back to the generic one
- const docUrl =
- sourceMapsDocLinksPerPlatform[platform] ??
- sourceMapsDocLinksPerPlatform[eventPlatform] ??
- 'https://docs.sentry.io/platforms/javascript/sourcemaps/';
-
- return (
- <Alert
- type="info"
- showIcon
- trailingItems={
- <ExternalLink
- href={docUrl}
- onClick={() => {
- trackAdvancedAnalyticsEvent(
- 'issue_group_details.stack_traces.setup_source_maps_alert.clicked',
- {
- organization,
- project_id: projectId,
- platform,
- }
- );
- }}
- >
- {t('Upload Source Maps')}
- </ExternalLink>
- }
- >
- {isLocalhost(url)
- ? t(
- 'In production, you might have minified JS code that makes stack traces hard to read. Sentry can un-minify it for you'
- )
- : t('Sentry can un-minify your code to show you more readable stack traces')}
- </Alert>
- );
-}
diff --git a/static/app/views/issueDetails/groupDetails.tsx b/static/app/views/issueDetails/groupDetails.tsx
index 793dd245d08ceb..d68fb7c1e133f9 100644
--- a/static/app/views/issueDetails/groupDetails.tsx
+++ b/static/app/views/issueDetails/groupDetails.tsx
@@ -6,7 +6,6 @@ import * as PropTypes from 'prop-types';
import {fetchOrganizationEnvironments} from 'sentry/actionCreators/environments';
import {Client} from 'sentry/api';
-import {shouldDisplaySetupSourceMapsAlert} from 'sentry/components/events/interfaces/crashContent/exception/setupSourceMapsAlert';
import LoadingError from 'sentry/components/loadingError';
import LoadingIndicator from 'sentry/components/loadingIndicator';
import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
@@ -148,7 +147,7 @@ class GroupDetails extends Component<Props, State> {
trackView(project: Project) {
const {group, event} = this.state;
- const {location, organization, router} = this.props;
+ const {location} = this.props;
const {alert_date, alert_rule_id, alert_type, ref_fallback, stream_index, query} =
location.query;
@@ -164,11 +163,6 @@ class GroupDetails extends Component<Props, State> {
typeof alert_date === 'string' ? getUtcDateString(Number(alert_date)) : undefined,
alert_rule_id: typeof alert_rule_id === 'string' ? alert_rule_id : undefined,
alert_type: typeof alert_type === 'string' ? alert_type : undefined,
- has_setup_source_maps_alert: shouldDisplaySetupSourceMapsAlert(
- organization,
- router.location.query.project,
- event
- ),
ref_fallback,
// Will be updated by StacktraceLink if there is a stacktrace link
stacktrace_link_viewed: false,
|
3df2c9d29f4d280b1fbabc7dfd8c41cadecc0d74
|
2024-09-27 01:06:28
|
George Gritsouk
|
feat(dashboards): Improve `apdex()` rendering (#78211)
| false
|
Improve `apdex()` rendering (#78211)
|
feat
|
diff --git a/static/app/utils/discover/fieldRenderers.tsx b/static/app/utils/discover/fieldRenderers.tsx
index 06a5c26093756f..b7c962af37f77f 100644
--- a/static/app/utils/discover/fieldRenderers.tsx
+++ b/static/app/utils/discover/fieldRenderers.tsx
@@ -45,6 +45,7 @@ import {
import {getShortEventId} from 'sentry/utils/events';
import {formatRate} from 'sentry/utils/formatters';
import getDynamicText from 'sentry/utils/getDynamicText';
+import {formatApdex} from 'sentry/utils/number/formatApdex';
import {formatFloat} from 'sentry/utils/number/formatFloat';
import {formatPercentage} from 'sentry/utils/number/formatPercentage';
import toPercent from 'sentry/utils/number/toPercent';
@@ -339,6 +340,7 @@ type SpecialField = {
};
type SpecialFields = {
+ 'apdex()': SpecialField;
attachments: SpecialField;
'count_unique(user)': SpecialField;
'error.handled': SpecialField;
@@ -376,6 +378,18 @@ const RightAlignedContainer = styled('span')`
const SPECIAL_FIELDS: SpecialFields = {
// This is a custom renderer for a field outside discover
// TODO - refactor code and remove from this file or add ability to query for attachments in Discover
+ 'apdex()': {
+ sortField: 'apdex()',
+ renderFunc: data => {
+ const field = 'apdex()';
+
+ return (
+ <NumberContainer>
+ {typeof data[field] === 'number' ? formatApdex(data[field]) : emptyValue}
+ </NumberContainer>
+ );
+ },
+ },
attachments: {
sortField: null,
renderFunc: (data, {organization, projectSlug}) => {
diff --git a/static/app/utils/number/formatApdex.spec.tsx b/static/app/utils/number/formatApdex.spec.tsx
new file mode 100644
index 00000000000000..baa3efc8a53413
--- /dev/null
+++ b/static/app/utils/number/formatApdex.spec.tsx
@@ -0,0 +1,15 @@
+import {formatApdex} from 'sentry/utils/number/formatApdex';
+
+describe('formatApdex', function () {
+ it.each([
+ [0, '0'],
+ [0.2, '0.200'],
+ [0.61, '0.610'],
+ [0.781, '0.781'],
+ [0.771231, '0.771'],
+ [0.99999, '0.999'],
+ [1.0, '1'],
+ ])('%s', (value, expected) => {
+ expect(formatApdex(value)).toEqual(expected);
+ });
+});
diff --git a/static/app/utils/number/formatApdex.tsx b/static/app/utils/number/formatApdex.tsx
new file mode 100644
index 00000000000000..089c0062e1af46
--- /dev/null
+++ b/static/app/utils/number/formatApdex.tsx
@@ -0,0 +1,15 @@
+export function formatApdex(value: number) {
+ if (value === 0) {
+ return '0';
+ }
+
+ if (value === 1) {
+ return '1';
+ }
+
+ return value.toLocaleString(undefined, {
+ minimumFractionDigits: 3,
+ maximumFractionDigits: 3,
+ roundingMode: 'trunc',
+ });
+}
|
742df0a46d7574d0f9cb248a7cdc8446ee4c5dee
|
2022-09-14 20:01:43
|
Priscila Oliveira
|
ref(advanced-data-scrubbing): Open rule edition modal via url - (#38734)
| false
|
Open rule edition modal via url - (#38734)
|
ref
|
diff --git a/static/app/components/events/interfaces/crashContent/exception/content.spec.tsx b/static/app/components/events/interfaces/crashContent/exception/content.spec.tsx
index 2bc18cdb33d741..252d41033eb376 100644
--- a/static/app/components/events/interfaces/crashContent/exception/content.spec.tsx
+++ b/static/app/components/events/interfaces/crashContent/exception/content.spec.tsx
@@ -148,12 +148,12 @@ describe('Exception Content', function () {
})
).toHaveAttribute(
'href',
- '/settings/org-slug/projects/project-slug/security-and-privacy/#advanced-data-scrubbing'
+ '/settings/org-slug/projects/project-slug/security-and-privacy/advanced-data-scrubbing/0/'
);
expect(screen.getByRole('link', {name: 'project-slug'})).toHaveAttribute(
'href',
- '/settings/org-slug/projects/project-slug/security-and-privacy/#advanced-data-scrubbing'
+ '/settings/org-slug/projects/project-slug/'
);
});
});
diff --git a/static/app/components/events/interfaces/frame/frameVariables.spec.tsx b/static/app/components/events/interfaces/frame/frameVariables.spec.tsx
index 41138c4ab2d259..c6ec8c41eb493e 100644
--- a/static/app/components/events/interfaces/frame/frameVariables.spec.tsx
+++ b/static/app/components/events/interfaces/frame/frameVariables.spec.tsx
@@ -98,12 +98,12 @@ describe('Frame Variables', function () {
})
).toHaveAttribute(
'href',
- '/settings/org-slug/projects/project-slug/security-and-privacy/#advanced-data-scrubbing'
+ '/settings/org-slug/projects/project-slug/security-and-privacy/advanced-data-scrubbing/0/'
);
expect(screen.getByRole('link', {name: 'project-slug'})).toHaveAttribute(
'href',
- '/settings/org-slug/projects/project-slug/security-and-privacy/#advanced-data-scrubbing'
+ '/settings/org-slug/projects/project-slug/'
);
});
});
diff --git a/static/app/components/events/interfaces/message.spec.tsx b/static/app/components/events/interfaces/message.spec.tsx
index 4f3560324a3d94..92b8dd0531a14e 100644
--- a/static/app/components/events/interfaces/message.spec.tsx
+++ b/static/app/components/events/interfaces/message.spec.tsx
@@ -69,12 +69,12 @@ describe('Message entry', function () {
})
).toHaveAttribute(
'href',
- '/settings/org-slug/security-and-privacy/#advanced-data-scrubbing'
+ '/settings/org-slug/security-and-privacy/advanced-data-scrubbing/0/'
);
expect(screen.getByRole('link', {name: 'org-slug'})).toHaveAttribute(
'href',
- '/settings/org-slug/security-and-privacy/#advanced-data-scrubbing'
+ '/settings/org-slug/'
);
});
});
diff --git a/static/app/components/events/meta/annotatedText/utils.tsx b/static/app/components/events/meta/annotatedText/utils.tsx
index 8360bbb55e6dde..6fad0b0cf07aea 100644
--- a/static/app/components/events/meta/annotatedText/utils.tsx
+++ b/static/app/components/events/meta/annotatedText/utils.tsx
@@ -2,7 +2,6 @@ import styled from '@emotion/styled';
import Link from 'sentry/components/links/link';
import {tct} from 'sentry/locale';
-import space from 'sentry/styles/space';
import {ChunkType, Organization, Project} from 'sentry/types';
import {convertRelayPiiConfig} from 'sentry/views/settings/components/dataScrubbing/convertRelayPiiConfig';
import {getRuleDescription} from 'sentry/views/settings/components/dataScrubbing/utils';
@@ -35,10 +34,9 @@ export function getTooltipText({
// default data scrubbing
if (KNOWN_RULES[rule_id]) {
- return tct('[method] because of the PII rule [break][rule-description]', {
+ return tct('[method] because of the PII rule [ruleDescription]', {
method,
- break: <br />,
- 'rule-description': KNOWN_RULES[rule_id],
+ ruleDescription: KNOWN_RULES[rule_id],
});
}
@@ -48,11 +46,14 @@ export function getTooltipText({
if (level === 'organization') {
// if organization is not available, fall back to the default message
if (!organization) {
- return tct('[method] because of the PII rule [break][rule-description]', {
- method,
- break: <br />,
- 'rule-description': rule_id,
- });
+ return (
+ <Wrapper>
+ {tct('[method] because of the PII rule [ruleDescription]', {
+ method,
+ ruleDescription: rule_id,
+ })}
+ </Wrapper>
+ );
}
const rules = convertRelayPiiConfig(organization?.relayPiiConfig);
@@ -61,27 +62,18 @@ export function getTooltipText({
return (
<Wrapper>
{tct(
- '[method] because of the PII rule [break][rule-description] in the settings of the organization [break][slug]',
+ '[method] because of the PII rule [ruleDescription] in the settings of the organization [organizationSlug]',
{
method,
- break: <br />,
- 'rule-description': (
- <RuleDescription>
- <Link
- to={`/settings/${organization.slug}/security-and-privacy/#advanced-data-scrubbing`}
- >
- {rule ? getRuleDescription(rule) : ruleId}
- </Link>
- </RuleDescription>
+ ruleDescription: (
+ <Link
+ to={`/settings/${organization.slug}/security-and-privacy/advanced-data-scrubbing/${ruleId}/`}
+ >
+ {rule ? getRuleDescription(rule) : ruleId}
+ </Link>
),
- slug: (
- <Slug>
- <Link
- to={`/settings/${organization.slug}/security-and-privacy/#advanced-data-scrubbing`}
- >
- {organization.slug}
- </Link>
- </Slug>
+ organizationSlug: (
+ <Link to={`/settings/${organization.slug}/`}>{organization.slug}</Link>
),
}
)}
@@ -91,52 +83,43 @@ export function getTooltipText({
// if project and organization are not available, fall back to the default message
if (!project || !organization) {
- return tct('[method] because of the PII rule [break][rule-description]', {
- method,
- break: <br />,
- 'rule-description': rule_id,
- });
+ return (
+ <Wrapper>
+ {tct('[method] because of the PII rule [ruleDescription]', {
+ method,
+ ruleDescription: rule_id,
+ })}
+ </Wrapper>
+ );
}
const rules = convertRelayPiiConfig(project?.relayPiiConfig);
const rule = rules.find(({id}) => String(id) === ruleId);
- return tct(
- '[method] because of the PII rule [break][rule-description] in the settings of the project [break][slug]',
- {
- method,
- break: <br />,
- 'rule-description': (
- <RuleDescription>
- <Link
- to={`/settings/${organization.slug}/projects/${project.slug}/security-and-privacy/#advanced-data-scrubbing`}
- >
- {rule ? getRuleDescription(rule) : ruleId}
- </Link>
- </RuleDescription>
- ),
- slug: (
- <Slug>
- <Link
- to={`/settings/${organization.slug}/projects/${project?.slug}/security-and-privacy/#advanced-data-scrubbing`}
- >
- {project.slug}
- </Link>
- </Slug>
- ),
- }
+ return (
+ <Wrapper>
+ {tct(
+ '[method] because of the PII rule [ruleDescription] in the settings of the project [projectSlug]',
+ {
+ method,
+ ruleDescription: (
+ <Link
+ to={`/settings/${organization.slug}/projects/${project.slug}/security-and-privacy/advanced-data-scrubbing/${ruleId}/`}
+ >
+ {rule ? getRuleDescription(rule) : ruleId}
+ </Link>
+ ),
+ projectSlug: (
+ <Link to={`/settings/${organization.slug}/projects/${project?.slug}/`}>
+ {project.slug}
+ </Link>
+ ),
+ }
+ )}
+ </Wrapper>
);
}
const Wrapper = styled('div')`
- display: grid;
- gap: ${space(0.5)};
-`;
-
-const RuleDescription = styled('div')`
- margin: ${space(0.5)} 0;
-`;
-
-const Slug = styled('div')`
- margin-top: ${space(0.5)};
+ line-height: ${p => p.theme.text.lineHeightBody};
`;
diff --git a/static/app/data/forms/organizationSecurityAndPrivacyGroups.tsx b/static/app/data/forms/organizationSecurityAndPrivacyGroups.tsx
index 56c2ef348a8c8c..742ffee056aebc 100644
--- a/static/app/data/forms/organizationSecurityAndPrivacyGroups.tsx
+++ b/static/app/data/forms/organizationSecurityAndPrivacyGroups.tsx
@@ -18,6 +18,9 @@ export default [
type: 'boolean',
label: t('Require Two-Factor Authentication'),
help: t('Require and enforce two-factor authentication for all members'),
+ 'aria-label': t(
+ 'Enable to require and enforce two-factor authentication for all members'
+ ),
confirm: {
true: t(
'This will remove all members without two-factor authentication' +
@@ -104,6 +107,7 @@ export default [
label: t('Allow Join Requests'),
help: t('Allow users to request to join your organization'),
+ 'aria-label': t('Enable to allow users to request to join your organization'),
confirm: {
true: t(
'Are you sure you want to allow users to request to join your organization?'
@@ -121,6 +125,7 @@ export default [
type: 'boolean',
label: t('Require Data Scrubber'),
help: t('Require server-side data scrubbing be enabled for all projects'),
+ 'aria-label': t('Enable server-side data scrubbing'),
confirm: {
false: t(
'Disabling this can have privacy implications for ALL projects, are you sure you want to continue?'
@@ -134,6 +139,9 @@ export default [
help: t(
'Require the default scrubbers be applied to prevent things like passwords and credit cards from being stored for all projects'
),
+ 'aria-label': t(
+ 'Enable to apply default scrubbers to prevent things like passwords and credit cards from being stored'
+ ),
confirm: {
false: t(
'Disabling this can have privacy implications for ALL projects, are you sure you want to continue?'
@@ -152,6 +160,9 @@ export default [
help: t(
'Additional field names to match against when scrubbing data for all projects. Separate multiple entries with a newline.'
),
+ 'aria-label': t(
+ 'Enter additional field names to match against when scrubbing data for all projects. Separate multiple entries with a newline.'
+ ),
extraHelp: t(
'Note: These fields will be used in addition to project specific fields.'
),
@@ -170,6 +181,9 @@ export default [
help: t(
'Field names which data scrubbers should ignore. Separate multiple entries with a newline.'
),
+ 'aria-label': t(
+ 'Enter field names which data scrubbers should ignore. Separate multiple entries with a newline.'
+ ),
extraHelp: t(
'Note: These fields will be used in addition to project specific fields'
),
@@ -183,6 +197,9 @@ export default [
help: t(
'Preventing IP addresses from being stored for new events on all projects'
),
+ 'aria-label': t(
+ 'Enable to prevent IP addresses from being stored for new events'
+ ),
confirm: {
false: t(
'Disabling this can have privacy implications for ALL projects, are you sure you want to continue?'
diff --git a/static/app/data/forms/projectSecurityAndPrivacyGroups.tsx b/static/app/data/forms/projectSecurityAndPrivacyGroups.tsx
index 5d462e596e4a33..6c5f76ed2deaae 100644
--- a/static/app/data/forms/projectSecurityAndPrivacyGroups.tsx
+++ b/static/app/data/forms/projectSecurityAndPrivacyGroups.tsx
@@ -66,6 +66,7 @@ export default [
disabled: hasOrgOverride,
disabledReason: ORG_DISABLED_REASON,
help: t('Enable server-side data scrubbing'),
+ 'aria-label': t('Enable server-side data scrubbing'),
// `props` are the props given to FormField
setValue: (val, props) =>
(props.organization && props.organization[props.name]) || val,
@@ -82,6 +83,9 @@ export default [
help: t(
'Apply default scrubbers to prevent things like passwords and credit cards from being stored'
),
+ 'aria-label': t(
+ 'Enable to apply default scrubbers to prevent things like passwords and credit cards from being stored'
+ ),
// `props` are the props given to FormField
setValue: (val, props) =>
(props.organization && props.organization[props.name]) || val,
@@ -99,6 +103,9 @@ export default [
(props.organization && props.organization[props.name]) || val,
label: t('Prevent Storing of IP Addresses'),
help: t('Preventing IP addresses from being stored for new events'),
+ 'aria-label': t(
+ 'Enable to prevent IP addresses from being stored for new events'
+ ),
confirm: {
false: t('Are you sure you want to disable scrubbing IP addresses?'),
},
@@ -115,6 +122,9 @@ export default [
help: t(
'Additional field names to match against when scrubbing data. Separate multiple entries with a newline'
),
+ 'aria-label': t(
+ 'Enter additional field names to match against when scrubbing data. Separate multiple entries with a newline'
+ ),
getValue: val => extractMultilineFields(val),
setValue: val => convertMultilineFieldValue(val),
},
@@ -130,6 +140,9 @@ export default [
help: t(
'Field names which data scrubbers should ignore. Separate multiple entries with a newline'
),
+ 'aria-label': t(
+ 'Enter field names which data scrubbers should ignore. Separate multiple entries with a newline'
+ ),
getValue: val => extractMultilineFields(val),
setValue: val => convertMultilineFieldValue(val),
},
diff --git a/static/app/routes.tsx b/static/app/routes.tsx
index cbbb2c47905cb5..e33be83a67d2d0 100644
--- a/static/app/routes.tsx
+++ b/static/app/routes.tsx
@@ -413,11 +413,19 @@ function buildRoutes() {
name={t('Data Forwarding')}
component={make(() => import('sentry/views/settings/projectDataForwarding'))}
/>
- <Route
- path="security-and-privacy/"
- name={t('Security & Privacy')}
- component={make(() => import('sentry/views/settings/projectSecurityAndPrivacy'))}
- />
+ <Route path="security-and-privacy/" name={t('Security & Privacy')}>
+ <IndexRoute
+ component={make(
+ () => import('sentry/views/settings/projectSecurityAndPrivacy')
+ )}
+ />
+ <Route
+ path="advanced-data-scrubbing/:scrubbingId/"
+ component={make(
+ () => import('sentry/views/settings/projectSecurityAndPrivacy')
+ )}
+ />
+ </Route>
<Route
path="debug-symbols/"
name={t('Debug Information Files')}
@@ -658,13 +666,20 @@ function buildRoutes() {
() => import('sentry/views/settings/organizationGeneralSettings')
)}
/>
- <Route
- path="security-and-privacy/"
- name={t('Security & Privacy')}
- component={make(
- () => import('sentry/views/settings/organizationSecurityAndPrivacy')
- )}
- />
+ <Route path="security-and-privacy/" name={t('Security & Privacy')}>
+ <IndexRoute
+ component={make(
+ () => import('sentry/views/settings/organizationSecurityAndPrivacy')
+ )}
+ />
+ <Route
+ path="advanced-data-scrubbing/:scrubbingId/"
+ component={make(
+ () => import('sentry/views/settings/organizationSecurityAndPrivacy')
+ )}
+ />
+ </Route>
+
<Route name={t('Teams')} path="teams/">
<IndexRoute
component={make(() => import('sentry/views/settings/organizationTeams'))}
diff --git a/static/app/utils.tsx b/static/app/utils.tsx
index 98b908d0afa974..bc7ff60a20421b 100644
--- a/static/app/utils.tsx
+++ b/static/app/utils.tsx
@@ -231,7 +231,7 @@ export function parseRepo<T>(repo: T): T {
* Converts a multi-line textarea input value into an array,
* eliminating empty lines
*/
-export function extractMultilineFields(value: string): Array<string> {
+export function extractMultilineFields(value: string): string[] {
return value
.split('\n')
.map(f => trim(f))
@@ -241,7 +241,7 @@ export function extractMultilineFields(value: string): Array<string> {
/**
* If the value is of type Array, converts it to type string, keeping the line breaks, if there is any
*/
-export function convertMultilineFieldValue<T extends string | Array<string>>(
+export function convertMultilineFieldValue<T extends string | string[]>(
value: T
): string {
if (Array.isArray(value)) {
diff --git a/static/app/views/settings/components/dataScrubbing/content.spec.tsx b/static/app/views/settings/components/dataScrubbing/content.spec.tsx
deleted file mode 100644
index 18b27629193669..00000000000000
--- a/static/app/views/settings/components/dataScrubbing/content.spec.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import {render, screen} from 'sentry-test/reactTestingLibrary';
-
-import Content from 'sentry/views/settings/components/dataScrubbing/content';
-import {convertRelayPiiConfig} from 'sentry/views/settings/components/dataScrubbing/convertRelayPiiConfig';
-
-describe('Content', function () {
- it('default empty', function () {
- render(<Content rules={[]} onEditRule={jest.fn()} onDeleteRule={jest.fn()} />);
-
- expect(screen.getByText('You have no data scrubbing rules')).toBeInTheDocument();
- });
-
- it('render rules', function () {
- render(
- <Content
- rules={convertRelayPiiConfig(
- JSON.stringify(TestStubs.DataScrubbingRelayPiiConfig())
- )}
- onEditRule={jest.fn()}
- onDeleteRule={jest.fn()}
- />
- );
-
- expect(screen.getAllByRole('button', {name: 'Edit Rule'})).toHaveLength(3);
- });
-});
diff --git a/static/app/views/settings/components/dataScrubbing/content.tsx b/static/app/views/settings/components/dataScrubbing/content.tsx
deleted file mode 100644
index 1913c2b542e6ca..00000000000000
--- a/static/app/views/settings/components/dataScrubbing/content.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import EmptyMessage from 'sentry/components/emptyMessage';
-import {IconWarning} from 'sentry/icons';
-import {t} from 'sentry/locale';
-
-import Rules from './rules';
-import {Rule} from './types';
-
-type Props = {
- onDeleteRule: (rule: Rule['id']) => () => void;
- onEditRule: (rule: Rule['id']) => () => void;
- rules: Array<Rule>;
- disabled?: boolean;
-};
-
-const Content = ({rules, disabled, onDeleteRule, onEditRule}: Props) => {
- if (rules.length === 0) {
- return (
- <EmptyMessage
- icon={<IconWarning size="xl" />}
- description={t('You have no data scrubbing rules')}
- />
- );
- }
-
- return (
- <Rules
- rules={rules}
- onDeleteRule={onDeleteRule}
- onEditRule={onEditRule}
- disabled={disabled}
- />
- );
-};
-
-export default Content;
diff --git a/static/app/views/settings/components/dataScrubbing/convertRelayPiiConfig.tsx b/static/app/views/settings/components/dataScrubbing/convertRelayPiiConfig.tsx
index d9c822cf197720..77061e9fa87665 100644
--- a/static/app/views/settings/components/dataScrubbing/convertRelayPiiConfig.tsx
+++ b/static/app/views/settings/components/dataScrubbing/convertRelayPiiConfig.tsx
@@ -7,7 +7,7 @@ import {Applications, MethodType, PiiConfig, Rule, RuleDefault, RuleType} from '
// For the time being the PII config format is documented at
// https://getsentry.github.io/relay/pii-config/
-export function convertRelayPiiConfig(relayPiiConfig?: string) {
+export function convertRelayPiiConfig(relayPiiConfig?: string): Rule[] {
const piiConfig = relayPiiConfig ? JSON.parse(relayPiiConfig) : {};
const rules: PiiConfig = piiConfig.rules || {};
const applications: Applications = piiConfig.applications || {};
diff --git a/static/app/views/settings/components/dataScrubbing/index.spec.tsx b/static/app/views/settings/components/dataScrubbing/index.spec.tsx
index 9d63a76f26662a..af2b08f575e878 100644
--- a/static/app/views/settings/components/dataScrubbing/index.spec.tsx
+++ b/static/app/views/settings/components/dataScrubbing/index.spec.tsx
@@ -1,27 +1,67 @@
-import {Fragment} from 'react';
+import React from 'react';
+import {InjectedRouter} from 'react-router';
+import {Location} from 'history';
+import {initializeOrg} from 'sentry-test/initializeOrg';
import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
import {textWithMarkupMatcher} from 'sentry-test/utils';
import GlobalModal from 'sentry/components/globalModal';
-import DataScrubbing from 'sentry/views/settings/components/dataScrubbing';
+import {Organization} from 'sentry/types';
+import {OrganizationContext} from 'sentry/views/organizationContext';
+import {RouteContext} from 'sentry/views/routeContext';
+import {DataScrubbing} from 'sentry/views/settings/components/dataScrubbing';
const relayPiiConfig = JSON.stringify(TestStubs.DataScrubbingRelayPiiConfig());
+function ComponentProviders({
+ router,
+ location,
+ organization,
+ children,
+}: {
+ children: React.ReactNode;
+ location: Location;
+ organization: Organization;
+ router: InjectedRouter;
+}) {
+ return (
+ <OrganizationContext.Provider value={organization}>
+ <RouteContext.Provider
+ value={{
+ router,
+ location,
+ params: {},
+ routes: [],
+ }}
+ >
+ {children}
+ </RouteContext.Provider>
+ </OrganizationContext.Provider>
+ );
+}
+
describe('Data Scrubbing', function () {
describe('Organization level', function () {
- const organization = TestStubs.Organization();
+ const {organization, router} = initializeOrg();
const additionalContext = 'These rules can be configured for each project.';
+ const endpoint = `organization/${organization.slug}/`;
it('default render', function () {
render(
- <DataScrubbing
- additionalContext={additionalContext}
- endpoint={`organization/${organization.slug}/`}
- relayPiiConfig={relayPiiConfig}
+ <ComponentProviders
+ location={router.location}
+ router={router}
organization={organization}
- onSubmitSuccess={jest.fn()}
- />
+ >
+ <DataScrubbing
+ additionalContext={additionalContext}
+ endpoint={endpoint}
+ relayPiiConfig={relayPiiConfig}
+ organization={organization}
+ onSubmitSuccess={jest.fn()}
+ />
+ </ComponentProviders>
);
// Header
@@ -31,7 +71,7 @@ describe('Data Scrubbing', function () {
expect(
screen.getByText(
textWithMarkupMatcher(
- `${additionalContext} The new rules will only apply to upcoming events. For more details, see full documentation on data scrubbing.`
+ `${additionalContext} The new rules will only apply to upcoming events. For more details, see full documentation on data scrubbing.`
)
)
).toBeInTheDocument();
@@ -54,16 +94,41 @@ describe('Data Scrubbing', function () {
expect(screen.getByRole('button', {name: 'Add Rule'})).toBeEnabled();
});
+ it('render empty state', function () {
+ render(
+ <ComponentProviders
+ location={router.location}
+ router={router}
+ organization={organization}
+ >
+ <DataScrubbing
+ endpoint={endpoint}
+ relayPiiConfig={undefined}
+ organization={organization}
+ onSubmitSuccess={jest.fn()}
+ />
+ </ComponentProviders>
+ );
+
+ expect(screen.getByText('You have no data scrubbing rules')).toBeInTheDocument();
+ });
+
it('render disabled actions', function () {
render(
- <DataScrubbing
- additionalContext={additionalContext}
- endpoint={`organization/${organization.slug}/`}
- relayPiiConfig={relayPiiConfig}
+ <ComponentProviders
+ location={router.location}
+ router={router}
organization={organization}
- onSubmitSuccess={jest.fn()}
- disabled
- />
+ >
+ <DataScrubbing
+ additionalContext={additionalContext}
+ endpoint={endpoint}
+ relayPiiConfig={relayPiiConfig}
+ organization={organization}
+ onSubmitSuccess={jest.fn()}
+ disabled
+ />
+ </ComponentProviders>
);
// Read Docs is the only enabled action
@@ -82,16 +147,22 @@ describe('Data Scrubbing', function () {
describe('Project level', function () {
it('default render', function () {
- const organization = TestStubs.Organization();
+ const {organization, router, project} = initializeOrg();
render(
- <DataScrubbing
- endpoint={`/projects/${organization.slug}/foo/`}
- relayPiiConfig={relayPiiConfig}
+ <ComponentProviders
+ location={router.location}
+ router={router}
organization={organization}
- onSubmitSuccess={jest.fn()}
- projectId="foo"
- />
+ >
+ <DataScrubbing
+ endpoint={`/projects/${organization.slug}/foo/`}
+ relayPiiConfig={relayPiiConfig}
+ organization={organization}
+ onSubmitSuccess={jest.fn()}
+ project={project}
+ />
+ </ComponentProviders>
);
// Header
@@ -101,16 +172,28 @@ describe('Data Scrubbing', function () {
});
it('OrganizationRules has content', function () {
- const organization = TestStubs.Organization({relayPiiConfig});
+ const {organization, router, project} = initializeOrg({
+ ...initializeOrg(),
+ organization: {
+ ...initializeOrg().organization,
+ relayPiiConfig,
+ },
+ });
render(
- <DataScrubbing
- endpoint={`/projects/${organization.slug}/foo/`}
- relayPiiConfig={relayPiiConfig}
+ <ComponentProviders
+ location={router.location}
+ router={router}
organization={organization}
- onSubmitSuccess={jest.fn()}
- projectId="foo"
- />
+ >
+ <DataScrubbing
+ endpoint={`/projects/${organization.slug}/foo/`}
+ relayPiiConfig={relayPiiConfig}
+ organization={organization}
+ onSubmitSuccess={jest.fn()}
+ project={project}
+ />
+ </ComponentProviders>
);
// Organization Rules
@@ -118,20 +201,24 @@ describe('Data Scrubbing', function () {
});
it('Delete rule successfully', async function () {
- const organization = TestStubs.Organization();
+ const {organization, router, project} = initializeOrg();
render(
- <Fragment>
+ <ComponentProviders
+ location={router.location}
+ router={router}
+ organization={organization}
+ >
<GlobalModal />
<DataScrubbing
endpoint={`/projects/${organization.slug}/foo/`}
- projectId="foo"
+ project={project}
relayPiiConfig={relayPiiConfig}
disabled={false}
organization={organization}
onSubmitSuccess={jest.fn()}
/>
- </Fragment>
+ </ComponentProviders>
);
userEvent.click(screen.getAllByLabelText('Delete Rule')[0]);
@@ -142,20 +229,24 @@ describe('Data Scrubbing', function () {
});
it('Open Add Rule Modal', async function () {
- const organization = TestStubs.Organization();
+ const {organization, router, project} = initializeOrg();
render(
- <Fragment>
+ <ComponentProviders
+ location={router.location}
+ router={router}
+ organization={organization}
+ >
<GlobalModal />
<DataScrubbing
endpoint={`/projects/${organization.slug}/foo/`}
- projectId="foo"
+ project={project}
relayPiiConfig={relayPiiConfig}
disabled={false}
organization={organization}
onSubmitSuccess={jest.fn()}
/>
- </Fragment>
+ </ComponentProviders>
);
userEvent.click(screen.getByRole('button', {name: 'Add Rule'}));
@@ -165,28 +256,35 @@ describe('Data Scrubbing', function () {
).toBeInTheDocument();
});
- it('Open Edit Rule Modal', async function () {
- const organization = TestStubs.Organization();
+ it('Open Edit Rule Modal', function () {
+ const {organization, router, project} = initializeOrg();
render(
- <Fragment>
+ <ComponentProviders
+ location={router.location}
+ router={router}
+ organization={organization}
+ >
<GlobalModal />
<DataScrubbing
endpoint={`/projects/${organization.slug}/foo/`}
- projectId="foo"
+ project={project}
relayPiiConfig={relayPiiConfig}
disabled={false}
organization={organization}
onSubmitSuccess={jest.fn()}
/>
- </Fragment>
+ </ComponentProviders>
);
userEvent.click(screen.getAllByRole('button', {name: 'Edit Rule'})[0]);
- expect(
- await screen.findByText('Edit an advanced data scrubbing rule')
- ).toBeInTheDocument();
+ // Verify the router to open the modal was called
+ expect(router.push).toHaveBeenCalledWith(
+ expect.objectContaining({
+ pathname: `/settings/${organization.slug}/projects/${project.slug}/security-and-privacy/advanced-data-scrubbing/0/`,
+ })
+ );
});
});
});
diff --git a/static/app/views/settings/components/dataScrubbing/index.tsx b/static/app/views/settings/components/dataScrubbing/index.tsx
index 88891fc693e439..3fa82057999d42 100644
--- a/static/app/views/settings/components/dataScrubbing/index.tsx
+++ b/static/app/views/settings/components/dataScrubbing/index.tsx
@@ -1,205 +1,207 @@
-import {Component} from 'react';
+import {useCallback, useEffect, useState} from 'react';
import styled from '@emotion/styled';
import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
import {openModal} from 'sentry/actionCreators/modal';
-import {Client} from 'sentry/api';
import Button from 'sentry/components/button';
+import EmptyMessage from 'sentry/components/emptyMessage';
import ExternalLink from 'sentry/components/links/externalLink';
import {Panel, PanelAlert, PanelBody, PanelHeader} from 'sentry/components/panels';
+import {IconWarning} from 'sentry/icons';
import {t, tct} from 'sentry/locale';
import space from 'sentry/styles/space';
import {Organization, Project} from 'sentry/types';
+import {defined} from 'sentry/utils';
+import useApi from 'sentry/utils/useApi';
+import {useNavigate} from 'sentry/utils/useNavigate';
+import {useRouteContext} from 'sentry/utils/useRouteContext';
import Add from './modals/add';
import Edit from './modals/edit';
-import Content from './content';
import {convertRelayPiiConfig} from './convertRelayPiiConfig';
-import OrganizationRules from './organizationRules';
+import {OrganizationRules} from './organizationRules';
+import Rules from './rules';
import submitRules from './submitRules';
-import {ProjectId, Rule} from './types';
+import {Rule} from './types';
const ADVANCED_DATASCRUBBING_LINK =
'https://docs.sentry.io/product/data-management-settings/scrubbing/advanced-datascrubbing/';
-type Props<T extends ProjectId> = {
+type Props = {
endpoint: string;
organization: Organization;
additionalContext?: React.ReactNode;
disabled?: boolean;
- onSubmitSuccess?: (data: T extends undefined ? Organization : Project) => void;
- projectId?: T;
+ onSubmitSuccess?: (data: {relayPiiConfig: string}) => void;
+ project?: Project;
relayPiiConfig?: string;
};
-type State = {
- orgRules: Array<Rule>;
- rules: Array<Rule>;
- savedRules: Array<Rule>;
- relayPiiConfig?: string;
-};
-
-class DataScrubbing<T extends ProjectId = undefined> extends Component<Props<T>, State> {
- state: State = {
- rules: [],
- savedRules: [],
- relayPiiConfig: this.props.relayPiiConfig,
- orgRules: [],
- };
-
- componentDidMount() {
- this.loadRules();
- this.loadOrganizationRules();
- }
-
- componentDidUpdate(_prevProps: Props<T>, prevState: State) {
- if (prevState.relayPiiConfig !== this.state.relayPiiConfig) {
- this.loadRules();
+export function DataScrubbing({
+ project,
+ endpoint,
+ organization,
+ disabled,
+ onSubmitSuccess,
+ additionalContext,
+ relayPiiConfig,
+}: Props) {
+ const api = useApi();
+ const [rules, setRules] = useState<Rule[]>([]);
+ const navigate = useNavigate();
+ const routeContext = useRouteContext();
+
+ const successfullySaved = useCallback(
+ (response: {relayPiiConfig: string}, successMessage: string) => {
+ setRules(convertRelayPiiConfig(response.relayPiiConfig));
+ addSuccessMessage(successMessage);
+ onSubmitSuccess?.(response);
+ },
+ [onSubmitSuccess]
+ );
+
+ const handleCloseModal = useCallback(() => {
+ const path = project?.slug
+ ? `/settings/${organization.slug}/projects/${project.slug}/security-and-privacy/`
+ : `/settings/${organization.slug}/security-and-privacy/`;
+
+ navigate(path);
+ }, [navigate, organization.slug, project?.slug]);
+
+ useEffect(() => {
+ if (
+ !defined(routeContext.params.scrubbingId) ||
+ !rules.some(rule => String(rule.id) === routeContext.params.scrubbingId)
+ ) {
+ return;
}
- }
-
- componentWillUnmount() {
- this.api.clear();
- }
-
- api = new Client();
- loadOrganizationRules() {
- const {organization, projectId} = this.props;
-
- if (projectId) {
+ openModal(
+ modalProps => (
+ <Edit
+ {...modalProps}
+ rule={rules[routeContext.params.scrubbingId]}
+ projectId={project?.id}
+ savedRules={rules}
+ api={api}
+ endpoint={endpoint}
+ orgSlug={organization.slug}
+ onSubmitSuccess={response => {
+ return successfullySaved(
+ response,
+ t('Successfully updated data scrubbing rule')
+ );
+ }}
+ />
+ ),
+ {onClose: handleCloseModal}
+ );
+ }, [
+ routeContext.params.scrubbingId,
+ rules,
+ project?.id,
+ api,
+ endpoint,
+ organization.slug,
+ successfullySaved,
+ handleCloseModal,
+ ]);
+
+ useEffect(() => {
+ function loadRules() {
try {
- this.setState({
- orgRules: convertRelayPiiConfig(organization.relayPiiConfig),
- });
+ setRules(convertRelayPiiConfig(relayPiiConfig));
} catch {
- addErrorMessage(t('Unable to load organization rules'));
+ addErrorMessage(t('Unable to load data scrubbing rules'));
}
}
- }
- loadRules() {
- try {
- const convertedRules = convertRelayPiiConfig(this.state.relayPiiConfig);
- this.setState({
- rules: convertedRules,
- savedRules: convertedRules,
- });
- } catch {
- addErrorMessage(t('Unable to load project rules'));
- }
- }
+ loadRules();
+ }, [relayPiiConfig]);
+
+ function handleEdit(id: Rule['id']) {
+ const path = project
+ ? `/settings/${organization.slug}/projects/${project.slug}/security-and-privacy/advanced-data-scrubbing/${id}/`
+ : `/settings/${organization.slug}/security-and-privacy/advanced-data-scrubbing/${id}/`;
- successfullySaved(
- response: T extends undefined ? Organization : Project,
- successMessage: string
- ) {
- const {onSubmitSuccess} = this.props;
- this.setState({rules: convertRelayPiiConfig(response.relayPiiConfig)});
- addSuccessMessage(successMessage);
- onSubmitSuccess?.(response);
+ navigate(path);
}
- handleOpenAddModal = () => {
- const {rules} = this.state;
+ function handleAdd() {
openModal(modalProps => (
<Add
{...modalProps}
- projectId={this.props.projectId}
+ projectId={project?.id}
savedRules={rules}
- api={this.api}
- endpoint={this.props.endpoint}
- orgSlug={this.props.organization.slug}
+ api={api}
+ endpoint={endpoint}
+ orgSlug={organization.slug}
onSubmitSuccess={response => {
- this.successfullySaved(response, t('Successfully added data scrubbing rule'));
+ return successfullySaved(response, t('Successfully added data scrubbing rule'));
}}
/>
));
- };
-
- handleOpenEditModal = (id: Rule['id']) => () => {
- const {rules} = this.state;
- openModal(modalProps => (
- <Edit
- {...modalProps}
- rule={rules[id]}
- projectId={this.props.projectId}
- savedRules={rules}
- api={this.api}
- endpoint={this.props.endpoint}
- orgSlug={this.props.organization.slug}
- onSubmitSuccess={response => {
- this.successfullySaved(response, t('Successfully updated data scrubbing rule'));
- }}
- />
- ));
- };
-
- handleDelete = (id: Rule['id']) => async () => {
- const {rules} = this.state;
- const filteredRules = rules.filter(rule => rule.id !== id);
+ }
+ async function handleDelete(id: Rule['id']) {
try {
- const data = await submitRules(this.api, this.props.endpoint, filteredRules);
+ const filteredRules = rules.filter(rule => rule.id !== id);
+ const data = await submitRules(api, endpoint, filteredRules);
if (data?.relayPiiConfig) {
- const convertedRules = convertRelayPiiConfig(data.relayPiiConfig);
-
- this.setState({rules: convertedRules});
+ setRules(convertRelayPiiConfig(data.relayPiiConfig));
addSuccessMessage(t('Successfully deleted data scrubbing rule'));
}
} catch {
addErrorMessage(t('An unknown error occurred while deleting data scrubbing rule'));
}
- };
-
- render() {
- const {additionalContext, disabled, projectId} = this.props;
- const {orgRules, rules} = this.state;
-
- return (
- <Panel data-test-id="advanced-data-scrubbing" id="advanced-data-scrubbing">
- <PanelHeader>
- <div>{t('Advanced Data Scrubbing')}</div>
- </PanelHeader>
- <PanelAlert type="info">
- {additionalContext}{' '}
- {`${t('The new rules will only apply to upcoming events. ')}`}{' '}
- {tct('For more details, see [linkToDocs].', {
+ }
+
+ return (
+ <Panel data-test-id="advanced-data-scrubbing">
+ <PanelHeader>
+ <div>{t('Advanced Data Scrubbing')}</div>
+ </PanelHeader>
+ <PanelAlert type="info">
+ {additionalContext}{' '}
+ {tct(
+ 'The new rules will only apply to upcoming events. For more details, see [linkToDocs].',
+ {
linkToDocs: (
<ExternalLink href={ADVANCED_DATASCRUBBING_LINK}>
{t('full documentation on data scrubbing')}
</ExternalLink>
),
- })}
- </PanelAlert>
- <PanelBody>
- {projectId && <OrganizationRules rules={orgRules} />}
- <Content
+ }
+ )}
+ </PanelAlert>
+ <PanelBody>
+ {project && <OrganizationRules organization={organization} />}
+ {!rules.length ? (
+ <EmptyMessage
+ icon={<IconWarning size="xl" />}
+ description={t('You have no data scrubbing rules')}
+ />
+ ) : (
+ <Rules
rules={rules}
- onDeleteRule={this.handleDelete}
- onEditRule={this.handleOpenEditModal}
+ onDeleteRule={handleDelete}
+ onEditRule={handleEdit}
disabled={disabled}
/>
- <PanelAction>
- <Button href={ADVANCED_DATASCRUBBING_LINK} external>
- {t('Read Docs')}
- </Button>
- <Button
- disabled={disabled}
- onClick={this.handleOpenAddModal}
- priority="primary"
- >
- {t('Add Rule')}
- </Button>
- </PanelAction>
- </PanelBody>
- </Panel>
- );
- }
+ )}
+ <PanelAction>
+ <Button href={ADVANCED_DATASCRUBBING_LINK} external>
+ {t('Read Docs')}
+ </Button>
+ <Button disabled={disabled} onClick={handleAdd} priority="primary">
+ {t('Add Rule')}
+ </Button>
+ </PanelAction>
+ </PanelBody>
+ </Panel>
+ );
}
-export default DataScrubbing;
-
const PanelAction = styled('div')`
padding: ${space(1)} ${space(2)};
position: relative;
diff --git a/static/app/views/settings/components/dataScrubbing/modals/add.tsx b/static/app/views/settings/components/dataScrubbing/modals/add.tsx
index 4a21579c1e1685..70c976716281c1 100644
--- a/static/app/views/settings/components/dataScrubbing/modals/add.tsx
+++ b/static/app/views/settings/components/dataScrubbing/modals/add.tsx
@@ -1,18 +1,15 @@
import {t} from 'sentry/locale';
-import {ProjectId, Rule} from '../types';
+import {Rule} from '../types';
import ModalManager from './modalManager';
-type ModalManagerProps<T extends ProjectId> = ModalManager<T>['props'];
-type Props<T extends ProjectId> = Omit<
- ModalManagerProps<T>,
- 'title' | 'initialValues' | 'onGetNewRules'
->;
+type ModalManagerProps = ModalManager['props'];
+type Props = Omit<ModalManagerProps, 'title' | 'initialValues' | 'onGetNewRules'>;
-const Add = <T extends ProjectId = undefined>({savedRules, ...props}: Props<T>) => {
+const Add = ({savedRules, ...props}: Props) => {
const handleGetNewRules = (
- values: Parameters<ModalManagerProps<T>['onGetNewRules']>[0]
+ values: Parameters<ModalManagerProps['onGetNewRules']>[0]
) => {
return [...savedRules, {...values, id: savedRules.length}] as Array<Rule>;
};
diff --git a/static/app/views/settings/components/dataScrubbing/modals/edit.tsx b/static/app/views/settings/components/dataScrubbing/modals/edit.tsx
index 33efb282b2858e..922fb1667bcf3f 100644
--- a/static/app/views/settings/components/dataScrubbing/modals/edit.tsx
+++ b/static/app/views/settings/components/dataScrubbing/modals/edit.tsx
@@ -1,20 +1,17 @@
import {t} from 'sentry/locale';
-import {ProjectId, Rule} from '../types';
+import {Rule} from '../types';
import ModalManager from './modalManager';
-type ModalManagerProps<T extends ProjectId> = ModalManager<T>['props'];
-type Props<T extends ProjectId> = Omit<
- ModalManagerProps<T>,
- 'title' | 'initialValues' | 'onGetNewRules'
-> & {
+type ModalManagerProps = ModalManager['props'];
+type Props = Omit<ModalManagerProps, 'title' | 'initialValues' | 'onGetNewRules'> & {
rule: Rule;
};
-const Edit = <T extends ProjectId>({savedRules, rule, ...props}: Props<T>) => {
+const Edit = ({savedRules, rule, ...props}: Props) => {
const handleGetNewRules = (
- values: Parameters<ModalManagerProps<T>['onGetNewRules']>[0]
+ values: Parameters<ModalManagerProps['onGetNewRules']>[0]
) => {
const updatedRule = {...values, id: rule.id};
diff --git a/static/app/views/settings/components/dataScrubbing/modals/modalManager.tsx b/static/app/views/settings/components/dataScrubbing/modals/modalManager.tsx
index 5962bef69b081b..d5260c19306b40 100644
--- a/static/app/views/settings/components/dataScrubbing/modals/modalManager.tsx
+++ b/static/app/views/settings/components/dataScrubbing/modals/modalManager.tsx
@@ -9,14 +9,7 @@ import {t} from 'sentry/locale';
import {Organization, Project} from 'sentry/types';
import submitRules from '../submitRules';
-import {
- EventIdStatus,
- KeysOfUnion,
- MethodType,
- ProjectId,
- Rule,
- RuleType,
-} from '../types';
+import {EventIdStatus, KeysOfUnion, MethodType, Rule, RuleType} from '../types';
import {valueSuggestions} from '../utils';
import Form from './form';
@@ -29,16 +22,16 @@ type Values = FormProps['values'];
type EventId = NonNullable<FormProps['eventId']>;
type SourceSuggestions = FormProps['sourceSuggestions'];
-type Props<T> = ModalRenderProps & {
+type Props = ModalRenderProps & {
api: Client;
endpoint: string;
- onGetNewRules: (values: Values) => Array<Rule>;
- onSubmitSuccess: (data: T extends undefined ? Organization : Project) => void;
+ onGetNewRules: (values: Values) => Rule[];
+ onSubmitSuccess: (data: {relayPiiConfig: string}) => void;
orgSlug: Organization['slug'];
- savedRules: Array<Rule>;
+ savedRules: Rule[];
title: string;
initialState?: Partial<Values>;
- projectId?: T;
+ projectId?: Project['id'];
};
type State = {
@@ -50,14 +43,14 @@ type State = {
values: Values;
};
-class ModalManager<T extends ProjectId> extends Component<Props<T>, State> {
+class ModalManager extends Component<Props, State> {
state = this.getDefaultState();
componentDidMount() {
this.handleValidateForm();
}
- componentDidUpdate(_prevProps: Props<T>, prevState: State) {
+ componentDidUpdate(_prevProps: Props, prevState: State) {
if (!isEqual(prevState.values, this.state.values)) {
this.handleValidateForm();
}
diff --git a/static/app/views/settings/components/dataScrubbing/organizationRules.tsx b/static/app/views/settings/components/dataScrubbing/organizationRules.tsx
index cfd9e7f331fc63..1362cc8da6f054 100644
--- a/static/app/views/settings/components/dataScrubbing/organizationRules.tsx
+++ b/static/app/views/settings/components/dataScrubbing/organizationRules.tsx
@@ -1,29 +1,45 @@
import {Component, createRef} from 'react';
import styled from '@emotion/styled';
+import {addErrorMessage} from 'sentry/actionCreators/indicator';
import Button from 'sentry/components/button';
import {IconChevron} from 'sentry/icons';
import {t} from 'sentry/locale';
import space from 'sentry/styles/space';
+import {Organization} from 'sentry/types';
+import {convertRelayPiiConfig} from 'sentry/views/settings/components/dataScrubbing/convertRelayPiiConfig';
import Rules from './rules';
import {Rule} from './types';
type Props = {
- rules: Array<Rule>;
+ organization: Organization;
};
type State = {
isCollapsed: boolean;
+ rules: Rule[];
contentHeight?: string;
};
-class OrganizationRules extends Component<Props, State> {
+export class OrganizationRules extends Component<Props, State> {
state: State = {
isCollapsed: true,
+ rules: [],
};
- componentDidUpdate() {
+ componentDidMount() {
+ this.loadRules();
+ }
+
+ componentDidUpdate(prevProps: Props) {
+ if (
+ prevProps.organization.relayPiiConfig !== this.props.organization.relayPiiConfig
+ ) {
+ this.loadRules();
+ return;
+ }
+
this.loadContentHeight();
}
@@ -44,9 +60,18 @@ class OrganizationRules extends Component<Props, State> {
}));
};
+ loadRules() {
+ try {
+ this.setState({
+ rules: convertRelayPiiConfig(this.props.organization.relayPiiConfig),
+ });
+ } catch {
+ addErrorMessage(t('Unable to load data scrubbing rules'));
+ }
+ }
+
render() {
- const {rules} = this.props;
- const {isCollapsed, contentHeight} = this.state;
+ const {isCollapsed, contentHeight, rules} = this.state;
if (rules.length === 0) {
return (
@@ -78,8 +103,6 @@ class OrganizationRules extends Component<Props, State> {
}
}
-export default OrganizationRules;
-
const Content = styled('div')`
transition: height 300ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;
height: 0;
diff --git a/static/app/views/settings/components/dataScrubbing/rules.tsx b/static/app/views/settings/components/dataScrubbing/rules.tsx
index fae362997b486c..3f6e1bd2c23b39 100644
--- a/static/app/views/settings/components/dataScrubbing/rules.tsx
+++ b/static/app/views/settings/components/dataScrubbing/rules.tsx
@@ -14,8 +14,8 @@ import {getRuleDescription} from './utils';
type Props = {
rules: Array<Rule>;
disabled?: boolean;
- onDeleteRule?: (id: Rule['id']) => () => void;
- onEditRule?: (id: Rule['id']) => () => void;
+ onDeleteRule?: (id: Rule['id']) => void;
+ onEditRule?: (id: Rule['id']) => void;
};
const Rules = forwardRef(function RulesList(
@@ -34,7 +34,7 @@ const Rules = forwardRef(function RulesList(
<Button
aria-label={t('Edit Rule')}
size="sm"
- onClick={onEditRule(id)}
+ onClick={() => onEditRule(id)}
icon={<IconEdit />}
disabled={disabled}
title={
@@ -46,9 +46,7 @@ const Rules = forwardRef(function RulesList(
<ConfirmDelete
message={t('Are you sure you wish to delete this rule?')}
priority="danger"
- onConfirm={() => {
- onDeleteRule(id)();
- }}
+ onConfirm={() => onDeleteRule(id)}
confirmInput={ruleDescription}
disabled={disabled}
stopPropagation
diff --git a/static/app/views/settings/components/dataScrubbing/types.tsx b/static/app/views/settings/components/dataScrubbing/types.tsx
index 29672a79147fb3..6f506c80bd6e81 100644
--- a/static/app/views/settings/components/dataScrubbing/types.tsx
+++ b/static/app/views/settings/components/dataScrubbing/types.tsx
@@ -1,5 +1,3 @@
-import {Project} from 'sentry/types';
-
export enum RuleType {
PATTERN = 'pattern',
CREDITCARD = 'creditcard',
@@ -125,5 +123,3 @@ export type PiiConfig =
export type Applications = Record<string, Array<string>>;
export type Errors = Partial<Record<KeysOfUnion<Rule>, string>>;
-
-export type ProjectId = Project['id'] | undefined;
diff --git a/static/app/views/settings/organizationSecurityAndPrivacy/index.tsx b/static/app/views/settings/organizationSecurityAndPrivacy/index.tsx
index 29969ef1d80f95..09fae86c0ac738 100644
--- a/static/app/views/settings/organizationSecurityAndPrivacy/index.tsx
+++ b/static/app/views/settings/organizationSecurityAndPrivacy/index.tsx
@@ -1,5 +1,4 @@
-import {Fragment} from 'react';
-import {RouteComponentProps} from 'react-router';
+import {Fragment, useEffect, useState} from 'react';
import {addErrorMessage} from 'sentry/actionCreators/indicator';
import {updateOrganization} from 'sentry/actionCreators/organizations';
@@ -9,71 +8,74 @@ import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
import organizationSecurityAndPrivacyGroups from 'sentry/data/forms/organizationSecurityAndPrivacyGroups';
import {t} from 'sentry/locale';
import {Organization} from 'sentry/types';
-import withOrganization from 'sentry/utils/withOrganization';
-import AsyncView from 'sentry/views/asyncView';
+import useApi from 'sentry/utils/useApi';
+import useOrganization from 'sentry/utils/useOrganization';
import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
-import DataScrubbing from '../components/dataScrubbing';
+import {DataScrubbing} from '../components/dataScrubbing';
-type Props = RouteComponentProps<{orgId: string; projectId: string}, {}> & {
- organization: Organization;
-};
+export default function OrganizationSecurityAndPrivacyContent() {
+ const api = useApi();
+ const organization = useOrganization();
+ const [authProvider, setAuthProvider] = useState<string | null>(null);
-class OrganizationSecurityAndPrivacyContent extends AsyncView<Props> {
- getEndpoints(): ReturnType<AsyncView['getEndpoints']> {
- const {orgId} = this.props.params;
- return [['authProvider', `/organizations/${orgId}/auth-provider/`]];
- }
+ useEffect(() => {
+ async function fetchAuthProvider() {
+ try {
+ const response = await api.requestPromise(
+ `/organizations/${organization.slug}/auth-provider/`
+ );
+ setAuthProvider(response);
+ } catch {
+ addErrorMessage(t('Unable to fetch authentication provider'));
+ }
+ }
+
+ fetchAuthProvider();
+ }, [organization.slug, api]);
- handleUpdateOrganization = (data: Organization) => {
+ const initialData = organization;
+ const endpoint = `/organizations/${organization.slug}/`;
+ const access = new Set(organization.access);
+ const features = new Set(organization.features);
+ const relayPiiConfig = organization.relayPiiConfig;
+ const title = t('Security & Privacy');
+
+ function handleUpdateOrganization(data: Organization) {
// This will update OrganizationStore (as well as OrganizationsStore
// which is slightly incorrect because it has summaries vs a detailed org)
updateOrganization(data);
- };
-
- renderBody() {
- const {organization} = this.props;
- const {orgId} = this.props.params;
- const initialData = organization;
- const endpoint = `/organizations/${orgId}/`;
- const access = new Set(organization.access);
- const features = new Set(organization.features);
- const relayPiiConfig = organization.relayPiiConfig;
- const {authProvider} = this.state;
- const title = t('Security & Privacy');
+ }
- return (
- <Fragment>
- <SentryDocumentTitle title={title} orgSlug={organization.slug} />
- <SettingsPageHeader title={title} />
- <Form
- data-test-id="organization-settings-security-and-privacy"
- apiMethod="PUT"
- apiEndpoint={endpoint}
- initialData={initialData}
- additionalFieldProps={{hasSsoEnabled: !!authProvider}}
- onSubmitSuccess={this.handleUpdateOrganization}
- onSubmitError={() => addErrorMessage(t('Unable to save change'))}
- saveOnBlur
- allowUndo
- >
- <JsonForm
- features={features}
- forms={organizationSecurityAndPrivacyGroups}
- disabled={!access.has('org:write')}
- />
- </Form>
- <DataScrubbing
- additionalContext={t('These rules can be configured for each project.')}
- endpoint={endpoint}
- relayPiiConfig={relayPiiConfig}
+ return (
+ <Fragment>
+ <SentryDocumentTitle title={title} orgSlug={organization.slug} />
+ <SettingsPageHeader title={title} />
+ <Form
+ data-test-id="organization-settings-security-and-privacy"
+ apiMethod="PUT"
+ apiEndpoint={endpoint}
+ initialData={initialData}
+ additionalFieldProps={{hasSsoEnabled: !!authProvider}}
+ onSubmitSuccess={handleUpdateOrganization}
+ onSubmitError={() => addErrorMessage(t('Unable to save change'))}
+ saveOnBlur
+ allowUndo
+ >
+ <JsonForm
+ features={features}
+ forms={organizationSecurityAndPrivacyGroups}
disabled={!access.has('org:write')}
- organization={organization}
- onSubmitSuccess={this.handleUpdateOrganization}
/>
- </Fragment>
- );
- }
+ </Form>
+ <DataScrubbing
+ additionalContext={t('These rules can be configured for each project.')}
+ endpoint={endpoint}
+ relayPiiConfig={relayPiiConfig}
+ organization={organization}
+ disabled={!access.has('org:write')}
+ onSubmitSuccess={data => handleUpdateOrganization({...organization, ...data})}
+ />
+ </Fragment>
+ );
}
-
-export default withOrganization(OrganizationSecurityAndPrivacyContent);
diff --git a/static/app/views/settings/organizationSecurityAndPrivacy/organizationSecurityAndPrivacy.spec.jsx b/static/app/views/settings/organizationSecurityAndPrivacy/organizationSecurityAndPrivacy.spec.jsx
deleted file mode 100644
index cd03e2c7703d5a..00000000000000
--- a/static/app/views/settings/organizationSecurityAndPrivacy/organizationSecurityAndPrivacy.spec.jsx
+++ /dev/null
@@ -1,147 +0,0 @@
-import {mountWithTheme} from 'sentry-test/enzyme';
-import {initializeOrg} from 'sentry-test/initializeOrg';
-import {mountGlobalModal} from 'sentry-test/modal';
-
-import OrganizationSecurityAndPrivacy from 'sentry/views/settings/organizationSecurityAndPrivacy';
-
-describe('OrganizationSecurityAndPrivacy', function () {
- let organization;
- let routerContext;
-
- beforeEach(function () {
- ({organization, routerContext} = initializeOrg());
- MockApiClient.addMockResponse({
- url: `/organizations/${organization.slug}/auth-provider/`,
- method: 'GET',
- });
-
- MockApiClient.addMockResponse({
- url: `/organizations/${organization.slug}/`,
- method: 'GET',
- });
- });
-
- it('shows require2fa switch', async function () {
- const wrapper = mountWithTheme(
- <OrganizationSecurityAndPrivacy
- params={{orgId: organization.slug}}
- organization={organization}
- />,
- routerContext
- );
- await tick();
- wrapper.update();
- expect(wrapper.find('Switch[name="require2FA"]')).toHaveLength(1);
- });
-
- it('returns to "off" if switch enable fails (e.g. API error)', async function () {
- MockApiClient.addMockResponse({
- url: '/organizations/org-slug/',
- method: 'PUT',
- statusCode: 500,
- });
-
- const wrapper = mountWithTheme(
- <OrganizationSecurityAndPrivacy
- params={{orgId: organization.slug}}
- organization={organization}
- />,
- routerContext
- );
-
- await tick();
- wrapper.update();
- wrapper.find('Switch[name="require2FA"]').simulate('click');
-
- // hide console.error for this test
- jest.spyOn(console, 'error').mockImplementation(() => {});
- // Confirm but has API failure
- const modal = await mountGlobalModal();
- modal.find('Button[priority="primary"]').simulate('click');
-
- await tick();
- wrapper.update();
- expect(wrapper.find('Switch[name="require2FA"]').prop('isActive')).toBe(false);
- // eslint-disable-next-line no-console
- console.error.mockRestore();
- });
-
- it('renders join request switch', async function () {
- const wrapper = mountWithTheme(
- <OrganizationSecurityAndPrivacy params={{orgId: organization.slug}} />,
- TestStubs.routerContext([{organization}])
- );
-
- await tick();
- wrapper.update();
- expect(wrapper.find('Switch[name="allowJoinRequests"]').exists()).toBe(true);
- });
-
- it('enables require2fa but cancels confirm modal', async function () {
- const mock = MockApiClient.addMockResponse({
- url: '/organizations/org-slug/',
- method: 'PUT',
- });
- const wrapper = mountWithTheme(
- <OrganizationSecurityAndPrivacy
- params={{orgId: organization.slug}}
- organization={organization}
- />,
- routerContext
- );
-
- await tick();
- wrapper.update();
- expect(wrapper.find('Switch[name="require2FA"]')).toHaveLength(1);
- wrapper.find('Switch[name="require2FA"]').simulate('click');
-
- // Cancel
- const modal = await mountGlobalModal();
- modal.find('Button').first().simulate('click');
-
- await tick();
- wrapper.update();
-
- expect(wrapper.find('Switch[name="require2FA"]').prop('isActive')).toBe(false);
- expect(mock).not.toHaveBeenCalled();
- });
-
- it('enables require2fa with confirm modal', async function () {
- const mock = MockApiClient.addMockResponse({
- url: '/organizations/org-slug/',
- method: 'PUT',
- });
-
- const wrapper = mountWithTheme(
- <OrganizationSecurityAndPrivacy
- params={{orgId: organization.slug}}
- organization={organization}
- />,
- routerContext
- );
-
- await tick();
- wrapper.update();
-
- expect(wrapper.find('Switch[name="require2FA"]')).toHaveLength(1);
- wrapper.find('Switch[name="require2FA"]').simulate('click');
-
- // Confirm
- const modal = await mountGlobalModal();
- modal.find('Button[priority="primary"]').simulate('click');
-
- await tick();
- wrapper.update();
-
- expect(wrapper.find('Switch[name="require2FA"]').prop('isActive')).toBe(true);
- expect(mock).toHaveBeenCalledWith(
- '/organizations/org-slug/',
- expect.objectContaining({
- method: 'PUT',
- data: {
- require2FA: true,
- },
- })
- );
- });
-});
diff --git a/static/app/views/settings/organizationSecurityAndPrivacy/organizationSecurityAndPrivacy.spec.tsx b/static/app/views/settings/organizationSecurityAndPrivacy/organizationSecurityAndPrivacy.spec.tsx
new file mode 100644
index 00000000000000..193079daacb6ee
--- /dev/null
+++ b/static/app/views/settings/organizationSecurityAndPrivacy/organizationSecurityAndPrivacy.spec.tsx
@@ -0,0 +1,206 @@
+import {InjectedRouter} from 'react-router';
+import {Location} from 'history';
+
+import {initializeOrg} from 'sentry-test/initializeOrg';
+import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary';
+
+import GlobalModal from 'sentry/components/globalModal';
+import {Organization} from 'sentry/types';
+import {OrganizationContext} from 'sentry/views/organizationContext';
+import {RouteContext} from 'sentry/views/routeContext';
+import OrganizationSecurityAndPrivacy from 'sentry/views/settings/organizationSecurityAndPrivacy';
+
+function ComponentProviders({
+ router,
+ location,
+ organization,
+ children,
+}: {
+ children: React.ReactNode;
+ location: Location;
+ organization: Organization;
+ router: InjectedRouter;
+}) {
+ MockApiClient.addMockResponse({
+ url: `/organizations/${organization.slug}/auth-provider/`,
+ method: 'GET',
+ body: {},
+ });
+
+ return (
+ <OrganizationContext.Provider value={organization}>
+ <RouteContext.Provider
+ value={{
+ router,
+ location,
+ params: {},
+ routes: [],
+ }}
+ >
+ {children}
+ </RouteContext.Provider>
+ </OrganizationContext.Provider>
+ );
+}
+
+describe('OrganizationSecurityAndPrivacy', function () {
+ it('shows require2fa switch', async function () {
+ const {organization, router} = initializeOrg();
+
+ render(
+ <ComponentProviders
+ organization={organization}
+ router={router}
+ location={router.location}
+ >
+ <OrganizationSecurityAndPrivacy />
+ </ComponentProviders>
+ );
+
+ expect(
+ await screen.findByRole('checkbox', {
+ name: 'Enable to require and enforce two-factor authentication for all members',
+ })
+ ).toBeInTheDocument();
+ });
+
+ it('returns to "off" if switch enable fails (e.g. API error)', async function () {
+ const {organization, router} = initializeOrg();
+
+ MockApiClient.addMockResponse({
+ url: `/organizations/${organization.slug}/`,
+ method: 'PUT',
+ statusCode: 500,
+ });
+
+ render(
+ <ComponentProviders
+ organization={organization}
+ router={router}
+ location={router.location}
+ >
+ <GlobalModal />
+ <OrganizationSecurityAndPrivacy />
+ </ComponentProviders>
+ );
+
+ userEvent.click(
+ await screen.findByRole('checkbox', {
+ name: 'Enable to require and enforce two-factor authentication for all members',
+ })
+ );
+
+ // Hide console.error for this test
+ jest.spyOn(console, 'error').mockImplementation(() => {});
+
+ // Confirm but has API failure
+ userEvent.click(screen.getByRole('button', {name: 'Confirm'}));
+
+ expect(
+ await screen.findByRole('checkbox', {
+ name: 'Enable to require and enforce two-factor authentication for all members',
+ })
+ ).not.toBeChecked();
+ });
+
+ it('renders join request switch', async function () {
+ const {organization, router} = initializeOrg();
+
+ render(
+ <ComponentProviders
+ organization={organization}
+ router={router}
+ location={router.location}
+ >
+ <OrganizationSecurityAndPrivacy />
+ </ComponentProviders>
+ );
+
+ expect(
+ await screen.findByRole('checkbox', {
+ name: 'Enable to allow users to request to join your organization',
+ })
+ ).toBeInTheDocument();
+ });
+
+ it('enables require2fa but cancels confirm modal', async function () {
+ const {organization, router} = initializeOrg();
+
+ const mock = MockApiClient.addMockResponse({
+ url: `/organizations/${organization.slug}/`,
+ method: 'PUT',
+ });
+
+ render(
+ <ComponentProviders
+ organization={organization}
+ router={router}
+ location={router.location}
+ >
+ <GlobalModal />
+ <OrganizationSecurityAndPrivacy />
+ </ComponentProviders>
+ );
+
+ userEvent.click(
+ await screen.findByRole('checkbox', {
+ name: 'Enable to require and enforce two-factor authentication for all members',
+ })
+ );
+
+ // Cancel
+ userEvent.click(screen.getByRole('button', {name: 'Cancel'}));
+
+ expect(
+ screen.getByRole('checkbox', {
+ name: 'Enable to require and enforce two-factor authentication for all members',
+ })
+ ).not.toBeChecked();
+
+ expect(mock).not.toHaveBeenCalled();
+ });
+
+ it('enables require2fa with confirm modal', async function () {
+ const {organization, router} = initializeOrg();
+
+ const mock = MockApiClient.addMockResponse({
+ url: `/organizations/${organization.slug}/`,
+ method: 'PUT',
+ });
+
+ render(
+ <ComponentProviders
+ organization={organization}
+ router={router}
+ location={router.location}
+ >
+ <GlobalModal />
+ <OrganizationSecurityAndPrivacy />
+ </ComponentProviders>
+ );
+
+ userEvent.click(
+ await screen.findByRole('checkbox', {
+ name: 'Enable to require and enforce two-factor authentication for all members',
+ })
+ );
+
+ userEvent.click(screen.getByRole('button', {name: 'Confirm'}));
+
+ expect(
+ screen.getByRole('checkbox', {
+ name: 'Enable to require and enforce two-factor authentication for all members',
+ })
+ ).toBeChecked();
+
+ expect(mock).toHaveBeenCalledWith(
+ '/organizations/org-slug/',
+ expect.objectContaining({
+ method: 'PUT',
+ data: {
+ require2FA: true,
+ },
+ })
+ );
+ });
+});
diff --git a/static/app/views/settings/projectSecurityAndPrivacy/index.tsx b/static/app/views/settings/projectSecurityAndPrivacy/index.tsx
index ae2e668461d44c..ebb44de2b40ba7 100644
--- a/static/app/views/settings/projectSecurityAndPrivacy/index.tsx
+++ b/static/app/views/settings/projectSecurityAndPrivacy/index.tsx
@@ -1,5 +1,4 @@
-import {Component, Fragment} from 'react';
-import {RouteComponentProps} from 'react-router';
+import {Fragment} from 'react';
import {addErrorMessage} from 'sentry/actionCreators/indicator';
import ProjectActions from 'sentry/actions/projectActions';
@@ -12,75 +11,70 @@ import {t, tct} from 'sentry/locale';
import {Organization, Project} from 'sentry/types';
import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
-import DataScrubbing from '../components/dataScrubbing';
+import {DataScrubbing} from '../components/dataScrubbing';
-type Props = RouteComponentProps<{orgId: string; projectId: string}, {}> & {
+type Props = {
organization: Organization;
project: Project;
};
-class ProjectSecurityAndPrivacy extends Component<Props> {
- handleUpdateProject = (data: Project) => {
+export default function ProjectSecurityAndPrivacy({organization, project}: Props) {
+ function handleUpdateProject(data: Project) {
// This will update our project global state
ProjectActions.updateSuccess(data);
- };
+ }
- render() {
- const {organization, project} = this.props;
- const initialData = project;
- const projectSlug = project.slug;
- const endpoint = `/projects/${organization.slug}/${projectSlug}/`;
- const access = new Set(organization.access);
- const features = new Set(organization.features);
- const relayPiiConfig = project.relayPiiConfig;
- const apiMethod = 'PUT';
- const title = t('Security & Privacy');
+ const initialData = project;
+ const projectSlug = project.slug;
+ const endpoint = `/projects/${organization.slug}/${projectSlug}/`;
+ const access = new Set(organization.access);
+ const features = new Set(organization.features);
+ const relayPiiConfig = project.relayPiiConfig;
+ const apiMethod = 'PUT';
+ const title = t('Security & Privacy');
- return (
- <Fragment>
- <SentryDocumentTitle title={title} projectSlug={projectSlug} />
- <SettingsPageHeader title={title} />
- <Form
- saveOnBlur
- allowUndo
- initialData={initialData}
- apiMethod={apiMethod}
- apiEndpoint={endpoint}
- onSubmitSuccess={this.handleUpdateProject}
- onSubmitError={() => addErrorMessage('Unable to save change')}
- >
- <JsonForm
- additionalFieldProps={{organization}}
- features={features}
- disabled={!access.has('project:write')}
- forms={projectSecurityAndPrivacyGroups}
- />
- </Form>
- <DataScrubbing
- additionalContext={
- <span>
- {tct(
- 'These rules can be configured at the organization level in [linkToOrganizationSecurityAndPrivacy].',
- {
- linkToOrganizationSecurityAndPrivacy: (
- <Link to={`/settings/${organization.slug}/security-and-privacy/`}>
- {title}
- </Link>
- ),
- }
- )}
- </span>
- }
- endpoint={endpoint}
- relayPiiConfig={relayPiiConfig}
+ return (
+ <Fragment>
+ <SentryDocumentTitle title={title} projectSlug={projectSlug} />
+ <SettingsPageHeader title={title} />
+ <Form
+ saveOnBlur
+ allowUndo
+ initialData={initialData}
+ apiMethod={apiMethod}
+ apiEndpoint={endpoint}
+ onSubmitSuccess={handleUpdateProject}
+ onSubmitError={() => addErrorMessage('Unable to save change')}
+ >
+ <JsonForm
+ additionalFieldProps={{organization}}
+ features={features}
disabled={!access.has('project:write')}
- organization={organization}
- projectId={project.id}
- onSubmitSuccess={this.handleUpdateProject}
+ forms={projectSecurityAndPrivacyGroups}
/>
- </Fragment>
- );
- }
+ </Form>
+ <DataScrubbing
+ additionalContext={
+ <span>
+ {tct(
+ 'These rules can be configured at the organization level in [linkToOrganizationSecurityAndPrivacy].',
+ {
+ linkToOrganizationSecurityAndPrivacy: (
+ <Link to={`/settings/${organization.slug}/security-and-privacy/`}>
+ {title}
+ </Link>
+ ),
+ }
+ )}
+ </span>
+ }
+ endpoint={endpoint}
+ relayPiiConfig={relayPiiConfig}
+ disabled={!access.has('project:write')}
+ organization={organization}
+ project={project}
+ onSubmitSuccess={data => handleUpdateProject({...project, ...data})}
+ />
+ </Fragment>
+ );
}
-
-export default ProjectSecurityAndPrivacy;
diff --git a/static/app/views/settings/projectSecurityAndPrivacy/projectSecurityAndPrivacy.spec.tsx b/static/app/views/settings/projectSecurityAndPrivacy/projectSecurityAndPrivacy.spec.tsx
index f7fea42ac7a5ab..54053e54fbbafa 100644
--- a/static/app/views/settings/projectSecurityAndPrivacy/projectSecurityAndPrivacy.spec.tsx
+++ b/static/app/views/settings/projectSecurityAndPrivacy/projectSecurityAndPrivacy.spec.tsx
@@ -1,60 +1,134 @@
-import {mountWithTheme} from 'sentry-test/enzyme';
+import {InjectedRouter} from 'react-router';
+import {Location} from 'history';
+
+import {initializeOrg} from 'sentry-test/initializeOrg';
+import {render, screen} from 'sentry-test/reactTestingLibrary';
import {Organization} from 'sentry/types';
+import {OrganizationContext} from 'sentry/views/organizationContext';
+import {RouteContext} from 'sentry/views/routeContext';
import ProjectSecurityAndPrivacy from 'sentry/views/settings/projectSecurityAndPrivacy';
-const org = TestStubs.Organization();
-const project = TestStubs.ProjectDetails();
-
-function renderComponent(providedOrg?: Organization) {
- const organization = providedOrg ?? org;
-
- MockApiClient.addMockResponse({
- url: `/projects/${organization.slug}/${project.slug}/`,
- method: 'GET',
- body: project,
- });
-
- return mountWithTheme(
- <ProjectSecurityAndPrivacy
- {...TestStubs.routerContext().context}
- project={project}
- organization={organization}
- params={{orgId: organization.slug, projectId: project.slug}}
- />
+function ComponentProviders({
+ router,
+ location,
+ organization,
+ children,
+}: {
+ children: React.ReactNode;
+ location: Location;
+ organization: Organization;
+ router: InjectedRouter;
+}) {
+ return (
+ <OrganizationContext.Provider value={organization}>
+ <RouteContext.Provider
+ value={{
+ router,
+ location,
+ params: {},
+ routes: [],
+ }}
+ >
+ {children}
+ </RouteContext.Provider>
+ </OrganizationContext.Provider>
);
}
describe('projectSecurityAndPrivacy', function () {
it('renders form fields', function () {
- const wrapper = renderComponent();
+ const {organization, router} = initializeOrg();
+ const project = TestStubs.ProjectDetails();
- expect(wrapper.find('Switch[name="dataScrubber"]').prop('isActive')).toBeFalsy();
- expect(
- wrapper.find('Switch[name="dataScrubberDefaults"]').prop('isActive')
- ).toBeFalsy();
- expect(wrapper.find('Switch[name="scrubIPAddresses"]').prop('isActive')).toBeFalsy();
- expect(wrapper.find('TextArea[name="sensitiveFields"]').prop('value')).toBe(
- 'creditcard\nssn'
- );
- expect(wrapper.find('TextArea[name="safeFields"]').prop('value')).toBe(
- 'business-email\ncompany'
+ render(
+ <ComponentProviders
+ organization={organization}
+ router={router}
+ location={router.location}
+ >
+ <ProjectSecurityAndPrivacy project={project} organization={organization} />
+ </ComponentProviders>
);
+
+ expect(
+ screen.getByRole('checkbox', {
+ name: 'Enable server-side data scrubbing',
+ })
+ ).not.toBeChecked();
+
+ expect(
+ screen.getByRole('checkbox', {
+ name: 'Enable to apply default scrubbers to prevent things like passwords and credit cards from being stored',
+ })
+ ).not.toBeChecked();
+
+ expect(
+ screen.getByRole('checkbox', {
+ name: 'Enable to prevent IP addresses from being stored for new events',
+ })
+ ).not.toBeChecked();
+
+ expect(
+ screen.getByRole('textbox', {
+ name: 'Enter field names which data scrubbers should ignore. Separate multiple entries with a newline',
+ })
+ ).toHaveValue('business-email\ncompany');
+
+ expect(
+ screen.getByRole('textbox', {
+ name: 'Enter additional field names to match against when scrubbing data. Separate multiple entries with a newline',
+ })
+ ).toHaveValue('creditcard\nssn');
+
+ expect(
+ screen.getByRole('textbox', {
+ name: 'Enter additional field names to match against when scrubbing data. Separate multiple entries with a newline',
+ })
+ ).toHaveValue('creditcard\nssn');
});
it('disables field when equivalent org setting is true', function () {
- const newOrganization = {...org};
- newOrganization.dataScrubber = true;
- newOrganization.scrubIPAddresses = false;
+ const {organization, router} = initializeOrg();
+ const project = TestStubs.ProjectDetails();
+
+ organization.dataScrubber = true;
+ organization.scrubIPAddresses = false;
- const wrapper = renderComponent(newOrganization);
+ MockApiClient.addMockResponse({
+ url: `/projects/${organization.slug}/${project.slug}/`,
+ method: 'GET',
+ body: project,
+ });
- expect(wrapper.find('Switch[name="scrubIPAddresses"]').prop('isDisabled')).toBe(
- false
+ render(
+ <ComponentProviders
+ organization={organization}
+ router={router}
+ location={router.location}
+ >
+ <ProjectSecurityAndPrivacy project={project} organization={organization} />
+ </ComponentProviders>
);
- expect(wrapper.find('Switch[name="scrubIPAddresses"]').prop('isActive')).toBeFalsy();
- expect(wrapper.find('Switch[name="dataScrubber"]').prop('isDisabled')).toBe(true);
- expect(wrapper.find('Switch[name="dataScrubber"]').prop('isActive')).toBe(true);
+ expect(
+ screen.getByRole('checkbox', {
+ name: 'Enable to prevent IP addresses from being stored for new events',
+ })
+ ).toBeEnabled();
+
+ expect(
+ screen.getByRole('checkbox', {
+ name: 'Enable to prevent IP addresses from being stored for new events',
+ })
+ ).not.toBeChecked();
+
+ expect(
+ screen.getByRole('checkbox', {name: 'Enable server-side data scrubbing'})
+ ).toBeDisabled();
+
+ expect(
+ screen.getByRole('checkbox', {name: 'Enable server-side data scrubbing'})
+ ).toBeChecked();
});
});
|
dec9f69d4c3edcff60332300f6b1d7b7adfb602e
|
2025-01-03 23:08:22
|
George Gritsouk
|
chore(dashboards): Remove widget viewer minimap feature declaration (#82863)
| false
|
Remove widget viewer minimap feature declaration (#82863)
|
chore
|
diff --git a/src/sentry/features/temporary.py b/src/sentry/features/temporary.py
index 51119782cdd7e3..8e3241aa02668e 100644
--- a/src/sentry/features/temporary.py
+++ b/src/sentry/features/temporary.py
@@ -529,8 +529,6 @@ def register_temporary_features(manager: FeatureManager):
manager.add("organizations:visibility-explore-dataset", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
# Enable RPC on the new explore page
manager.add("organizations:visibility-explore-rpc", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
- # Enable minimap in the widget viewer modal in dashboards
- manager.add("organizations:widget-viewer-modal-minimap", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True)
# Enabled unresolved issue webhook for organization
manager.add("organizations:webhooks-unresolved", OrganizationFeature, FeatureHandlerStrategy.OPTIONS, api_expose=True)
# Enable dual writing for metric alert issues (see: alerts create issues)
|
604a7d759a152a72e757b410d5e8677d97790f06
|
2023-09-01 01:56:15
|
Nar Saynorath
|
feat(stat-detectors): Show bad events in All Events tab (#55554)
| false
|
Show bad events in All Events tab (#55554)
|
feat
|
diff --git a/static/app/components/events/eventStatisticalDetector/eventComparison/eventDisplay.tsx b/static/app/components/events/eventStatisticalDetector/eventComparison/eventDisplay.tsx
index 9fff0f2efd9d84..cfa135796d13be 100644
--- a/static/app/components/events/eventStatisticalDetector/eventComparison/eventDisplay.tsx
+++ b/static/app/components/events/eventStatisticalDetector/eventComparison/eventDisplay.tsx
@@ -25,6 +25,26 @@ import {useApiQuery} from 'sentry/utils/queryClient';
import {useLocation} from 'sentry/utils/useLocation';
import useOrganization from 'sentry/utils/useOrganization';
+export function getSampleEventQuery({
+ transaction,
+ durationBaseline,
+ addUpperBound = true,
+}: {
+ durationBaseline: number;
+ transaction: string;
+ addUpperBound?: boolean;
+}) {
+ const baseQuery = `event.type:transaction transaction:"${transaction}" transaction.duration:>=${
+ durationBaseline * 0.5
+ }ms`;
+
+ if (addUpperBound) {
+ return `${baseQuery} transaction.duration:<=${durationBaseline * 1.5}ms`;
+ }
+
+ return baseQuery;
+}
+
// A hook for getting "sample events" for a transaction
// In its current state it will just fetch at most 5 events that match the
// transaction name within a range of the duration baseline provided
@@ -48,9 +68,7 @@ function useFetchSampleEvents({
start: new Date(start * 1000).toISOString(),
end: new Date(end * 1000).toISOString(),
fields: [{field: 'id'}],
- query: `event.type:transaction transaction:"${transaction}" transaction.duration:>=${
- durationBaseline * 0.7
- }ms transaction.duration:<=${durationBaseline * 1.3}ms`,
+ query: getSampleEventQuery({transaction, durationBaseline}),
createdBy: undefined,
display: undefined,
diff --git a/static/app/views/issueDetails/allEventsTable.tsx b/static/app/views/issueDetails/allEventsTable.tsx
index 5975ea88bc2296..373c7993308d3a 100644
--- a/static/app/views/issueDetails/allEventsTable.tsx
+++ b/static/app/views/issueDetails/allEventsTable.tsx
@@ -1,6 +1,7 @@
import {useEffect, useState} from 'react';
import {Location} from 'history';
+import {getSampleEventQuery} from 'sentry/components/events/eventStatisticalDetector/eventComparison/eventDisplay';
import LoadingError from 'sentry/components/loadingError';
import {
PlatformCategory,
@@ -8,7 +9,13 @@ import {
profiling as PROFILING_PLATFORMS,
} from 'sentry/data/platformCategories';
import {t} from 'sentry/locale';
-import {EventTransaction, Group, IssueCategory, Organization} from 'sentry/types';
+import {
+ EventTransaction,
+ Group,
+ IssueCategory,
+ IssueType,
+ Organization,
+} from 'sentry/types';
import EventView, {decodeSorts} from 'sentry/utils/discover/eventView';
import {DiscoverDatasets} from 'sentry/utils/discover/types';
import {getConfigForIssueType} from 'sentry/utils/issueTypeConfig';
@@ -71,13 +78,32 @@ function AllEventsTable(props: Props) {
eventView.sorts = [{field: 'timestamp', kind: 'desc'}];
}
- const idQuery =
- group.issueCategory === IssueCategory.PERFORMANCE && !groupIsOccurrenceBacked
- ? `performance.issue_ids:${issueId} event.type:transaction`
- : `issue.id:${issueId}`;
+ eventView.statsPeriod = '90d';
+
+ let idQuery = `issue.id:${issueId}`;
+ if (group.issueCategory === IssueCategory.PERFORMANCE && !groupIsOccurrenceBacked) {
+ idQuery = `performance.issue_ids:${issueId} event.type:transaction`;
+ } else if (
+ group.issueType === IssueType.PERFORMANCE_DURATION_REGRESSION &&
+ groupIsOccurrenceBacked
+ ) {
+ const {transaction, aggregateRange2, breakpoint, requestEnd} =
+ data?.occurrence?.evidenceData ?? {};
+
+ // Surface the "bad" events that occur after the breakpoint
+ idQuery = getSampleEventQuery({
+ transaction,
+ durationBaseline: aggregateRange2,
+ addUpperBound: false,
+ });
+
+ eventView.dataset = DiscoverDatasets.DISCOVER;
+ eventView.start = new Date(breakpoint * 1000).toISOString();
+ eventView.end = new Date(requestEnd * 1000).toISOString();
+ eventView.statsPeriod = undefined;
+ }
eventView.project = [parseInt(group.project.id, 10)];
eventView.query = `${idQuery} ${props.location.query.query || ''}`;
- eventView.statsPeriod = '90d';
if (error || isLoadingError) {
return (
|
d77a1e87cbf5fd124f3bf096fe89c4dee6934031
|
2023-03-09 06:17:31
|
Evan Purkhiser
|
fix(replays): Split validator from serializer (#45552)
| false
|
Split validator from serializer (#45552)
|
fix
|
diff --git a/src/sentry/replays/endpoints/organization_replay_index.py b/src/sentry/replays/endpoints/organization_replay_index.py
index 1eff81b10fc660..463376dceb9f9e 100644
--- a/src/sentry/replays/endpoints/organization_replay_index.py
+++ b/src/sentry/replays/endpoints/organization_replay_index.py
@@ -11,7 +11,7 @@
from sentry.models.organization import Organization
from sentry.replays.post_process import process_raw_response
from sentry.replays.query import query_replays_collection, replay_url_parser_config
-from sentry.replays.serializers import ReplaySerializer
+from sentry.replays.validators import ReplayValidator
@region_silo_endpoint
@@ -37,11 +37,11 @@ def get(self, request: Request, organization: Organization) -> Response:
except NoProjects:
return Response({"data": []}, status=200)
- serializer = ReplaySerializer(data=request.GET)
- if not serializer.is_valid():
- raise ParseError(serializer.errors)
+ result = ReplayValidator(data=request.GET)
+ if not result.is_valid():
+ raise ParseError(result.errors)
- for key, value in serializer.validated_data.items():
+ for key, value in result.validated_data.items():
if key not in filter_params:
filter_params[key] = value
diff --git a/src/sentry/replays/serializers.py b/src/sentry/replays/serializers.py
index 380d6c14e83b4a..a38b7ef0446f08 100644
--- a/src/sentry/replays/serializers.py
+++ b/src/sentry/replays/serializers.py
@@ -1,5 +1,3 @@
-from rest_framework import serializers
-
from sentry.api.serializers import Serializer
from sentry.replays.models import ReplayRecordingSegment
@@ -12,68 +10,3 @@ def serialize(self, obj: ReplayRecordingSegment, attrs, user):
"projectId": str(obj.project_id),
"dateAdded": obj.date_added,
}
-
-
-VALID_FIELD_SET = {
- "id",
- "title",
- "project_id",
- "errorIds",
- "traceIds",
- "urls",
- "startedAt",
- "finishedAt",
- "duration",
- "countErrors",
- "countSegments",
- "countUrls",
- "longestTransaction",
- "platform",
- "environment",
- "release",
- "dist",
- "user",
- "os",
- "browser",
- "device",
- "sdk",
- "tags",
- "activity",
-}
-
-
-class ReplaySerializer(serializers.Serializer):
- statsPeriod = serializers.CharField(
- help_text=(
- "This defines the range of the time series, relative to now. "
- "The range is given in a `<number><unit>` format. "
- "For example `1d` for a one day range. Possible units are `m` for minutes, `h` for hours, `d` for days and `w` for weeks."
- "You must either provide a `statsPeriod`, or a `start` and `end`."
- ),
- required=False,
- )
- start = serializers.DateTimeField(
- help_text="This defines the start of the time series range as an explicit datetime, either in UTC ISO8601 or epoch seconds."
- "Use along with `end` instead of `statsPeriod`.",
- required=False,
- )
- end = serializers.DateTimeField(
- help_text=(
- "This defines the inclusive end of the time series range as an explicit datetime, either in UTC ISO8601 or epoch seconds."
- "Use along with `start` instead of `statsPeriod`."
- ),
- required=False,
- )
- field = serializers.ChoiceField(
- VALID_FIELD_SET,
- help_text="Specifies a field that should be marshaled in the output. Invalid fields will be rejected.",
- required=False,
- )
- project = serializers.ListField(
- required=False, help_text="The ID of the projects to filter by."
- )
- environment = serializers.CharField(help_text="The environment to filter by.", required=False)
- sort = serializers.CharField(help_text="The field to sort the output by.", required=False)
- query = serializers.CharField(
- help_text="A structured query string to filter the output by.", required=False
- )
diff --git a/src/sentry/replays/validators.py b/src/sentry/replays/validators.py
new file mode 100644
index 00000000000000..5f5f1c611ffa2d
--- /dev/null
+++ b/src/sentry/replays/validators.py
@@ -0,0 +1,65 @@
+from rest_framework import serializers
+
+VALID_FIELD_SET = {
+ "id",
+ "title",
+ "project_id",
+ "errorIds",
+ "traceIds",
+ "urls",
+ "startedAt",
+ "finishedAt",
+ "duration",
+ "countErrors",
+ "countSegments",
+ "countUrls",
+ "longestTransaction",
+ "platform",
+ "environment",
+ "release",
+ "dist",
+ "user",
+ "os",
+ "browser",
+ "device",
+ "sdk",
+ "tags",
+ "activity",
+}
+
+
+class ReplayValidator(serializers.Serializer):
+ statsPeriod = serializers.CharField(
+ help_text=(
+ "This defines the range of the time series, relative to now. "
+ "The range is given in a `<number><unit>` format. "
+ "For example `1d` for a one day range. Possible units are `m` for minutes, `h` for hours, `d` for days and `w` for weeks."
+ "You must either provide a `statsPeriod`, or a `start` and `end`."
+ ),
+ required=False,
+ )
+ start = serializers.DateTimeField(
+ help_text="This defines the start of the time series range as an explicit datetime, either in UTC ISO8601 or epoch seconds."
+ "Use along with `end` instead of `statsPeriod`.",
+ required=False,
+ )
+ end = serializers.DateTimeField(
+ help_text=(
+ "This defines the inclusive end of the time series range as an explicit datetime, either in UTC ISO8601 or epoch seconds."
+ "Use along with `start` instead of `statsPeriod`."
+ ),
+ required=False,
+ )
+ field = serializers.ChoiceField(
+ VALID_FIELD_SET,
+ help_text="Specifies a field that should be marshaled in the output. Invalid fields will be rejected.",
+ required=False,
+ )
+ project = serializers.ListField(
+ required=False, help_text="The ID of the projects to filter by."
+ )
+ environment = serializers.CharField(help_text="The environment to filter by.", required=False)
+ sort = serializers.CharField(help_text="The field to sort the output by.", required=False)
+ query = serializers.CharField(
+ help_text="A structured query string to filter the output by.", required=False
+ )
|
e171b81e66f65825d4f9f38db2cc91d8927621b3
|
2020-01-10 01:19:06
|
josh
|
feat(django): pytest startup and test collection on Django 1.11 (#16105)
| false
|
pytest startup and test collection on Django 1.11 (#16105)
|
feat
|
diff --git a/.travis.yml b/.travis.yml
index 99a149a358bdc0..ff5e1a6fe9f751 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -149,6 +149,21 @@ matrix:
name: 'Acceptance'
env: TEST_SUITE=acceptance USE_SNUBA=1
+ # allowed to fail
+ - <<: *postgres_default
+ name: '[Django 1.11] Backend with migrations [Postgres] (1/2)'
+ env: DJANGO_VERSION=">=1.11,<1.12" TEST_SUITE=postgres DB=postgres TOTAL_TEST_GROUPS=2 TEST_GROUP=0 MIGRATIONS_TEST_MIGRATE=1
+
+ # allowed to fail
+ - <<: *postgres_default
+ name: '[Django 1.11] Backend with migrations [Postgres] (2/2)'
+ env: DJANGO_VERSION=">=1.11,<1.12" TEST_SUITE=postgres DB=postgres TOTAL_TEST_GROUPS=2 TEST_GROUP=1 MIGRATIONS_TEST_MIGRATE=1
+
+ # allowed to fail
+ - <<: *acceptance_default
+ name: '[Django 1.11] Acceptance'
+ env: DJANGO_VERSION=">=1.11,<1.12" TEST_SUITE=acceptance USE_SNUBA=1 PERCY_ENABLE=0
+
- <<: *acceptance_default
name: 'Plugins'
env: TEST_SUITE=plugins DB=postgres PERCY_TOKEN=${PLUGIN_PERCY_TOKEN}
@@ -214,6 +229,29 @@ matrix:
before_script:
- psql -c 'create database sentry;' -U postgres
+ # allowed to fail
+ - python: 2.7
+ name: '[Django 1.11] Snuba Integration with migrations'
+ env: DJANGO_VERSION=">=1.11,<1.12" TEST_SUITE=snuba USE_SNUBA=1 SENTRY_ZOOKEEPER_HOSTS=localhost:2181 SENTRY_KAFKA_HOSTS=localhost:9092 MIGRATIONS_TEST_MIGRATE=1
+ services:
+ - docker
+ - memcached
+ - redis-server
+ - postgresql
+ before_install:
+ - *pip_install
+ - docker run -d --network host --name zookeeper -e ZOOKEEPER_CLIENT_PORT=2181 confluentinc/cp-zookeeper:4.1.0
+ - docker run -d --network host --name kafka -e KAFKA_ZOOKEEPER_CONNECT=localhost:2181 -e KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://localhost:9092 -e KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1 confluentinc/cp-kafka:4.1.0
+ - docker run -d --network host --name clickhouse-server --ulimit nofile=262144:262144 yandex/clickhouse-server:19.11
+ - docker run -d --network host --name snuba --env SNUBA_SETTINGS=test --env CLICKHOUSE_SERVER=localhost:9000 getsentry/snuba
+ - docker ps -a
+ install:
+ - python setup.py install_egg_info
+ - pip install -U -e ".[dev]"
+ - pip install confluent-kafka
+ before_script:
+ - psql -c 'create database sentry;' -U postgres
+
# Deploy 'storybook' (component & style guide) - allowed to fail
- name: 'Storybook Deploy'
language: node_js
@@ -235,6 +273,10 @@ matrix:
allow_failures:
- name: 'Storybook Deploy'
+ - name: '[Django 1.11] Backend with migrations [Postgres] (1/2)'
+ - name: '[Django 1.11] Backend with migrations [Postgres] (2/2)'
+ - name: '[Django 1.11] Acceptance'
+ - name: '[Django 1.11] Snuba Integration with migrations'
notifications:
webhooks:
diff --git a/src/sentry/db/postgres/base.py b/src/sentry/db/postgres/base.py
index 51e67dc9fc73ac..ac29530ba44024 100644
--- a/src/sentry/db/postgres/base.py
+++ b/src/sentry/db/postgres/base.py
@@ -3,6 +3,8 @@
from six import string_types
import psycopg2 as Database
+import django
+
# Some of these imports are unused, but they are inherited from other engines
# and should be available as part of the backend ``base.py`` namespace.
from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper
@@ -95,7 +97,18 @@ def _set_isolation_level(self, level):
@auto_reconnect_connection
def _cursor(self, *args, **kwargs):
cursor = super(DatabaseWrapper, self)._cursor()
- return CursorWrapper(self, cursor)
+ if django.VERSION[:2] < (1, 11):
+ return CursorWrapper(self, cursor)
+ return cursor
+
+ # We're overriding this internal method that's present in Django 1.11+, because
+ # things were shuffled around since 1.10 resulting in not constructing a django CursorWrapper
+ # with our CursorWrapper. We need to be passing our wrapped cursor to their wrapped cursor,
+ # not the other way around since then we'll lose things like __enter__ due to the way this
+ # wrapper is working (getattr on self.cursor).
+ def _prepare_cursor(self, cursor):
+ cursor = super(DatabaseWrapper, self)._prepare_cursor(CursorWrapper(self, cursor))
+ return cursor
def close(self, reconnect=False):
"""
diff --git a/src/sentry/new_migrations/monkey/__init__.py b/src/sentry/new_migrations/monkey/__init__.py
index c998459e8748ea..5fd96cd0dae9c7 100644
--- a/src/sentry/new_migrations/monkey/__init__.py
+++ b/src/sentry/new_migrations/monkey/__init__.py
@@ -7,7 +7,7 @@
from django.db.migrations import migration, executor, writer
-LAST_VERIFIED_DJANGO_VERSION = (1, 10)
+LAST_VERIFIED_DJANGO_VERSION = (1, 11)
CHECK_MESSAGE = """Looks like you're trying to upgrade Django! Since we monkeypatch
the Django migration library in several places, please verify that we have the latest
code, and that the monkeypatching still works as expected. Currently the main things
diff --git a/src/sentry/runner/initializer.py b/src/sentry/runner/initializer.py
index 394bbef6d5a966..c635281515878f 100644
--- a/src/sentry/runner/initializer.py
+++ b/src/sentry/runner/initializer.py
@@ -404,7 +404,8 @@ def __model_unpickle_compat(model_id, attrs=None, factory=None):
attrs = [] if attrs is None else attrs
factory = django.db.models.base.simple_class_factory if factory is None else factory
return model_unpickle(model_id, attrs, factory)
- elif VERSION[:2] == (1, 10):
+ # TODO(joshuarli): unverified on 1.11, but i'm doing this to unblock tests for now
+ elif VERSION[:2] in [(1, 10), (1, 11)]:
return model_unpickle(model_id)
else:
raise NotImplementedError
|
9ee245de4c97ef65894d46aecd6550c1ef75acda
|
2024-07-15 21:57:53
|
Jodi Jang
|
chore(similarity): Add killswitches for each feature flag (#74274)
| false
|
Add killswitches for each feature flag (#74274)
|
chore
|
diff --git a/src/sentry/options/defaults.py b/src/sentry/options/defaults.py
index 07474ed2b173e1..cf691c7f8527dc 100644
--- a/src/sentry/options/defaults.py
+++ b/src/sentry/options/defaults.py
@@ -824,6 +824,30 @@
type=Bool,
flags=FLAG_MODIFIABLE_BOOL | FLAG_AUTOMATOR_MODIFIABLE,
)
+register(
+ "seer.similarity-embeddings-killswitch.enabled",
+ default=False,
+ type=Bool,
+ flags=FLAG_MODIFIABLE_BOOL | FLAG_AUTOMATOR_MODIFIABLE,
+)
+register(
+ "seer.similarity-embeddings-grouping-killswitch.enabled",
+ default=False,
+ type=Bool,
+ flags=FLAG_MODIFIABLE_BOOL | FLAG_AUTOMATOR_MODIFIABLE,
+)
+register(
+ "seer.similarity-embeddings-metadata-killswitch.enabled",
+ default=False,
+ type=Bool,
+ flags=FLAG_MODIFIABLE_BOOL | FLAG_AUTOMATOR_MODIFIABLE,
+)
+register(
+ "seer.similarity-embeddings-delete-by-hash-killswitch.enabled",
+ default=False,
+ type=Bool,
+ flags=FLAG_MODIFIABLE_BOOL | FLAG_AUTOMATOR_MODIFIABLE,
+)
register(
"seer.severity-killswitch.enabled",
default=False,
|
b2f2161f32da3617f780947ba89ca1b6e041e795
|
2022-08-03 23:39:16
|
Nikhar Saxena
|
feat(eventstore): Add method to retrieve transactions (#37386)
| false
|
Add method to retrieve transactions (#37386)
|
feat
|
diff --git a/src/sentry/eventstore/base.py b/src/sentry/eventstore/base.py
index 78a226dee57c72..7075585dfa0a48 100644
--- a/src/sentry/eventstore/base.py
+++ b/src/sentry/eventstore/base.py
@@ -272,3 +272,30 @@ def bind_nodes(self, object_list, node_name="data"):
for item, node in object_node_list:
data = node_results.get(node.id) or {}
node.bind_data(data, ref=node.get_ref(item))
+
+ def get_unfetched_transactions(
+ self,
+ snuba_filter,
+ orderby=None,
+ limit=100,
+ offset=0,
+ referrer="eventstore.get_unfetched_transactions",
+ ):
+ """
+ Same as get_unfetched_events but returns transactions.
+ Only the event ID, projectID and timestamp field will be present without
+ an additional fetch to nodestore.
+
+ Used for fetching large volumes of transactions that do not need data
+ loaded from nodestore. Currently this is just used for transaction
+ data deletions where we just need the transactions IDs in order to
+ process the deletions.
+
+ Arguments:
+ snuba_filter (Filter): Filter
+ orderby (Sequence[str]): List of fields to order by - default ['-time', '-event_id']
+ limit (int): Query limit - default 100
+ offset (int): Query offset - default 0
+ referrer (string): Referrer - default "eventstore.get_unfetched_transactions"
+ """
+ raise NotImplementedError
diff --git a/src/sentry/eventstore/snuba/backend.py b/src/sentry/eventstore/snuba/backend.py
index 286bfd5e4eb59f..6658beff0f671d 100644
--- a/src/sentry/eventstore/snuba/backend.py
+++ b/src/sentry/eventstore/snuba/backend.py
@@ -336,3 +336,43 @@ def __make_event(self, snuba_data):
return Event(
event_id=event_id, group_id=group_id, project_id=project_id, snuba_data=snuba_data
)
+
+ def get_unfetched_transactions(
+ self,
+ filter,
+ orderby=None,
+ limit=DEFAULT_LIMIT,
+ offset=DEFAULT_OFFSET,
+ referrer="eventstore.get_unfetched_transactions",
+ ):
+ """
+ Get transactions from Snuba, without node data loaded.
+ """
+ assert filter, "You must provide a filter"
+ cols = self.__get_columns()
+ orderby = orderby or DESC_ORDERING
+
+ result = snuba.aliased_query(
+ selected_columns=cols,
+ start=filter.start,
+ end=filter.end,
+ conditions=filter.conditions,
+ filter_keys=filter.filter_keys,
+ orderby=orderby,
+ limit=limit,
+ offset=offset,
+ referrer=referrer,
+ dataset=snuba.Dataset.Transactions,
+ )
+
+ if "error" not in result:
+ events = [self.__make_transaction(evt) for evt in result["data"]]
+ return events
+
+ return []
+
+ def __make_transaction(self, snuba_data):
+ event_id = snuba_data[Columns.EVENT_ID.value.event_name]
+ project_id = snuba_data[Columns.PROJECT_ID.value.event_name]
+
+ return Event(event_id=event_id, project_id=project_id, snuba_data=snuba_data)
diff --git a/tests/sentry/eventstore/snuba/test_backend.py b/tests/sentry/eventstore/snuba/test_backend.py
index 7c8f7987877219..d3c8b298c6b67a 100644
--- a/tests/sentry/eventstore/snuba/test_backend.py
+++ b/tests/sentry/eventstore/snuba/test_backend.py
@@ -55,7 +55,7 @@ def setUp(self):
event_data["start_timestamp"] = iso_format(before_now(minutes=1, seconds=1))
event_data["event_id"] = "d" * 32
- self.transaction_event = self.store_event(data=event_data, project_id=self.project2.id)
+ self.transaction_event = self.store_event(data=event_data, project_id=self.project1.id)
event_data_2 = load_data("transaction")
event_data_2["timestamp"] = iso_format(before_now(seconds=30))
@@ -65,6 +65,24 @@ def setUp(self):
self.transaction_event_2 = self.store_event(data=event_data_2, project_id=self.project2.id)
+ event_data_3 = load_data("transaction")
+ event_data_3["timestamp"] = iso_format(before_now(seconds=30))
+ event_data_3["start_timestamp"] = iso_format(before_now(seconds=31))
+
+ event_data_3["event_id"] = "f" * 32
+
+ self.transaction_event_3 = self.store_event(data=event_data_3, project_id=self.project2.id)
+
+ """
+ event_data_4 = load_data("transaction")
+ event_data_4["timestamp"] = iso_format(before_now(seconds=30))
+ event_data_4["start_timestamp"] = iso_format(before_now(seconds=31))
+
+ event_data_4["event_id"] = "g" * 32
+
+ self.transaction_event_4 = self.store_event(data=event_data_4, project_id=self.project2.id)
+ """
+
self.eventstore = SnubaEventStorage()
def test_get_events(self):
@@ -105,6 +123,20 @@ def test_get_unfetched_events(self, get_multi):
assert len(events) == 1
assert get_multi.call_count == 0
+ @mock.patch("sentry.nodestore.get_multi")
+ def test_get_unfetched_transactions(self, get_multi):
+ transactions_proj1 = self.eventstore.get_unfetched_transactions(
+ filter=Filter(project_ids=[self.project1.id])
+ )
+ assert len(transactions_proj1) == 1
+ assert get_multi.call_count == 0
+
+ transactions_proj2 = self.eventstore.get_unfetched_transactions(
+ filter=Filter(project_ids=[self.project2.id])
+ )
+ assert len(transactions_proj2) == 2
+ assert get_multi.call_count == 0
+
def test_get_event_by_id(self):
# Get valid event
event = self.eventstore.get_event_by_id(self.project1.id, "a" * 32)
@@ -114,13 +146,13 @@ def test_get_event_by_id(self):
assert event.group_id == event.group.id
# Get non existent event
- event = self.eventstore.get_event_by_id(self.project2.id, "f" * 32)
+ event = self.eventstore.get_event_by_id(self.project2.id, "z" * 32)
assert event is None
# Get transaction
- event = self.eventstore.get_event_by_id(self.project2.id, self.transaction_event.event_id)
+ event = self.eventstore.get_event_by_id(self.project2.id, self.transaction_event_2.event_id)
- assert event.event_id == "d" * 32
+ assert event.event_id == "e" * 32
assert event.get_event_type() == "transaction"
assert event.project_id == self.project2.id
@@ -241,7 +273,7 @@ def test_get_latest_or_oldest_event_id(self):
oldest_event = self.eventstore.get_earliest_event_id(event, filter=_filter)
latest_event = self.eventstore.get_latest_event_id(event, filter=_filter)
assert oldest_event == (str(self.project1.id), "a" * 32)
- assert latest_event == (str(self.project2.id), "e" * 32)
+ assert latest_event == (str(self.project2.id), "f" * 32)
# Returns none when no latest/oldest event that meets conditions
event = self.eventstore.get_event_by_id(self.project2.id, "b" * 32)
@@ -253,18 +285,18 @@ def test_get_latest_or_oldest_event_id(self):
def test_transaction_get_next_prev_event_id(self):
_filter = Filter(
- project_ids=[self.project1.id, self.project2.id],
+ project_ids=[self.project2.id],
conditions=[["event.type", "=", "transaction"]],
)
- event = self.eventstore.get_event_by_id(self.project2.id, "e" * 32)
+ event = self.eventstore.get_event_by_id(self.project2.id, "f" * 32)
prev_event = self.eventstore.get_prev_event_id(event, filter=_filter)
next_event = self.eventstore.get_next_event_id(event, filter=_filter)
- assert prev_event == (str(self.project2.id), "d" * 32)
+ assert prev_event == (str(self.project2.id), "e" * 32)
assert next_event is None
- event = self.eventstore.get_event_by_id(self.project2.id, "d" * 32)
+ event = self.eventstore.get_event_by_id(self.project2.id, "e" * 32)
prev_event = self.eventstore.get_prev_event_id(event, filter=_filter)
next_event = self.eventstore.get_next_event_id(event, filter=_filter)
assert prev_event is None
- assert next_event == (str(self.project2.id), "e" * 32)
+ assert next_event == (str(self.project2.id), "f" * 32)
|
5729c9687602640c6430c1745dcb27dca98f6c26
|
2022-10-10 19:14:14
|
Matej Minar
|
feat(sampling): Add parent projects alert [TET-338] (#39598)
| false
|
Add parent projects alert [TET-338] (#39598)
|
feat
|
diff --git a/static/app/types/sampling.tsx b/static/app/types/sampling.tsx
index 9b68150c6b3412..b6536547f69b45 100644
--- a/static/app/types/sampling.tsx
+++ b/static/app/types/sampling.tsx
@@ -102,6 +102,13 @@ export type SamplingRule = {
export type SamplingDistribution = {
endTimestamp: string | null;
+ parentProjectBreakdown:
+ | null
+ | {
+ percentage: number;
+ project: string;
+ projectId: number;
+ }[];
projectBreakdown:
| null
| {
diff --git a/static/app/views/settings/project/server-side-sampling/samplingBreakdown.spec.tsx b/static/app/views/settings/project/server-side-sampling/samplingBreakdown.spec.tsx
index b845bc89155dcc..cbedfe3541793a 100644
--- a/static/app/views/settings/project/server-side-sampling/samplingBreakdown.spec.tsx
+++ b/static/app/views/settings/project/server-side-sampling/samplingBreakdown.spec.tsx
@@ -18,11 +18,7 @@ describe('Server-Side Sampling - SamplingBreakdown', function () {
render(<SamplingBreakdown orgSlug={organization.slug} />);
- expect(
- screen.getByText(
- 'There were no traces initiated from this project in the last 30 days.'
- )
- ).toBeInTheDocument();
+ expect(screen.getByText(/This project made no/)).toBeInTheDocument();
});
it('renders project breakdown', function () {
diff --git a/static/app/views/settings/project/server-side-sampling/samplingBreakdown.tsx b/static/app/views/settings/project/server-side-sampling/samplingBreakdown.tsx
index c450fbe6e7fd9e..6adbc47d40216d 100644
--- a/static/app/views/settings/project/server-side-sampling/samplingBreakdown.tsx
+++ b/static/app/views/settings/project/server-side-sampling/samplingBreakdown.tsx
@@ -63,7 +63,7 @@ export function SamplingBreakdown({orgSlug}: Props) {
<HeaderTitle>{t('Transaction Breakdown')}</HeaderTitle>
<QuestionTooltip
title={tct(
- 'Sampling rules defined here can also affect other projects. [learnMore: Learn more]',
+ 'Shows which projects are affected by the sampling decisions this project makes. [learnMore: Learn more]',
{
learnMore: (
<ExternalLink
@@ -110,8 +110,28 @@ export function SamplingBreakdown({orgSlug}: Props) {
</Projects>
) : (
<EmptyMessage>
- {t(
- 'There were no traces initiated from this project in the last 30 days.'
+ {tct(
+ 'This project made no [samplingDecisions] within the last 30 days.',
+ {
+ samplingDecisions: (
+ <Tooltip
+ title={tct(
+ 'The first transaction in a trace makes the sampling decision for all following transactions. [learnMore: Learn more]',
+ {
+ learnMore: (
+ <ExternalLink
+ href={`${SERVER_SIDE_SAMPLING_DOC_LINK}#traces--propagation-of-sampling-decisions`}
+ />
+ ),
+ }
+ )}
+ showUnderline
+ isHoverable
+ >
+ {t('sampling decisions')}
+ </Tooltip>
+ ),
+ }
)}
</EmptyMessage>
)}
diff --git a/static/app/views/settings/project/server-side-sampling/samplingFromOtherProject.spec.tsx b/static/app/views/settings/project/server-side-sampling/samplingFromOtherProject.spec.tsx
new file mode 100644
index 00000000000000..51a7566b8a638a
--- /dev/null
+++ b/static/app/views/settings/project/server-side-sampling/samplingFromOtherProject.spec.tsx
@@ -0,0 +1,63 @@
+import {act, render, screen} from 'sentry-test/reactTestingLibrary';
+
+import ProjectsStore from 'sentry/stores/projectsStore';
+import {ServerSideSamplingStore} from 'sentry/stores/serverSideSamplingStore';
+
+import {SamplingFromOtherProject} from './samplingFromOtherProject';
+import {getMockData, mockedSamplingDistribution} from './testUtils';
+
+export const samplingBreakdownTitle = 'Transaction Breakdown';
+
+describe('Server-Side Sampling - SamplingFromOtherProject', function () {
+ afterEach(function () {
+ act(() => ProjectsStore.reset());
+ act(() => ServerSideSamplingStore.reset());
+ });
+
+ it('renders the parent projects', function () {
+ const {organization} = getMockData();
+ const parentProjectBreakdown = mockedSamplingDistribution.parentProjectBreakdown;
+
+ ProjectsStore.loadInitialData(
+ parentProjectBreakdown!.map(p =>
+ TestStubs.Project({id: p.projectId, slug: p.project})
+ )
+ );
+
+ ServerSideSamplingStore.distributionRequestSuccess(mockedSamplingDistribution);
+
+ render(<SamplingFromOtherProject orgSlug={organization.slug} projectSlug="abc" />);
+
+ expect(screen.getByText('parent-project')).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ 'The following project made sampling decisions for this project. You might want to set up rules there.'
+ )
+ ).toBeInTheDocument();
+ });
+
+ it('does not render if there are no parent projects', function () {
+ const {organization} = getMockData();
+ const parentProjectBreakdown = mockedSamplingDistribution.parentProjectBreakdown;
+
+ ProjectsStore.loadInitialData(
+ parentProjectBreakdown!.map(p =>
+ TestStubs.Project({id: p.projectId, slug: p.project})
+ )
+ );
+
+ ServerSideSamplingStore.distributionRequestSuccess({
+ ...mockedSamplingDistribution,
+ parentProjectBreakdown: [],
+ });
+
+ render(<SamplingFromOtherProject orgSlug={organization.slug} projectSlug="abc" />);
+
+ expect(screen.queryByText('parent-project')).not.toBeInTheDocument();
+ expect(
+ screen.queryByText(
+ 'The following project made sampling decisions for this project. You might want to set up rules there.'
+ )
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/static/app/views/settings/project/server-side-sampling/samplingFromOtherProject.tsx b/static/app/views/settings/project/server-side-sampling/samplingFromOtherProject.tsx
new file mode 100644
index 00000000000000..56c81104d5da5b
--- /dev/null
+++ b/static/app/views/settings/project/server-side-sampling/samplingFromOtherProject.tsx
@@ -0,0 +1,74 @@
+import styled from '@emotion/styled';
+
+import Alert from 'sentry/components/alert';
+import Button from 'sentry/components/button';
+import ProjectBadge from 'sentry/components/idBadge/projectBadge';
+import {t, tn} from 'sentry/locale';
+import space from 'sentry/styles/space';
+import {Organization, Project} from 'sentry/types';
+import useProjects from 'sentry/utils/useProjects';
+
+import {useDistribution} from './utils/useDistribution';
+import {SERVER_SIDE_SAMPLING_DOC_LINK} from './utils';
+
+type Props = {
+ orgSlug: Organization['slug'];
+ projectSlug: Project['slug'];
+};
+
+export function SamplingFromOtherProject({orgSlug, projectSlug}: Props) {
+ const {distribution, loading} = useDistribution();
+
+ const {projects} = useProjects({
+ slugs: distribution?.parentProjectBreakdown?.map(({project}) => project) ?? [],
+ orgId: orgSlug,
+ });
+
+ const otherProjects = projects.filter(project => project.slug !== projectSlug);
+
+ if (loading || otherProjects.length === 0) {
+ return null;
+ }
+
+ return (
+ <Alert
+ type="info"
+ showIcon
+ trailingItems={
+ <Button
+ href={`${SERVER_SIDE_SAMPLING_DOC_LINK}#traces--propagation-of-sampling-decisions`}
+ priority="link"
+ borderless
+ external
+ >
+ {t('Learn More')}
+ </Button>
+ }
+ >
+ {tn(
+ 'The following project made sampling decisions for this project. You might want to set up rules there.',
+ 'The following projects made sampling decisions for this project. You might want to set up rules there.',
+ otherProjects.length
+ )}
+ <Projects>
+ {otherProjects.map(project => (
+ <ProjectBadge
+ key={project.slug}
+ project={project}
+ avatarSize={16}
+ to={`/settings/${orgSlug}/projects/${project.slug}/dynamic-sampling/`}
+ />
+ ))}
+ </Projects>
+ </Alert>
+ );
+}
+
+const Projects = styled('div')`
+ display: flex;
+ flex-wrap: wrap;
+ gap: ${space(1.5)};
+ justify-content: flex-start;
+ align-items: center;
+ margin-top: ${space(1)};
+`;
diff --git a/static/app/views/settings/project/server-side-sampling/serverSideSampling.tsx b/static/app/views/settings/project/server-side-sampling/serverSideSampling.tsx
index d85d00f4f81577..ba0e620d77904a 100644
--- a/static/app/views/settings/project/server-side-sampling/serverSideSampling.tsx
+++ b/static/app/views/settings/project/server-side-sampling/serverSideSampling.tsx
@@ -63,6 +63,7 @@ import {
} from './rule';
import {SamplingBreakdown} from './samplingBreakdown';
import {SamplingFeedback} from './samplingFeedback';
+import {SamplingFromOtherProject} from './samplingFromOtherProject';
import {SamplingProjectIncompatibleAlert} from './samplingProjectIncompatibleAlert';
import {SamplingPromo} from './samplingPromo';
import {SamplingSDKClientRateChangeAlert} from './samplingSDKClientRateChangeAlert';
@@ -541,6 +542,11 @@ export function ServerSideSampling({project}: Props) {
/>
)}
+ <SamplingFromOtherProject
+ orgSlug={organization.slug}
+ projectSlug={project.slug}
+ />
+
{hasAccess && <SamplingBreakdown orgSlug={organization.slug} />}
{!rules.length ? (
<SamplingPromo
diff --git a/static/app/views/settings/project/server-side-sampling/testUtils.tsx b/static/app/views/settings/project/server-side-sampling/testUtils.tsx
index eca32cf45f0cbe..15cf7d8e091f04 100644
--- a/static/app/views/settings/project/server-side-sampling/testUtils.tsx
+++ b/static/app/views/settings/project/server-side-sampling/testUtils.tsx
@@ -141,6 +141,13 @@ export const mockedSamplingDistribution: SamplingDistribution = {
'count()': 100,
},
],
+ parentProjectBreakdown: [
+ {
+ percentage: 10,
+ project: 'parent-project',
+ projectId: 10,
+ },
+ ],
sampleSize: 100,
startTimestamp: '2017-08-04T07:52:11Z',
endTimestamp: '2017-08-05T07:52:11Z',
|
6c70b74b77f4aa62fa948a6897d8e25929a302db
|
2023-12-27 22:49:33
|
George Gritsouk
|
ref(ts): Remove usage of `TestStubs.Dashboard` (#62328)
| false
|
Remove usage of `TestStubs.Dashboard` (#62328)
|
ref
|
diff --git a/fixtures/js-stubs/dashboard.tsx b/fixtures/js-stubs/dashboard.tsx
index f763dac2ccd1b9..60930baa013d4c 100644
--- a/fixtures/js-stubs/dashboard.tsx
+++ b/fixtures/js-stubs/dashboard.tsx
@@ -1,6 +1,7 @@
import type {
DashboardDetails as TDashboardDetails,
DashboardFilters as TDashboardFilters,
+ DashboardListItem as TDashboardListItem,
Widget as TWidget,
} from 'sentry/views/dashboards/types';
@@ -18,3 +19,15 @@ export function Dashboard(
...props,
};
}
+
+export function DashboardListItem(
+ params: Partial<TDashboardListItem> = {}
+): TDashboardListItem {
+ return {
+ id: '1',
+ title: 'Dashboard',
+ widgetDisplay: [],
+ widgetPreview: [],
+ ...params,
+ };
+}
diff --git a/static/app/views/dashboards/detail.spec.tsx b/static/app/views/dashboards/detail.spec.tsx
index 09a73ea434d325..141609b29d1cd3 100644
--- a/static/app/views/dashboards/detail.spec.tsx
+++ b/static/app/views/dashboards/detail.spec.tsx
@@ -1,4 +1,5 @@
import {browserHistory} from 'react-router';
+import {Dashboard as DashboardFixture} from 'sentry-fixture/dashboard';
import LocationFixture from 'sentry-fixture/locationFixture';
import {Organization} from 'sentry-fixture/organization';
import {Project as ProjectFixture} from 'sentry-fixture/project';
@@ -45,13 +46,13 @@ describe('Dashboards > Detail', function () {
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/',
body: [
- TestStubs.Dashboard([], {id: 'default-overview', title: 'Default'}),
- TestStubs.Dashboard([], {id: '1', title: 'Custom Errors'}),
+ DashboardFixture([], {id: 'default-overview', title: 'Default'}),
+ DashboardFixture([], {id: '1', title: 'Custom Errors'}),
],
});
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/default-overview/',
- body: TestStubs.Dashboard([], {id: 'default-overview', title: 'Default'}),
+ body: DashboardFixture([], {id: 'default-overview', title: 'Default'}),
});
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/1/visit/',
@@ -103,7 +104,7 @@ describe('Dashboards > Detail', function () {
});
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/default-overview/',
- body: TestStubs.Dashboard(
+ body: DashboardFixture(
[
TestStubs.Widget(
[
@@ -288,21 +289,25 @@ describe('Dashboards > Detail', function () {
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/',
body: [
- TestStubs.Dashboard([], {
- id: 'default-overview',
- title: 'Default',
+ {
+ ...DashboardFixture([], {
+ id: 'default-overview',
+ title: 'Default',
+ }),
widgetDisplay: ['area'],
- }),
- TestStubs.Dashboard([], {
- id: '1',
- title: 'Custom Errors',
+ },
+ {
+ ...DashboardFixture([], {
+ id: '1',
+ title: 'Custom Errors',
+ }),
widgetDisplay: ['area'],
- }),
+ },
],
});
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/1/',
- body: TestStubs.Dashboard(widgets, {
+ body: DashboardFixture(widgets, {
id: '1',
title: 'Custom Errors',
filters: {},
@@ -311,7 +316,7 @@ describe('Dashboards > Detail', function () {
mockPut = MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/1/',
method: 'PUT',
- body: TestStubs.Dashboard(widgets, {id: '1', title: 'Custom Errors'}),
+ body: DashboardFixture(widgets, {id: '1', title: 'Custom Errors'}),
});
MockApiClient.addMockResponse({
url: '/organizations/org-slug/events-stats/',
@@ -365,7 +370,7 @@ describe('Dashboards > Detail', function () {
const updateMock = MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/1/',
method: 'PUT',
- body: TestStubs.Dashboard([widgets[0]], {id: '1', title: 'Custom Errors'}),
+ body: DashboardFixture([widgets[0]], {id: '1', title: 'Custom Errors'}),
});
render(
<OrganizationContext.Provider value={initialData.organization}>
@@ -412,7 +417,7 @@ describe('Dashboards > Detail', function () {
it('appends dashboard-level filters to series request', async function () {
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/1/',
- body: TestStubs.Dashboard(widgets, {
+ body: DashboardFixture(widgets, {
id: '1',
title: 'Custom Errors',
filters: {release: ['[email protected]']},
@@ -535,7 +540,7 @@ describe('Dashboards > Detail', function () {
// A case where someone has async added widgets to a dashboard
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/1/',
- body: TestStubs.Dashboard(
+ body: DashboardFixture(
[
TestStubs.Widget(
[
@@ -595,7 +600,7 @@ describe('Dashboards > Detail', function () {
it('does not trigger request if layout not updated', async () => {
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/1/',
- body: TestStubs.Dashboard(
+ body: DashboardFixture(
[
TestStubs.Widget(
[
@@ -642,7 +647,7 @@ describe('Dashboards > Detail', function () {
it('renders the custom resize handler for a widget', async () => {
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/1/',
- body: TestStubs.Dashboard(
+ body: DashboardFixture(
[
TestStubs.Widget(
[
@@ -691,7 +696,7 @@ describe('Dashboards > Detail', function () {
it('does not trigger an alert when the widgets have no layout and user cancels without changes', async () => {
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/1/',
- body: TestStubs.Dashboard(
+ body: DashboardFixture(
[
TestStubs.Widget(
[
@@ -756,7 +761,7 @@ describe('Dashboards > Detail', function () {
);
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/1/',
- body: TestStubs.Dashboard([widget], {id: '1', title: 'Custom Errors'}),
+ body: DashboardFixture([widget], {id: '1', title: 'Custom Errors'}),
});
render(
@@ -787,7 +792,7 @@ describe('Dashboards > Detail', function () {
const openWidgetViewerModal = jest.spyOn(modals, 'openWidgetViewerModal');
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/1/',
- body: TestStubs.Dashboard([], {id: '1', title: 'Custom Errors'}),
+ body: DashboardFixture([], {id: '1', title: 'Custom Errors'}),
});
render(
<ViewEditDashboard
@@ -937,7 +942,7 @@ describe('Dashboards > Detail', function () {
const openWidgetViewerModal = jest.spyOn(modals, 'openWidgetViewerModal');
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/1/',
- body: TestStubs.Dashboard(widgets, {
+ body: DashboardFixture(widgets, {
id: '1',
filters: {release: ['[email protected]']},
}),
@@ -968,7 +973,7 @@ describe('Dashboards > Detail', function () {
const openWidgetViewerModal = jest.spyOn(modals, 'openWidgetViewerModal');
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/1/',
- body: TestStubs.Dashboard(widgets, {
+ body: DashboardFixture(widgets, {
id: '1',
filters: {release: ['[email protected]']},
}),
@@ -1057,7 +1062,7 @@ describe('Dashboards > Detail', function () {
it('can clear dashboard filters in compact select', async () => {
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/1/',
- body: TestStubs.Dashboard(widgets, {
+ body: DashboardFixture(widgets, {
id: '1',
title: 'Custom Errors',
filters: {release: ['[email protected]']},
@@ -1289,7 +1294,7 @@ describe('Dashboards > Detail', function () {
});
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/1/',
- body: TestStubs.Dashboard(widgets, {
+ body: DashboardFixture(widgets, {
id: '1',
title: 'Custom Errors',
filters: {},
@@ -1384,7 +1389,7 @@ describe('Dashboards > Detail', function () {
it('resets release in URL params', async function () {
MockApiClient.addMockResponse({
url: '/organizations/org-slug/dashboards/1/',
- body: TestStubs.Dashboard(widgets, {
+ body: DashboardFixture(widgets, {
id: '1',
title: 'Custom Errors',
filters: {
diff --git a/static/app/views/dashboards/manage/dashboardList.spec.tsx b/static/app/views/dashboards/manage/dashboardList.spec.tsx
index 9759a53e55c7a0..5d03da32de0264 100644
--- a/static/app/views/dashboards/manage/dashboardList.spec.tsx
+++ b/static/app/views/dashboards/manage/dashboardList.spec.tsx
@@ -1,6 +1,8 @@
+import {DashboardListItem as DashboardListItemFixture} from 'sentry-fixture/dashboard';
import LocationFixture from 'sentry-fixture/locationFixture';
import {Organization} from 'sentry-fixture/organization';
import {Project as ProjectFixture} from 'sentry-fixture/project';
+import {User as UserFixture} from 'sentry-fixture/user';
import {initializeOrg} from 'sentry-test/initializeOrg';
import {
@@ -13,9 +15,10 @@ import {
} from 'sentry-test/reactTestingLibrary';
import DashboardList from 'sentry/views/dashboards/manage/dashboardList';
+import {DisplayType} from 'sentry/views/dashboards/types';
describe('Dashboards - DashboardList', function () {
- let dashboards, widgets, deleteMock, dashboardUpdateMock, createMock;
+ let dashboards, deleteMock, dashboardUpdateMock, createMock;
const organization = Organization({
features: ['global-views', 'dashboards-basic', 'dashboards-edit', 'discover-query'],
projects: [ProjectFixture()],
@@ -30,59 +33,26 @@ describe('Dashboards - DashboardList', function () {
url: '/organizations/org-slug/projects/',
body: [],
});
- widgets = [
- TestStubs.Widget(
- [{name: '', conditions: 'event.type:error', fields: ['count()']}],
- {
- title: 'Errors',
- interval: '1d',
- id: '1',
- }
- ),
- TestStubs.Widget(
- [{name: '', conditions: 'event.type:transaction', fields: ['count()']}],
- {
- title: 'Transactions',
- interval: '1d',
- id: '2',
- }
- ),
- TestStubs.Widget(
- [
- {
- name: '',
- conditions: 'event.type:transaction transaction:/api/cats',
- fields: ['p50()'],
- },
- ],
- {
- title: 'p50 of /api/cats',
- interval: '1d',
- id: '3',
- }
- ),
- ];
dashboards = [
- TestStubs.Dashboard([], {
+ DashboardListItemFixture({
id: '1',
title: 'Dashboard 1',
dateCreated: '2021-04-19T13:13:23.962105Z',
- createdBy: {id: '1'},
- widgetPreview: [],
+ createdBy: UserFixture({id: '1'}),
}),
- TestStubs.Dashboard(widgets, {
+ DashboardListItemFixture({
id: '2',
title: 'Dashboard 2',
dateCreated: '2021-04-19T13:13:23.962105Z',
- createdBy: {id: '1'},
+ createdBy: UserFixture({id: '1'}),
widgetPreview: [
{
- displayType: 'line',
- layout: {},
+ displayType: DisplayType.LINE,
+ layout: null,
},
{
- displayType: 'table',
- layout: {},
+ displayType: DisplayType.TABLE,
+ layout: null,
},
],
}),
@@ -228,11 +198,11 @@ describe('Dashboards - DashboardList', function () {
it('cannot delete last dashboard', async function () {
const singleDashboard = [
- TestStubs.Dashboard([], {
+ DashboardListItemFixture({
id: '1',
title: 'Dashboard 1',
dateCreated: '2021-04-19T13:13:23.962105Z',
- createdBy: {id: '1'},
+ createdBy: UserFixture({id: '1'}),
widgetPreview: [],
}),
];
|
0da500833dee34f8bd17a476ddf084137923fdda
|
2022-10-28 03:13:47
|
Ryan Albrecht
|
feat(replays): Allow organization-tagkey-values endpoint to lookup from Replay dataset (#40678)
| false
|
Allow organization-tagkey-values endpoint to lookup from Replay dataset (#40678)
|
feat
|
diff --git a/src/sentry/api/endpoints/organization_tagkey_values.py b/src/sentry/api/endpoints/organization_tagkey_values.py
index da2d703bb7d7e5..90acb8bd8d1f11 100644
--- a/src/sentry/api/endpoints/organization_tagkey_values.py
+++ b/src/sentry/api/endpoints/organization_tagkey_values.py
@@ -45,6 +45,7 @@ def get(self, request: Request, organization, key) -> Response:
order_by=validate_sort_field(request.GET.get("sort", "-last_seen")),
include_transactions=request.GET.get("includeTransactions") == "1",
include_sessions=request.GET.get("includeSessions") == "1",
+ include_replays=request.GET.get("includeReplays") == "1",
)
return self.paginate(
diff --git a/src/sentry/tagstore/snuba/backend.py b/src/sentry/tagstore/snuba/backend.py
index fb61846a3f87c2..1deca6dcdb68a8 100644
--- a/src/sentry/tagstore/snuba/backend.py
+++ b/src/sentry/tagstore/snuba/backend.py
@@ -985,6 +985,7 @@ def get_tag_value_paginator_for_projects(
order_by="-last_seen",
include_transactions=False,
include_sessions=False,
+ include_replays=False,
):
from sentry.api.paginator import SequencePaginator
@@ -999,6 +1000,8 @@ def get_tag_value_paginator_for_projects(
dataset = Dataset.Events
if include_transactions:
dataset = Dataset.Discover
+ if include_replays:
+ dataset = Dataset.Replays
snuba_key = snuba.get_snuba_column_name(key, dataset=dataset)
|
23e09e524d9b530b5f809934e1fd633daa63ffc5
|
2023-06-06 00:40:45
|
Sebastian Zivota
|
feat(backpressure): Proof of concept for queue monitoring service (#50315)
| false
|
Proof of concept for queue monitoring service (#50315)
|
feat
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index 123a0a70826f7e..bf25c1a5c6307d 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -3427,3 +3427,7 @@ def build_cdc_postgres_init_db_volume(settings):
SENTRY_METRICS_INDEXER_RAISE_VALIDATION_ERRORS = False
SENTRY_FILE_COPY_ROLLOUT_RATE = 0.01
+
+# The Redis cluster to use for monitoring the health of
+# Celery queues.
+SENTRY_QUEUE_MONITORING_REDIS_CLUSTER = "default"
diff --git a/src/sentry/monitoring/queues.py b/src/sentry/monitoring/queues.py
index 1190b389762095..8e94533743fc45 100644
--- a/src/sentry/monitoring/queues.py
+++ b/src/sentry/monitoring/queues.py
@@ -1,8 +1,19 @@
+from threading import Thread
+from time import sleep
+from typing import List, Tuple
from urllib.parse import urlparse
+import sentry_sdk
from django.conf import settings
from django.utils.functional import cached_property
+from sentry import options
+from sentry.utils import redis
+
+QUEUES = ["profiles.process"]
+
+KEY_NAME = "unhealthy-queues"
+
class RedisBackend:
def __init__(self, broker_url):
@@ -38,7 +49,7 @@ def __init__(self, broker_url):
host="%s:%d" % (host, port),
userid=dsn.username,
password=dsn.password,
- virtual_host=dsn.path[1:],
+ virtual_host=dsn.path[1:] or "/",
)
def get_conn(self):
@@ -94,3 +105,88 @@ def get_queue_by_name(name):
backend = get_backend_for_broker(settings.BROKER_URL)
except KeyError:
backend = None
+
+
+queue_monitoring_cluster = redis.redis_clusters.get(settings.SENTRY_QUEUE_MONITORING_REDIS_CLUSTER)
+
+
+def _unhealthy_queue_key(queue_name: str) -> str:
+ return f"{KEY_NAME}:{queue_name}"
+
+
+def is_queue_healthy(queue_name: str) -> bool:
+ """Checks whether the given queue is healthy by looking it up in Redis.
+
+ NB: If the queue is not found in Redis, it is assumed to be healthy.
+ This behavior might change in the future.
+ """
+
+ if not options.get("backpressure.monitor_queues.enable"):
+ return True
+ # check if queue is healthy by pinging Redis
+ try:
+ healthy = queue_monitoring_cluster.exists(_unhealthy_queue_key(queue_name))
+ except Exception:
+ healthy = False
+ return healthy
+
+
+def _is_healthy(queue_size) -> bool:
+ return queue_size < options.get("backpressure.monitor_queues.unhealthy_threshold")
+
+
+def _update_queue_stats(redis_cluster, queue_health: List[Tuple[str, bool]]) -> None:
+ unhealthy = [queue for (queue, unhealthy) in queue_health if unhealthy]
+ if unhealthy:
+ # Report list of unhealthy queues to sentry
+ with sentry_sdk.push_scope() as scope:
+ scope.set_extra("unhealthy_queues", unhealthy)
+ sentry_sdk.capture_message("RabbitMQ queues are exceeding size threshold")
+
+ with redis_cluster.pipeline(transaction=True) as pipeline:
+ for (queue, unhealthy) in queue_health:
+ if unhealthy:
+ pipeline.set(_unhealthy_queue_key(queue), "1", ex=60)
+ else:
+ pipeline.delete(_unhealthy_queue_key(queue))
+ pipeline.execute()
+
+
+def _run_queue_stats_updater(redis_cluster: str) -> None:
+ # bonus point if we manage to use asyncio and launch all tasks at once
+ # in case we have many queues to check
+ cluster = redis.redis_clusters.get(redis_cluster)
+
+ queue_history = {queue: 0 for queue in QUEUES}
+ while True:
+ if not options.get("backpressure.monitor_queues.enable"):
+ sleep(10)
+ continue
+
+ try:
+ new_sizes = backend.bulk_get_sizes(QUEUES)
+ for (queue, size) in new_sizes:
+ if _is_healthy(size):
+ queue_history[queue] = 0
+ else:
+ queue_history[queue] += 1
+ except Exception:
+ # If there was an error getting queue sizes from RabbitMQ, assume
+ # all queues are unhealthy
+ for queue in QUEUES:
+ queue_history[queue] += 1
+
+ strike_threshold = options.get("backpressure.monitor_queues.strike_threshold")
+ queue_health = [(queue, count >= strike_threshold) for (queue, count) in queue_history]
+ _update_queue_stats(cluster, queue_health)
+ sleep(options.get("backpressure.monitor_queues.check_interval"))
+
+
+def monitor_queues():
+ if backend is None:
+ return
+ queue_stats_updater_process = Thread(
+ target=_run_queue_stats_updater,
+ args=(settings.SENTRY_QUEUE_MONITORING_REDIS_CLUSTER,),
+ )
+ queue_stats_updater_process.start()
diff --git a/src/sentry/options/defaults.py b/src/sentry/options/defaults.py
index 075c94995c1458..1596d32b401297 100644
--- a/src/sentry/options/defaults.py
+++ b/src/sentry/options/defaults.py
@@ -718,3 +718,11 @@
register("span_descs.bump-lifetime-sample-rate", default=0.25)
# Decides whether artifact bundles asynchronous renewal is enabled.
register("sourcemaps.artifact-bundles.enable-renewal", default=0.0)
+# Enables queue monitoring for backpressure management.
+register("backpressure.monitor_queues.enable", default=False)
+register("backpressure.monitor_queues.unhealthy_threshold", default=1000)
+# How often we check queue health.
+register("backpressure.monitor_queues.check_interval", default=5)
+# How many times in a row a queue must be unhealthy before it is
+# recorded in Redis. 12 * 5sec = unhealthy for 1 minute.
+register("backpressure.monitor_queues.strike_threshold", default=12)
diff --git a/src/sentry/profiles/consumers/process/factory.py b/src/sentry/profiles/consumers/process/factory.py
index 881716bd402f24..88117c98a5145e 100644
--- a/src/sentry/profiles/consumers/process/factory.py
+++ b/src/sentry/profiles/consumers/process/factory.py
@@ -1,19 +1,30 @@
from typing import Mapping
from arroyo.backends.kafka.consumer import KafkaPayload
-from arroyo.processing.strategies.abstract import ProcessingStrategy, ProcessingStrategyFactory
+from arroyo.processing.strategies.abstract import (
+ MessageRejected,
+ ProcessingStrategy,
+ ProcessingStrategyFactory,
+)
from arroyo.processing.strategies.commit import CommitOffsets
from arroyo.processing.strategies.run_task import RunTask
from arroyo.types import Commit, Message, Partition
+from sentry.monitoring.queues import is_queue_healthy, monitor_queues
from sentry.profiles.task import process_profile_task
def process_message(message: Message[KafkaPayload]) -> None:
+ if not is_queue_healthy("profiles.process"):
+ raise MessageRejected()
process_profile_task.s(payload=message.payload.value).apply_async()
class ProcessProfileStrategyFactory(ProcessingStrategyFactory[KafkaPayload]):
+ def __init__(self) -> None:
+ super().__init__()
+ monitor_queues()
+
def create_with_partitions(
self,
commit: Commit,
|
e2e6411ab90750ab9d1eb47572fabf2ac71e009e
|
2023-06-14 22:08:43
|
Stephen Cefali
|
fix(slack): don't use parsed version for linking to release (#50951)
| false
|
don't use parsed version for linking to release (#50951)
|
fix
|
diff --git a/src/sentry/notifications/notifications/activity/regression.py b/src/sentry/notifications/notifications/activity/regression.py
index f630e28efe9cb0..7a02c7c3c6c27a 100644
--- a/src/sentry/notifications/notifications/activity/regression.py
+++ b/src/sentry/notifications/notifications/activity/regression.py
@@ -40,7 +40,7 @@ def get_notification_title(
text = "Issue marked as regression"
if self.version:
version_url = self.organization.absolute_url(
- f"/organizations/{self.organization.slug}/releases/{self.version_parsed}/"
+ f"/organizations/{self.organization.slug}/releases/{self.version}/"
)
text += f" in release {self.format_url(text=self.version_parsed, url=version_url, provider=provider)}"
return text
|
cb9f9c548722eca6c8388051d1eb8d2fa8f2b975
|
2023-03-15 23:29:39
|
David Wang
|
ref(crons): Monitor form visual tweaks (#45738)
| false
|
Monitor form visual tweaks (#45738)
|
ref
|
diff --git a/static/app/views/monitors/components/monitorForm.tsx b/static/app/views/monitors/components/monitorForm.tsx
index 97ea55d2fdc01f..03ffc4baf4b4de 100644
--- a/static/app/views/monitors/components/monitorForm.tsx
+++ b/static/app/views/monitors/components/monitorForm.tsx
@@ -36,8 +36,8 @@ import {
} from '../types';
const SCHEDULE_OPTIONS: RadioOption<string>[] = [
- [ScheduleType.INTERVAL, t('Interval')],
[ScheduleType.CRONTAB, t('Crontab')],
+ [ScheduleType.INTERVAL, t('Interval')],
];
const DEFAULT_MONITOR_TYPE = 'cron_job';
@@ -181,6 +181,7 @@ function MonitorForm({
<StyledSentryProjectSelectorField
name="project"
projects={projects.filter(project => project.isMember)}
+ placeholder={t('Choose Project')}
disabled={!!monitor}
disabledReason={t('Existing monitors cannot be moved between projects')}
valueIsSlug
@@ -197,7 +198,7 @@ function MonitorForm({
<StyledListItem>{t('Choose your schedule type')}</StyledListItem>
<ListItemSubText>
- {tct('You can use our simple schedule or [link:the crontab syntax].', {
+ {tct('You can use [link:the crontab syntax] or our interval schedule.', {
link: <ExternalLink href="https://en.wikipedia.org/wiki/Cron" />,
})}
</ListItemSubText>
@@ -274,6 +275,7 @@ function MonitorForm({
options={getIntervals(
Number(form.current.getValue('config.schedule.frequency') ?? 1)
)}
+ placeholder="minute"
required
stacked
inline={false}
@@ -287,35 +289,29 @@ function MonitorForm({
</InputGroup>
<StyledListItem>{t('Set a missed status')}</StyledListItem>
<ListItemSubText>
- {t('How long to wait before we consider a check-in as missed.')}
+ {t("The number of minutes we'll wait before we consider a check-in as missed.")}
</ListItemSubText>
<InputGroup>
- <LabeledInputs>
- <StyledNumberField
- name="config.checkin_margin"
- placeholder="e.g. 30"
- stacked
- inline={false}
- />
- <LabelText>{t('Minutes')}</LabelText>
- </LabeledInputs>
+ <StyledNumberField
+ name="config.checkin_margin"
+ placeholder="e.g. 30"
+ stacked
+ inline={false}
+ />
</InputGroup>
<StyledListItem>{t('Set a failed status')}</StyledListItem>
<ListItemSubText>
{t(
- "How long a check-in is allowed to run before it's considered failed. If the job encounters an error it will also fail."
+ "The number of minutes a check-in is allowed to run before it's considered failed."
)}
</ListItemSubText>
<InputGroup>
- <LabeledInputs>
- <StyledNumberField
- name="config.max_runtime"
- placeholder="e.g. 30"
- stacked
- inline={false}
- />
- <LabelText>{t('Minutes')}</LabelText>
- </LabeledInputs>
+ <StyledNumberField
+ name="config.max_runtime"
+ placeholder="e.g. 30"
+ stacked
+ inline={false}
+ />
</InputGroup>
</StyledList>
</Form>
@@ -325,7 +321,7 @@ function MonitorForm({
export default MonitorForm;
const StyledList = styled(List)`
- width: 500px;
+ width: 600px;
`;
const StyledTextCopyInput = styled(TextCopyInput)`
@@ -377,14 +373,10 @@ const InputGroup = styled('div')`
gap: ${space(1)};
`;
-const LabeledInputs = styled('div')`
+const ScheduleGroupInputs = styled('div')<{interval?: boolean}>`
display: grid;
- grid-template-columns: 1fr auto;
align-items: center;
gap: ${space(1)};
-`;
-
-const ScheduleGroupInputs = styled(LabeledInputs)<{interval?: boolean}>`
grid-template-columns: ${p => p.interval && 'auto'} 1fr 2fr;
`;
diff --git a/static/app/views/monitors/monitors.tsx b/static/app/views/monitors/monitors.tsx
index 3a8976494fce8a..3dcdb006b3377d 100644
--- a/static/app/views/monitors/monitors.tsx
+++ b/static/app/views/monitors/monitors.tsx
@@ -119,8 +119,8 @@ class Monitors extends AsyncView<Props, State> {
<Layout.HeaderActions>
<ButtonBar gap={1}>
<CronsFeedbackButton />
- <NewMonitorButton size="sm" icon={<IconAdd isCircled size="xs" />}>
- {t('Add monitor')}
+ <NewMonitorButton size="sm" icon={<IconAdd size="xs" />}>
+ {t('Add Monitor')}
</NewMonitorButton>
</ButtonBar>
</Layout.HeaderActions>
|
cc1724100a7dac16faad6286dfa38b516caefb3c
|
2023-04-26 01:34:35
|
Dominik Buszowiecki
|
feat(starfish): add additional columns to query details (#47898)
| false
|
add additional columns to query details (#47898)
|
feat
|
diff --git a/static/app/views/starfish/modules/databaseModule/panel.tsx b/static/app/views/starfish/modules/databaseModule/panel.tsx
index 68567bd2046857..c69e7bf6a58824 100644
--- a/static/app/views/starfish/modules/databaseModule/panel.tsx
+++ b/static/app/views/starfish/modules/databaseModule/panel.tsx
@@ -1,6 +1,9 @@
import {useTheme} from '@emotion/react';
import styled from '@emotion/styled';
import {useQuery} from '@tanstack/react-query';
+import keyBy from 'lodash/keyBy';
+import merge from 'lodash/merge';
+import values from 'lodash/values';
import GridEditable, {GridColumnHeader} from 'sentry/components/gridEditable';
import Link from 'sentry/components/links/link';
@@ -24,6 +27,7 @@ type TransactionListDataRow = {
group_id: string;
p75: number;
transaction: string;
+ uniqueEvents: number;
};
const COLUMN_ORDER = [
@@ -32,13 +36,21 @@ const COLUMN_ORDER = [
name: 'Transaction',
width: 400,
},
+ {
+ key: 'p75',
+ name: 'p75',
+ },
{
key: 'count',
name: 'Count',
},
{
- key: 'p75',
- name: 'p75',
+ key: 'frequency',
+ name: 'Frequency',
+ },
+ {
+ key: 'uniqueEvents',
+ name: 'Total Events',
},
];
@@ -78,6 +90,21 @@ function QueryDetailBody({row}: EndpointDetailBodyProps) {
ORDER BY interval asc
`;
+ const EVENT_COUNT_QUERY = `
+ SELECT transaction, count(DISTINCT transaction_id) as uniqueEvents
+ FROM spans_experimental_starfish
+ WHERE transaction
+ IN (SELECT transaction FROM spans_experimental_starfish WHERE module='db' AND description='${row.description}')
+ GROUP BY transaction
+ `;
+
+ // const INCLUDED_EVENT_COUNT_QUERY = `
+ // SELECT transaction, count(DISTINCT transaction_id) as included_event_count
+ // FROM spans_experimental_starfish
+ // WHERE module='db' AND description='${row.description}'
+ // GROUP BY transaction
+ // `;
+
const {isLoading, data: graphData} = useQuery({
queryKey: ['dbQueryDetailsGraph', row.group_id],
queryFn: () =>
@@ -93,7 +120,18 @@ function QueryDetailBody({row}: EndpointDetailBodyProps) {
initialData: [],
});
- // console.log(row.desc);
+ const {isLoading: isEventCountLoading, data: eventCountData} = useQuery({
+ queryKey: ['dbQueryDetailsEventCount', row.description],
+ queryFn: () => fetch(`${HOST}/?query=${EVENT_COUNT_QUERY}`).then(res => res.json()),
+ retry: true,
+ initialData: [],
+ });
+
+ const isDataLoading = isLoading || isTableLoading || isEventCountLoading;
+
+ const mergedTableData = values(
+ merge(keyBy(eventCountData, 'transaction'), keyBy(tableData, 'transaction'))
+ ).filter((data: Partial<TransactionListDataRow>) => !!data.count && !!data.p75);
const [countSeries, p75Series] = throughputQueryToChartData(graphData);
@@ -105,7 +143,12 @@ function QueryDetailBody({row}: EndpointDetailBodyProps) {
column: GridColumnHeader,
dataRow: TransactionListDataRow
): React.ReactNode => {
- if (column.key === 'transaction') {
+ if (column.key === 'frequency') {
+ return <span>{(dataRow.count / dataRow.uniqueEvents).toFixed(2)}</span>;
+ }
+ const {key} = column;
+ const value = dataRow[key];
+ if (key === 'transaction') {
return (
<Link
to={`/starfish/span/${encodeURIComponent(row.group_id)}:${encodeURIComponent(
@@ -116,10 +159,10 @@ function QueryDetailBody({row}: EndpointDetailBodyProps) {
</Link>
);
}
- if (column.key === 'p75') {
- return <span>{dataRow[column.key].toFixed(2)}ms</span>;
+ if (key === 'p75') {
+ return <span>{value?.toFixed(2)}ms</span>;
}
- return <span>{dataRow[column.key]}</span>;
+ return <span>{value}</span>;
};
return (
@@ -142,7 +185,7 @@ function QueryDetailBody({row}: EndpointDetailBodyProps) {
data={[countSeries]}
start=""
end=""
- loading={isLoading}
+ loading={isDataLoading}
utc={false}
disableMultiAxis
stacked
@@ -160,7 +203,7 @@ function QueryDetailBody({row}: EndpointDetailBodyProps) {
data={[p75Series]}
start=""
end=""
- loading={isLoading}
+ loading={isDataLoading}
utc={false}
chartColors={[theme.charts.getColorPalette(4)[3]]}
disableMultiAxis
@@ -172,8 +215,8 @@ function QueryDetailBody({row}: EndpointDetailBodyProps) {
</FlexRowItem>
</FlexRowContainer>
<GridEditable
- isLoading={isTableLoading}
- data={tableData}
+ isLoading={isDataLoading}
+ data={mergedTableData}
columnOrder={COLUMN_ORDER}
columnSortBy={[]}
grid={{
|
d2dbab043eef3012e9c54e8dcab3196822ce9f20
|
2021-06-24 05:36:20
|
Colleen O'Rourke
|
feat(notification platform): Add slash command for team linking (#26750)
| false
|
Add slash command for team linking (#26750)
|
feat
|
diff --git a/src/sentry/integrations/slack/command_endpoint.py b/src/sentry/integrations/slack/command_endpoint.py
index 80f97db5a17688..82792e6cbc9cb9 100644
--- a/src/sentry/integrations/slack/command_endpoint.py
+++ b/src/sentry/integrations/slack/command_endpoint.py
@@ -1,25 +1,42 @@
import logging
-from typing import Mapping
+from typing import Mapping, Sequence, Tuple
-from django.http import HttpResponse
+from django.http import Http404, HttpResponse
from rest_framework.request import Request
from sentry.api.base import Endpoint
+from sentry.integrations.slack.link_team import build_linking_url
from sentry.integrations.slack.message_builder.help import SlackHelpMessageBuilder
from sentry.integrations.slack.requests.base import SlackRequestError
from sentry.integrations.slack.requests.command import SlackCommandRequest
+from sentry.models import Identity, IdentityProvider
logger = logging.getLogger("sentry.integrations.slack")
+LINK_TEAM_MESSAGE = "Link your Sentry team to this Slack channel! <{associate_url}|Link your team now> to receive notifications of issues in Sentry in Slack."
+LINK_USER_MESSAGE = "You must first link your identity to Sentry by typing /sentry link. Be aware that you must be an admin or higher in your Sentry organization to link your team."
-def get_command(payload: Mapping[str, str]) -> str:
- return payload.get("text", "").split(" ")[0].lower()
+def get_command_and_args(payload: Mapping[str, str]) -> Tuple[str, Sequence[str]]:
+ text = payload.get("text", "").lower().split()
+ if not text:
+ return "", []
+
+ return text[0], text[1:]
class SlackCommandsEndpoint(Endpoint):
authentication_classes = ()
permission_classes = ()
+ def send_ephemeral_notification(self, message):
+ return self.respond(
+ {
+ "response_type": "ephemeral",
+ "replace_original": False,
+ "text": message,
+ }
+ )
+
def post(self, request: Request) -> HttpResponse:
"""
All Slack commands are handled by this endpoint. This block just
@@ -32,12 +49,36 @@ def post(self, request: Request) -> HttpResponse:
return self.respond(status=e.status)
payload = slack_request.data
- command = get_command(payload)
-
+ command, args = get_command_and_args(payload)
+ # TODO(mgaeta): Add more commands.
if command in ["help", ""]:
return self.respond(SlackHelpMessageBuilder().build())
+ if command == "link":
+ if args and args[0] == "team":
+ integration = slack_request.integration
+ user_id = payload.get("user_id")
+ try:
+ idp = IdentityProvider.objects.get(
+ type="slack", external_id=slack_request.team_id
+ )
+ except IdentityProvider.DoesNotExist:
+ logger.error(
+ "slack.action.invalid-team-id", extra={"slack_team": slack_request.team_id}
+ )
+ raise Http404
- # TODO(mgaeta): Add more commands.
+ if not Identity.objects.filter(idp=idp, external_id=user_id).exists():
+ return self.send_ephemeral_notification(LINK_USER_MESSAGE)
+ channel_id = payload.get("channel_id", "")
+ channel_name = payload.get("channel_name", "")
+ user_id = payload.get("user_id", "")
+ response_url = payload.get("response_url")
+ associate_url = build_linking_url(
+ integration, user_id, channel_id, channel_name, response_url
+ )
+ return self.send_ephemeral_notification(
+ LINK_TEAM_MESSAGE.format(associate_url=associate_url)
+ )
# If we cannot interpret the command, print help text.
return self.respond(SlackHelpMessageBuilder(command).build())
diff --git a/src/sentry/integrations/slack/link_team.py b/src/sentry/integrations/slack/link_team.py
new file mode 100644
index 00000000000000..0044c8a4b303c9
--- /dev/null
+++ b/src/sentry/integrations/slack/link_team.py
@@ -0,0 +1,208 @@
+from django import forms
+from django.urls import reverse
+from django.views.decorators.cache import never_cache
+
+from sentry.models import (
+ ExternalActor,
+ Identity,
+ IdentityProvider,
+ Integration,
+ NotificationSetting,
+ OrganizationMember,
+ Team,
+)
+from sentry.notifications.types import NotificationSettingOptionValues, NotificationSettingTypes
+from sentry.shared_integrations.exceptions import ApiError
+from sentry.types.integrations import ExternalProviders
+from sentry.utils.http import absolute_uri
+from sentry.utils.signing import sign, unsign
+from sentry.web.decorators import transaction_start
+from sentry.web.frontend.base import BaseView
+from sentry.web.helpers import render_to_response
+
+from .client import SlackClient
+from .utils import logger
+
+
+def build_linking_url(integration, slack_id, channel_id, channel_name, response_url):
+ signed_params = sign(
+ integration_id=integration.id,
+ slack_id=slack_id,
+ channel_id=channel_id,
+ channel_name=channel_name,
+ response_url=response_url,
+ )
+
+ return absolute_uri(
+ reverse("sentry-integration-slack-link-team", kwargs={"signed_params": signed_params})
+ )
+
+
+class SelectTeamForm(forms.Form):
+ team = forms.ChoiceField(label="Team")
+
+ def __init__(self, teams, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ self.fields["team"].choices = [(team.id, team.slug) for team in teams]
+ self.fields["team"].widget.choices = self.fields["team"].choices
+
+
+class SlackLinkTeamView(BaseView):
+ def get_identity(self, request, integration, slack_id):
+ try:
+ idp = IdentityProvider.objects.get(type="slack", external_id=integration.external_id)
+ except IdentityProvider.DoesNotExist:
+ logger.error(
+ "slack.action.invalid-team-id", extra={"slack_id": integration.external_id}
+ )
+ return self.render_error_page(request, body_text="HTTP 403: Invalid team ID")
+
+ try:
+ identity = Identity.objects.select_related("user").get(idp=idp, external_id=slack_id)
+ except Identity.DoesNotExist:
+ logger.error(
+ "slack.action.missing-identity", extra={"slack_id": integration.external_id}
+ )
+ return self.render_error_page(
+ request, body_text="HTTP 403: User identity does not exist"
+ )
+ return identity
+
+ def render_error_page(self, request, body_text):
+ return render_to_response(
+ "sentry/slack-link-team-error.html",
+ request=request,
+ context={"body_text": body_text},
+ )
+
+ def send_slack_message(self, request, client, token, text, channel_id, integration):
+ payload = {
+ "token": token,
+ "channel": channel_id,
+ "text": text["body"],
+ }
+ headers = {"Authorization": "Bearer %s" % token}
+ try:
+ client.post("/chat.postMessage", headers=headers, data=payload, json=True)
+ except ApiError as e:
+ message = str(e)
+ if message != "Expired url":
+ logger.error("slack.link-notify.response-error", extra={"error": message})
+ else:
+ return render_to_response(
+ "sentry/slack-post-linked-team.html",
+ request=request,
+ context={
+ "heading_text": text["heading"],
+ "body_text": text["body"],
+ "channel_id": channel_id,
+ "team_id": integration.external_id,
+ },
+ )
+
+ @transaction_start("SlackLinkTeamView")
+ @never_cache
+ def handle(self, request, signed_params):
+ params = unsign(signed_params)
+ integration = Integration.objects.get(id=params["integration_id"])
+ organization = integration.organizations.all()[0]
+ teams = Team.objects.get_for_user(organization, request.user)
+ channel_name = params["channel_name"]
+ channel_id = params["channel_id"]
+ form = SelectTeamForm(teams, request.POST or None)
+ if request.method not in ["POST", "GET"]:
+ return self.render_error_page(request, body_text="HTTP 405: Method not allowed")
+
+ if request.method == "POST":
+ if not form.is_valid():
+ return self.render_error_page(request, body_text="HTTP 400: Bad request")
+ team_id = form.cleaned_data["team"]
+
+ if request.method == "GET":
+ return self.respond(
+ "sentry/slack-link-team.html",
+ {
+ "form": form,
+ "teams": teams,
+ "channel_name": channel_name,
+ "provider": integration.get_provider(),
+ },
+ )
+
+ team = Team.objects.get(id=team_id, organization=organization)
+ if not team:
+ return self.render_error_page(body_text="HTTP 404: Team does not exist")
+
+ INSUFFICIENT_ROLE_MESSAGE = {
+ "heading": "Insufficient role",
+ "body": "You must be an admin or higher to link teams.",
+ }
+ ALREADY_LINKED_MESSAGE = {
+ "heading": "Already linked",
+ "body": f"The {team.slug} team has already been linked to a Slack channel.",
+ }
+ SUCCESS_LINKED_MESSAGE = {
+ "heading": "Team linked",
+ "body": f"The {team.slug} team will now receive issue alert notifications in the {channel_name} channel.",
+ }
+ identity = self.get_identity(request, integration, params["slack_id"])
+ org_member = OrganizationMember.objects.get(user=identity.user, organization=organization)
+ client = SlackClient()
+ token = (
+ integration.metadata.get("user_access_token") or integration.metadata["access_token"]
+ )
+ allowed_roles = ["admin", "manager", "owner"]
+ if not (
+ org_member.role in allowed_roles
+ and (organization.flags.allow_joinleave or team in [org_member.teams])
+ ):
+ return self.send_slack_message(
+ request,
+ client,
+ token,
+ INSUFFICIENT_ROLE_MESSAGE,
+ channel_id,
+ integration,
+ )
+
+ if ExternalActor.objects.filter(
+ actor_id=team.actor_id,
+ organization=organization,
+ integration=integration,
+ provider=ExternalProviders.SLACK.value,
+ ).exists():
+ return self.send_slack_message(
+ request,
+ client,
+ token,
+ ALREADY_LINKED_MESSAGE,
+ channel_id,
+ integration,
+ )
+
+ external_team, created = ExternalActor.objects.get_or_create(
+ actor_id=team.actor_id,
+ organization=organization,
+ integration=integration,
+ provider=ExternalProviders.SLACK.value,
+ external_name=channel_name,
+ external_id=channel_id,
+ )
+
+ if created:
+ # turn on notifications for all of a team's projects
+ NotificationSetting.objects.update_settings(
+ ExternalProviders.SLACK,
+ NotificationSettingTypes.ISSUE_ALERTS,
+ NotificationSettingOptionValues.ALWAYS,
+ team=team,
+ )
+ return self.send_slack_message(
+ request,
+ client,
+ token,
+ SUCCESS_LINKED_MESSAGE,
+ channel_id,
+ integration,
+ )
diff --git a/src/sentry/integrations/slack/urls.py b/src/sentry/integrations/slack/urls.py
index 65986d02947a08..a35c053f16a3a9 100644
--- a/src/sentry/integrations/slack/urls.py
+++ b/src/sentry/integrations/slack/urls.py
@@ -4,6 +4,7 @@
from .command_endpoint import SlackCommandsEndpoint
from .event_endpoint import SlackEventEndpoint
from .link_identity import SlackLinkIdentityView
+from .link_team import SlackLinkTeamView
from .unlink_identity import SlackUnlinkIdentityView
urlpatterns = [
@@ -20,4 +21,9 @@
SlackUnlinkIdentityView.as_view(),
name="sentry-integration-slack-unlink-identity",
),
+ url(
+ r"^link-team/(?P<signed_params>[^\/]+)/$",
+ SlackLinkTeamView.as_view(),
+ name="sentry-integration-slack-link-team",
+ ),
]
diff --git a/src/sentry/templates/sentry/slack-link-team-error.html b/src/sentry/templates/sentry/slack-link-team-error.html
new file mode 100644
index 00000000000000..c861a930da9947
--- /dev/null
+++ b/src/sentry/templates/sentry/slack-link-team-error.html
@@ -0,0 +1,14 @@
+{% extends "sentry/bases/modal.html" %}
+
+{% load i18n %}
+
+{% block title %}{% trans "Error" %} | {{ block.super }}{% endblock %}
+{% block wrapperclass %}narrow auth{% endblock %}
+
+{% block main %}
+ <div class="align-center">
+ <p>
+ {% trans body_text %}
+ </p>
+ </div>
+{% endblock %}
diff --git a/src/sentry/templates/sentry/slack-link-team.html b/src/sentry/templates/sentry/slack-link-team.html
new file mode 100644
index 00000000000000..ce3fab39d006b7
--- /dev/null
+++ b/src/sentry/templates/sentry/slack-link-team.html
@@ -0,0 +1,35 @@
+{% extends "sentry/bases/auth.html" %}
+
+{% load crispy_forms_tags %}
+{% load i18n %}
+{% load sentry_assets %}
+
+{% block title %}{% trans "Link Team" %} | {{ block.super }}{% endblock %}
+
+{% block auth_main %}
+<form class="form-stacked" action="" method="post">
+ {% csrf_token %}
+
+ <div class="align-center">
+ <img src="{% asset_url "sentry" "images/logos/default-organization-logo.png" %}" class="org-avatar">
+ </div>
+
+ <div class="align-center">
+ <p>Choose which team you'd like to link to the <b>#{{ channel_name }}</b> channel.</p>
+
+ <div class="align-center" style="padding-bottom:20px;">
+ <select id="{{ form.team.id_for_label }}" name="{{ form.team.html_name }}" class="form-control">
+ {% for team in teams %}
+ <option value="{{ team.id }}">{{ team.slug }}</option>
+ {% endfor %}
+ </select>
+ </div>
+
+ <p>
+ <button type="submit" class="btn btn-default btn-login-{{ provider.key }}">
+ <span class="provider-logo {{ provider.key }}"></span> Link with {{ provider.name }}
+ </button>
+ </p>
+ </div>
+</form>
+{% endblock %}
diff --git a/src/sentry/templates/sentry/slack-post-linked-team.html b/src/sentry/templates/sentry/slack-post-linked-team.html
new file mode 100644
index 00000000000000..718f37115fa7f6
--- /dev/null
+++ b/src/sentry/templates/sentry/slack-post-linked-team.html
@@ -0,0 +1,19 @@
+{% extends "sentry/bases/modal.html" %}
+
+{% load i18n %}
+
+{% block title %}{% trans heading_text %} | {{ block.super }}{% endblock %}
+{% block wrapperclass %}narrow auth{% endblock %}
+
+{% block main %}
+ <div class="align-center">
+ <p>
+ {% trans body_text %}
+ </p>
+ <p>
+ <a href="slack://channel?id={{ channel_id }}&team={{ team_id }}" class="btn btn-default btn-login-slack">
+ <span class="provider-logo slack"></span> Go back to Slack
+ </a>
+ </p>
+ </div>
+{% endblock %}
diff --git a/tests/sentry/api/endpoints/test_integrations_slack_commands.py b/tests/sentry/api/endpoints/test_integrations_slack_commands.py
index 0bd2942dc27827..9c0084df15ac63 100644
--- a/tests/sentry/api/endpoints/test_integrations_slack_commands.py
+++ b/tests/sentry/api/endpoints/test_integrations_slack_commands.py
@@ -1,14 +1,18 @@
from typing import Mapping, Optional
from urllib.parse import urlencode
+import responses
from django.urls import reverse
from requests import Response
from rest_framework import status
from sentry import options
+from sentry.integrations.slack.command_endpoint import LINK_USER_MESSAGE
+from sentry.integrations.slack.link_team import build_linking_url
from sentry.integrations.slack.util.auth import set_signing_secret
-from sentry.models import Integration
-from sentry.testutils import APITestCase
+from sentry.models import ExternalActor, Identity, IdentityProvider, IdentityStatus, Integration
+from sentry.testutils import APITestCase, TestCase
+from sentry.types.integrations import ExternalProviders
from sentry.utils import json
@@ -19,7 +23,7 @@ def assert_is_help_text(response: Response, expected_command: Optional[str] = No
assert expected_command in data["text"]
-class SlackCommandsTest(APITestCase):
+class SlackCommandsTest(APITestCase, TestCase):
endpoint = "sentry-integration-slack-commands"
def get_slack_response(
@@ -40,8 +44,15 @@ def setUp(self):
super().setUp()
self.external_id = "slack:1"
self.integration = Integration.objects.create(
- provider="slack", name="Slack", external_id=self.external_id
+ provider="slack",
+ name="Slack",
+ external_id=self.external_id,
+ metadata={
+ "access_token": "xoxp-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx",
+ "installation_type": "born_as_bot",
+ },
)
+ self.integration.add_organization(self.organization, self.user)
class SlackCommandsGetTest(SlackCommandsTest):
@@ -49,7 +60,7 @@ def test_method_get_not_allowed(self):
self.get_error_response(status_code=status.HTTP_405_METHOD_NOT_ALLOWED)
-class SlackCommandsPostTest(SlackCommandsTest):
+class SlackCommandsHelpTest(SlackCommandsTest):
method = "post"
def test_invalid_signature(self):
@@ -70,3 +81,229 @@ def test_invalid_command(self):
def test_help_command(self):
response = self.get_slack_response({"text": "help", "team_id": self.external_id})
assert_is_help_text(response)
+
+
+class SlackCommandsLinkTeamTest(SlackCommandsTest):
+ method = "post"
+
+ def setUp(self):
+ super().setUp()
+ self.idp = IdentityProvider.objects.create(type="slack", external_id="slack:1", config={})
+ self.login_as(self.user)
+ Identity.objects.create(
+ external_id="UXXXXXXX1",
+ idp=self.idp,
+ user=self.user,
+ status=IdentityStatus.VALID,
+ scopes=[],
+ )
+ response = self.get_slack_response(
+ {"text": "link team", "team_id": self.external_id, "user_id": "UXXXXXXX1"}
+ )
+ self.data = json.loads(str(response.content.decode("utf-8")))
+ responses.add(
+ method=responses.POST,
+ url="https://slack.com/api/chat.postMessage",
+ body='{"ok": true}',
+ status=200,
+ content_type="application/json",
+ )
+ self.external_actor = ExternalActor.objects.filter(
+ actor_id=self.team.actor_id,
+ organization=self.organization,
+ integration=self.integration,
+ provider=ExternalProviders.SLACK.value,
+ external_name="general",
+ external_id="CXXXXXXX9",
+ )
+
+ @responses.activate
+ def test_link_team_command(self):
+ """Test that we successfully link a team to a Slack channel"""
+ assert "Link your Sentry team to this Slack channel!" in self.data["text"]
+ linking_url = build_linking_url(
+ self.integration,
+ "UXXXXXXX1",
+ "CXXXXXXX9",
+ "general",
+ "http://example.slack.com/response_url",
+ )
+
+ resp = self.client.get(linking_url)
+ assert resp.status_code == 200
+ self.assertTemplateUsed(resp, "sentry/slack-link-team.html")
+
+ data = urlencode({"team": self.team.id})
+ resp = self.client.post(linking_url, data, content_type="application/x-www-form-urlencoded")
+ assert resp.status_code == 200
+ self.assertTemplateUsed(resp, "sentry/slack-post-linked-team.html")
+
+ assert len(self.external_actor) == 1
+ assert self.external_actor[0].actor_id == self.team.actor_id
+
+ assert len(responses.calls) >= 1
+ data = json.loads(str(responses.calls[0].request.body.decode("utf-8")))
+ assert (
+ f"The {self.team.slug} team will now receive issue alert notifications in the {self.external_actor[0].external_name} channel."
+ in data["text"]
+ )
+
+ def test_link_team_idp_does_not_exist(self):
+ """Test that get_identity fails if we cannot find a matching idp"""
+ self.get_slack_response(
+ {"text": "link team", "team_id": "slack:2", "user_id": "UA1J9RTE1"},
+ status_code=403,
+ )
+
+ def test_link_team_identity_does_not_exist(self):
+ """Test that get_identity fails if the user has no Identity and we reply with the LINK_USER_MESSAGE"""
+ user2 = self.create_user()
+ self.create_member(
+ teams=[self.team], user=user2, role="member", organization=self.organization
+ )
+ self.login_as(user2)
+ response = self.get_slack_response(
+ {"text": "link team", "team_id": self.external_id, "user_id": "UXXXXXXX2"}
+ )
+ data = json.loads(str(response.content.decode("utf-8")))
+ assert LINK_USER_MESSAGE in data["text"]
+
+ @responses.activate
+ def test_link_team_insufficient_role(self):
+ """Test that when a user whose role is insufficient and is a member of the
+ team in question in a closed membership org attempts to link a team, we reject
+ them and reply with the INSUFFICIENT_ROLE_MESSAGE"""
+ user2 = self.create_user()
+ self.create_member(
+ teams=[self.team], user=user2, role="member", organization=self.organization
+ )
+ self.login_as(user2)
+ Identity.objects.create(
+ external_id="UXXXXXXX2",
+ idp=self.idp,
+ user=user2,
+ status=IdentityStatus.VALID,
+ scopes=[],
+ )
+ assert "Link your Sentry team to this Slack channel!" in self.data["text"]
+ linking_url = build_linking_url(
+ self.integration,
+ "UXXXXXXX2",
+ "CXXXXXXX9",
+ "general",
+ "http://example.slack.com/response_url",
+ )
+
+ resp = self.client.get(linking_url)
+
+ assert resp.status_code == 200
+ self.assertTemplateUsed(resp, "sentry/slack-link-team.html")
+
+ data = urlencode({"team": self.team.id})
+ resp = self.client.post(linking_url, data, content_type="application/x-www-form-urlencoded")
+ assert resp.status_code == 200
+ self.assertTemplateUsed(resp, "sentry/slack-post-linked-team.html")
+
+ assert len(self.external_actor) == 0
+
+ assert len(responses.calls) >= 1
+ data = json.loads(str(responses.calls[0].request.body.decode("utf-8")))
+ assert "You must be an admin or higher" in data["text"]
+
+ @responses.activate
+ def test_link_team_insufficient_role_open_membership(self):
+ """Test that when a user whose role is insufficient in an open membership organization
+ attempts to link a team, we reject them and reply with the INSUFFICIENT_ROLE_MESSAGE"""
+ self.organization.flags.allow_joinleave = True
+ user2 = self.create_user()
+ self.create_member(
+ teams=[self.team], user=user2, role="member", organization=self.organization
+ )
+ self.login_as(user2)
+ Identity.objects.create(
+ external_id="UXXXXXXX2",
+ idp=self.idp,
+ user=user2,
+ status=IdentityStatus.VALID,
+ scopes=[],
+ )
+ assert "Link your Sentry team to this Slack channel!" in self.data["text"]
+ linking_url = build_linking_url(
+ self.integration,
+ "UXXXXXXX2",
+ "CXXXXXXX9",
+ "general",
+ "http://example.slack.com/response_url",
+ )
+
+ resp = self.client.get(linking_url)
+
+ assert resp.status_code == 200
+ self.assertTemplateUsed(resp, "sentry/slack-link-team.html")
+
+ data = urlencode({"team": self.team.id})
+ resp = self.client.post(linking_url, data, content_type="application/x-www-form-urlencoded")
+ assert resp.status_code == 200
+ self.assertTemplateUsed(resp, "sentry/slack-post-linked-team.html")
+
+ assert len(self.external_actor) == 0
+
+ assert len(responses.calls) >= 1
+ data = json.loads(str(responses.calls[0].request.body.decode("utf-8")))
+ assert "You must be an admin or higher" in data["text"]
+
+ @responses.activate
+ def test_link_team_already_linked(self):
+ """Test that if a team has already been linked to a Slack channel when a user tries
+ to link them again, we reject the attempt and reply with the ALREADY_LINKED_MESSAGE"""
+ ExternalActor.objects.create(
+ actor_id=self.team.actor_id,
+ organization=self.organization,
+ integration=self.integration,
+ provider=ExternalProviders.SLACK.value,
+ external_name="general",
+ external_id="CXXXXXXX9",
+ )
+ assert "Link your Sentry team to this Slack channel!" in self.data["text"]
+ linking_url = build_linking_url(
+ self.integration,
+ "UXXXXXXX1",
+ "CXXXXXXX9",
+ "general",
+ "http://example.slack.com/response_url",
+ )
+
+ resp = self.client.get(linking_url)
+
+ assert resp.status_code == 200
+ self.assertTemplateUsed(resp, "sentry/slack-link-team.html")
+
+ data = urlencode({"team": self.team.id})
+ resp = self.client.post(linking_url, data, content_type="application/x-www-form-urlencoded")
+ assert resp.status_code == 200
+ self.assertTemplateUsed(resp, "sentry/slack-post-linked-team.html")
+ assert len(responses.calls) >= 1
+ data = json.loads(str(responses.calls[0].request.body.decode("utf-8")))
+ assert (
+ f"The {self.team.slug} team has already been linked to a Slack channel." in data["text"]
+ )
+
+ def test_error_page(self):
+ """Test that we successfully render an error page when bad form data is sent."""
+ assert "Link your Sentry team to this Slack channel!" in self.data["text"]
+ linking_url = build_linking_url(
+ self.integration,
+ "UXXXXXXX1",
+ "CXXXXXXX9",
+ "general",
+ "http://example.slack.com/response_url",
+ )
+
+ resp = self.client.get(linking_url)
+ assert resp.status_code == 200
+ self.assertTemplateUsed(resp, "sentry/slack-link-team.html")
+
+ data = urlencode({"team": ["some", "garbage"]})
+ resp = self.client.post(linking_url, data, content_type="application/x-www-form-urlencoded")
+ assert resp.status_code == 200
+ self.assertTemplateUsed(resp, "sentry/slack-link-team-error.html")
|
416b7f487c1ae5ee150f16ba0b9dfbded24bff6c
|
2024-03-16 02:32:20
|
Ryan Albrecht
|
chore: Stop checking organizations:session-replay-count-query-optimize (#64306)
| false
|
Stop checking organizations:session-replay-count-query-optimize (#64306)
|
chore
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index 5f559dabe5dbd4..dc1b44944030a5 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -1841,8 +1841,6 @@ def custom_parameter_sort(parameter: dict) -> tuple[str, int]:
"organizations:session-replay-accessibility-issues": False,
# Enable combined envelope Kafka items in Relay
"organizations:session-replay-combined-envelope-items": False,
- # Enable core Session Replay SDK for recording onError events on sentry.io
- "organizations:session-replay-count-query-optimize": False,
# Enable canvas recording
"organizations:session-replay-enable-canvas": False,
# Enable canvas replaying
diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py
index 08e6848ad20092..4a18c7494703f3 100644
--- a/src/sentry/features/__init__.py
+++ b/src/sentry/features/__init__.py
@@ -241,7 +241,6 @@
default_manager.add("organizations:session-replay-a11y-tab", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:session-replay-accessibility-issues", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:session-replay-combined-envelope-items", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
-default_manager.add("organizations:session-replay-count-query-optimize", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:session-replay-enable-canvas-replayer", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:session-replay-enable-canvas", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:session-replay-issue-emails", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
diff --git a/src/sentry/replays/endpoints/organization_replay_count.py b/src/sentry/replays/endpoints/organization_replay_count.py
index b7cafffd30c888..2e136fe0513b9e 100644
--- a/src/sentry/replays/endpoints/organization_replay_count.py
+++ b/src/sentry/replays/endpoints/organization_replay_count.py
@@ -93,11 +93,8 @@ def get(self, request: Request, organization: Organization) -> Response:
except NoProjects:
return Response({})
- if features.has(
- "organizations:session-replay-count-query-optimize", organization, actor=request.user
- ):
- if not project_in_org_has_sent_replay(organization):
- return Response({})
+ if not project_in_org_has_sent_replay(organization):
+ return Response({})
result = ReplayDataSourceValidator(data=request.GET)
if not result.is_valid():
diff --git a/tests/sentry/replays/test_organization_replay_count.py b/tests/sentry/replays/test_organization_replay_count.py
index e12d5218d4377b..a87281c4e5b873 100644
--- a/tests/sentry/replays/test_organization_replay_count.py
+++ b/tests/sentry/replays/test_organization_replay_count.py
@@ -31,6 +31,7 @@ class OrganizationReplayCountEndpointTest(
):
def setUp(self):
super().setUp()
+ self.project.update(flags=F("flags").bitor(Project.flags.has_replays))
self.min_ago = before_now(minutes=1)
self.login_as(user=self.user)
self.url = reverse(
|
f9014d6c26ea1328247a3870d551c88ec584005f
|
2022-03-25 00:18:28
|
Armen Zambrano G
|
fix(ci): Prevent Visual Snapshots from triggering when not all jobs complete (#32915)
| false
|
Prevent Visual Snapshots from triggering when not all jobs complete (#32915)
|
fix
|
diff --git a/.github/workflows/acceptance.yml b/.github/workflows/acceptance.yml
index 5d5fb2b019e9f7..144236ccd61297 100644
--- a/.github/workflows/acceptance.yml
+++ b/.github/workflows/acceptance.yml
@@ -265,3 +265,22 @@ jobs:
- name: Handle artifacts
uses: ./.github/actions/artifacts
+
+ visual-diff:
+ # This guarantees that we will only schedule Visual Snapshots if all
+ # workflows that generate artifacts succeed
+ needs: [acceptance, frontend, chartcuterie]
+ name: triggers visual snapshot
+ # Do not execute on forks or on master
+ if: github.repository == 'getsentry/sentry' && github.ref != 'refs/heads/master'
+ runs-on: ubuntu-20.04
+ timeout-minutes: 20
+
+ steps:
+ - name: Diff snapshots
+ id: visual-snapshots-diff
+ uses: getsentry/action-visual-snapshot@v2
+ with:
+ api-token: ${{ secrets.VISUAL_SNAPSHOT_SECRET }}
+ gcs-bucket: 'sentry-visual-snapshots'
+ gcp-service-account-key: ${{ secrets.SNAPSHOT_GOOGLE_SERVICE_ACCOUNT_KEY }}
diff --git a/.github/workflows/visual-diff.yml b/.github/workflows/visual-diff.yml
deleted file mode 100644
index de35acaf5b25ef..00000000000000
--- a/.github/workflows/visual-diff.yml
+++ /dev/null
@@ -1,22 +0,0 @@
-name: visual diff
-on:
- workflow_run:
- workflows:
- - acceptance
- types:
- - completed
-
-jobs:
- visual-diff:
- if: github.repository == 'getsentry/sentry'
- runs-on: ubuntu-20.04
- timeout-minutes: 20
-
- steps:
- - name: Diff snapshots
- id: visual-snapshots-diff
- uses: getsentry/action-visual-snapshot@v2
- with:
- api-token: ${{ secrets.VISUAL_SNAPSHOT_SECRET }}
- gcs-bucket: 'sentry-visual-snapshots'
- gcp-service-account-key: ${{ secrets.SNAPSHOT_GOOGLE_SERVICE_ACCOUNT_KEY }}
|
79737728d87fa4e37d3f84458eb87a5f9380e823
|
2021-06-17 18:31:50
|
Shruthi
|
feat(performance): Org-level Apdex updates Project-level threshold (#26642)
| false
|
Org-level Apdex updates Project-level threshold (#26642)
|
feat
|
diff --git a/src/sentry/api/endpoints/organization_details.py b/src/sentry/api/endpoints/organization_details.py
index 0412f7a3c6464f..e37c7f5115b4a4 100644
--- a/src/sentry/api/endpoints/organization_details.py
+++ b/src/sentry/api/endpoints/organization_details.py
@@ -3,7 +3,7 @@
from datetime import datetime
from uuid import uuid4
-from django.db import models
+from django.db import models, transaction
from django.db.models.query_utils import DeferredAttribute
from pytz import UTC
from rest_framework import serializers, status
@@ -29,8 +29,11 @@
OrganizationAvatar,
OrganizationOption,
OrganizationStatus,
+ Project,
+ ProjectTransactionThreshold,
UserEmail,
)
+from sentry.models.transaction_threshold import TransactionMetric
from sentry.tasks.deletion import delete_organization
from sentry.utils.cache import memoize
@@ -480,6 +483,8 @@ def put(self, request, organization):
to be available and unique.
:auth: required
"""
+ from sentry import features
+
if request.access.has_scope("org:admin"):
serializer_cls = OwnerOrganizationSerializer
else:
@@ -516,6 +521,35 @@ def put(self, request, organization):
data=changed_data,
)
+ # Temporarily writing org-level apdex changes to ProjectTransactionThreshold
+ # for orgs who don't have the feature enabled so that when this
+ # feature is GA'ed it captures the orgs current apdex threshold.
+ if serializer.validated_data.get("apdexThreshold") is not None and not features.has(
+ "organizations:project-transaction-threshold", organization
+ ):
+ apdex_threshold = serializer.validated_data.get("apdexThreshold")
+
+ with transaction.atomic():
+ ProjectTransactionThreshold.objects.filter(
+ organization_id=organization.id
+ ).delete()
+
+ project_ids = Project.objects.filter(
+ organization_id=organization.id
+ ).values_list("id", flat=True)
+
+ ProjectTransactionThreshold.objects.bulk_create(
+ [
+ ProjectTransactionThreshold(
+ project_id=project_id,
+ organization_id=organization.id,
+ threshold=int(apdex_threshold),
+ metric=TransactionMetric.DURATION.value,
+ )
+ for project_id in project_ids
+ ]
+ )
+
context = serialize(
organization,
request.user,
diff --git a/tests/sentry/api/endpoints/test_organization_details.py b/tests/sentry/api/endpoints/test_organization_details.py
index 36507932ac9f34..c8e74945b31789 100644
--- a/tests/sentry/api/endpoints/test_organization_details.py
+++ b/tests/sentry/api/endpoints/test_organization_details.py
@@ -19,6 +19,7 @@
OrganizationOption,
OrganizationStatus,
)
+from sentry.models.transaction_threshold import ProjectTransactionThreshold, TransactionMetric
from sentry.signals import project_created
from sentry.testutils import APITestCase, TwoFactorAPITestCase, pytest
from sentry.utils import json
@@ -293,6 +294,86 @@ def test_various_options(self):
assert "to {}".format(data["alertsMemberWrite"]) in log.data["alertsMemberWrite"]
assert "to {}".format(data["apdexThreshold"]) in log.data["apdexThreshold"]
+ def test_setting_apdex_creates_project_threshold(self):
+ org = Organization.objects.get(id=self.organization.id)
+ project1 = self.create_project(organization=org, teams=[self.team], name="Bengal")
+ project2 = self.create_project(organization=org, teams=[self.team], name="Tiger")
+
+ ProjectTransactionThreshold.objects.create(
+ project_id=project1.id,
+ organization_id=org.id,
+ threshold=200,
+ metric=TransactionMetric.DURATION.value,
+ )
+
+ AuditLogEntry.objects.filter(organization=self.organization).delete()
+
+ data = {
+ "apdexThreshold": 450,
+ }
+
+ self.get_success_response(self.organization.slug, **data)
+
+ org = Organization.objects.get(id=self.organization.id)
+ options = {o.key: o.value for o in OrganizationOption.objects.filter(organization=org)}
+
+ assert options.get("sentry:apdex_threshold") == 450
+
+ # log created
+ log = AuditLogEntry.objects.get(organization=org)
+ assert log.get_event_display() == "org.edit"
+ assert "to {}".format(data["apdexThreshold"]) in log.data["apdexThreshold"]
+
+ thresholds = ProjectTransactionThreshold.objects.filter(
+ organization_id=org.id, project_id__in=[project1.id, project2.id]
+ )
+
+ assert thresholds.count() == 2
+ assert thresholds[0].threshold == 450
+ assert thresholds[0].metric == TransactionMetric.DURATION.value
+ assert thresholds[1].threshold == 450
+ assert thresholds[1].metric == TransactionMetric.DURATION.value
+
+ def test_setting_apdex_does_not_create_project_threshold(self):
+ org = Organization.objects.get(id=self.organization.id)
+ project1 = self.create_project(organization=org, teams=[self.team], name="Bengal")
+ project2 = self.create_project(organization=org, teams=[self.team], name="Tiger")
+
+ ProjectTransactionThreshold.objects.create(
+ project_id=project1.id,
+ organization_id=org.id,
+ threshold=200,
+ metric=TransactionMetric.DURATION.value,
+ )
+
+ AuditLogEntry.objects.filter(organization=self.organization).delete()
+
+ data = {
+ "apdexThreshold": 450,
+ }
+
+ with self.feature("organizations:project-transaction-threshold"):
+ self.get_success_response(self.organization.slug, **data)
+
+ org = Organization.objects.get(id=self.organization.id)
+ options = {o.key: o.value for o in OrganizationOption.objects.filter(organization=org)}
+
+ assert options.get("sentry:apdex_threshold") == 450
+
+ # log created
+ log = AuditLogEntry.objects.get(organization=org)
+ assert log.get_event_display() == "org.edit"
+ assert "to {}".format(data["apdexThreshold"]) in log.data["apdexThreshold"]
+
+ thresholds = ProjectTransactionThreshold.objects.filter(
+ organization_id=org.id, project_id__in=[project1.id, project2.id]
+ )
+
+ assert thresholds.count() == 1
+ assert thresholds[0].project_id == project1.id
+ assert thresholds[0].threshold == 200
+ assert thresholds[0].metric == TransactionMetric.DURATION.value
+
def test_setting_trusted_relays_forbidden(self):
data = {
"trustedRelays": [
|
980632a6c47c4c77c3c7579433a1b9943b55f201
|
2024-05-01 00:58:56
|
Gabe Villalobos
|
fix(hybrid-cloud): Cross-DB tombstone resubmission (#69814)
| false
|
Cross-DB tombstone resubmission (#69814)
|
fix
|
diff --git a/src/sentry/options/defaults.py b/src/sentry/options/defaults.py
index e16ac04818a746..dbb4f64bef8aae 100644
--- a/src/sentry/options/defaults.py
+++ b/src/sentry/options/defaults.py
@@ -1745,6 +1745,7 @@
register(
"hybrid_cloud.disable_relative_upload_urls", default=False, flags=FLAG_AUTOMATOR_MODIFIABLE
)
+register("hybrid_cloud.allow_cross_db_tombstones", default=False, flags=FLAG_AUTOMATOR_MODIFIABLE)
# Retry controls
register("hybridcloud.regionsiloclient.retries", default=5, flags=FLAG_AUTOMATOR_MODIFIABLE)
diff --git a/src/sentry/tasks/deletion/hybrid_cloud.py b/src/sentry/tasks/deletion/hybrid_cloud.py
index e4d644733886bb..03ae17f3e7a20d 100644
--- a/src/sentry/tasks/deletion/hybrid_cloud.py
+++ b/src/sentry/tasks/deletion/hybrid_cloud.py
@@ -9,6 +9,7 @@
Tombstone row will not, therefore, cascade to any related cross silo rows.
"""
import datetime
+from collections import defaultdict
from dataclasses import dataclass
from hashlib import sha1
from typing import Any
@@ -22,6 +23,8 @@
from django.db.models.manager import BaseManager
from django.utils import timezone
+from sentry import options
+from sentry.db.models import Model
from sentry.db.models.fields.hybrid_cloud_foreign_key import HybridCloudForeignKey
from sentry.models.tombstone import TombstoneBase
from sentry.silo.base import SiloMode
@@ -237,40 +240,22 @@ def _process_tombstone_reconciliation(
prefix = "tombstone"
watermark_manager: BaseManager = tombstone_cls.objects
- watermark_target = "t"
if row_after_tombstone:
prefix = "row"
watermark_manager = field.model.objects
- watermark_target = "r"
watermark_batch = _chunk_watermark_batch(
prefix, field, watermark_manager, batch_size=get_batch_size()
)
has_more = watermark_batch.has_more
- to_delete_ids: list[int] = []
-
if watermark_batch.low < watermark_batch.up:
- oldest_seen: datetime.datetime = timezone.now()
-
- with connections[router.db_for_read(model)].cursor() as conn:
- conn.execute(
- f"""
- SELECT r.id, t.created_at
- FROM {model._meta.db_table} r
- JOIN {tombstone_cls._meta.db_table} t
- ON t.table_name = %(table_name)s AND t.object_identifier = r.{field.name}
- WHERE {watermark_target}.id > %(low)s AND {watermark_target}.id <= %(up)s
- """,
- {
- "table_name": field.foreign_table_name,
- "low": watermark_batch.low,
- "up": watermark_batch.up,
- },
- )
-
- for (row_id, tomb_created) in conn.fetchall():
- to_delete_ids.append(row_id)
- oldest_seen = min(oldest_seen, tomb_created)
+ to_delete_ids, oldest_seen = _get_model_ids_for_tombstone_cascade(
+ tombstone_cls=tombstone_cls,
+ model=model,
+ field=field,
+ row_after_tombstone=row_after_tombstone,
+ watermark_batch=watermark_batch,
+ )
if field.on_delete == "CASCADE":
task = deletions.get(
@@ -306,3 +291,142 @@ def _process_tombstone_reconciliation(
)
return has_more
+
+
+def _get_model_ids_for_tombstone_cascade(
+ tombstone_cls: type[TombstoneBase],
+ model: type[Model],
+ field: HybridCloudForeignKey,
+ row_after_tombstone: bool,
+ watermark_batch: WatermarkBatch,
+) -> tuple[list[int], datetime.datetime]:
+ """
+ Queries the database or databases if spanning multiple, and returns
+ a tuple with a list of row IDs to delete, and the oldest
+ tombstone timestamp for the batch.
+
+ :param tombstone_cls: Either a RegionTombstone or ControlTombstone, depending on
+ which silo the tombstone process is running.
+ :param model: The model with a HybridCloudForeignKey to process.
+ :param field: The HybridCloudForeignKey field from the model to process.
+ :param row_after_tombstone: Determines which table is bound by the
+ watermark batch. When set to true, the model's IDs are used as the
+ bounds, otherwise, the tombstone's IDs are used.
+ :param watermark_batch: The batch information containing ID bounds for the
+ watermark query.
+ :return:
+ """
+
+ to_delete_ids = []
+ oldest_seen = timezone.now()
+ tombstone_and_model_in_same_db = router.db_for_read(model) == router.db_for_read(tombstone_cls)
+ watermark_target = "t"
+
+ if row_after_tombstone:
+ watermark_target = "r"
+
+ if tombstone_and_model_in_same_db:
+ with connections[router.db_for_read(model)].cursor() as conn:
+ conn.execute(
+ f"""
+ SELECT r.id, t.created_at
+ FROM {model._meta.db_table} r
+ JOIN {tombstone_cls._meta.db_table} t
+ ON t.table_name = %(table_name)s AND t.object_identifier = r.{field.name}
+ WHERE {watermark_target}.id > %(low)s AND {watermark_target}.id <= %(up)s
+ """,
+ {
+ "table_name": field.foreign_table_name,
+ "low": watermark_batch.low,
+ "up": watermark_batch.up,
+ },
+ )
+
+ for (row_id, tomb_created) in conn.fetchall():
+ to_delete_ids.append(row_id)
+ oldest_seen = min(oldest_seen, tomb_created)
+
+ return to_delete_ids, oldest_seen
+
+ if not options.get("hybrid_cloud.allow_cross_db_tombstones"):
+ raise Exception("Cannot process tombstones due to model living in separate database.")
+
+ # Because tombstones can span multiple databases, we can't always rely on
+ # the join code above. Instead, we have to manually query IDs from the
+ # watermark target table, querying the intersection of IDs manually.
+ # The implementation of this varies depending on whether we are
+ # processing row or tombstone watermarks.
+ if row_after_tombstone:
+ return get_ids_cross_db_for_row_watermark(
+ tombstone_cls=tombstone_cls,
+ model=model,
+ field=field,
+ row_watermark_batch=watermark_batch,
+ )
+
+ return get_ids_cross_db_for_tombstone_watermark(
+ tombstone_cls=tombstone_cls,
+ model=model,
+ field=field,
+ tombstone_watermark_batch=watermark_batch,
+ )
+
+
+def get_ids_cross_db_for_row_watermark(
+ tombstone_cls: type[TombstoneBase],
+ model: type[Model],
+ field: HybridCloudForeignKey,
+ row_watermark_batch: WatermarkBatch,
+) -> tuple[list[int], datetime.datetime]:
+ oldest_seen = timezone.now()
+ model_object_id_pairs = model.objects.filter(
+ id__lte=row_watermark_batch.up, id__gt=row_watermark_batch.low
+ ).values_list("id", f"{field.name}")
+
+ # Construct a map of foreign key IDs to model IDs, which gives us the
+ # minimal set of foreign key values to lookup in the tombstones table.
+ fk_to_model_id_map: defaultdict[int, set[int]] = defaultdict(set)
+ for m_id, o_id in model_object_id_pairs:
+ fk_to_model_id_map[o_id].add(m_id)
+
+ object_ids_to_check = fk_to_model_id_map.keys()
+ tombstone_entries = tombstone_cls.objects.filter(
+ object_identifier__in=object_ids_to_check,
+ table_name=field.foreign_table_name,
+ ).values_list("object_identifier", "created_at")
+
+ affected_rows: list[int] = []
+ # Once we have the intersecting tombstones, use the dictionary we
+ # created before to construct the minimal set of model IDs we need to
+ # update with cascade behavior.
+ for object_id, created_at in tombstone_entries:
+ affected_rows.extend(fk_to_model_id_map[object_id])
+ oldest_seen = min(oldest_seen, created_at)
+
+ return affected_rows, oldest_seen
+
+
+def get_ids_cross_db_for_tombstone_watermark(
+ tombstone_cls: type[TombstoneBase],
+ model: type[Model],
+ field: HybridCloudForeignKey,
+ tombstone_watermark_batch: WatermarkBatch,
+) -> tuple[list[int], datetime.datetime]:
+ oldest_seen = timezone.now()
+
+ tombstone_entries = tombstone_cls.objects.filter(
+ id__lte=tombstone_watermark_batch.up,
+ id__gt=tombstone_watermark_batch.low,
+ table_name=field.foreign_table_name,
+ ).values_list("object_identifier", "created_at")
+
+ ids_to_check = []
+ for object_id, created_at in tombstone_entries:
+ ids_to_check.append(object_id)
+ oldest_seen = min(oldest_seen, created_at)
+
+ field_name = f"{field.name}__in"
+ query_kwargs = {field_name: ids_to_check}
+ affected_rows = list(model.objects.filter(**query_kwargs).values_list("id", flat=True))
+
+ return affected_rows, oldest_seen
diff --git a/tests/sentry/tasks/deletion/test_hybrid_cloud.py b/tests/sentry/tasks/deletion/test_hybrid_cloud.py
index 3dc598aaa40c92..b76bf297a705ee 100644
--- a/tests/sentry/tasks/deletion/test_hybrid_cloud.py
+++ b/tests/sentry/tasks/deletion/test_hybrid_cloud.py
@@ -1,3 +1,4 @@
+from operator import itemgetter
from unittest.mock import patch
import pytest
@@ -12,19 +13,31 @@
from sentry.models.integrations.integration import Integration
from sentry.models.outbox import ControlOutbox, OutboxScope, outbox_context
from sentry.models.savedsearch import SavedSearch
+from sentry.models.tombstone import RegionTombstone
from sentry.models.user import User
+from sentry.monitors.models import Monitor
from sentry.silo.base import SiloMode
from sentry.tasks.deletion.hybrid_cloud import (
+ WatermarkBatch,
+ get_ids_cross_db_for_row_watermark,
+ get_ids_cross_db_for_tombstone_watermark,
get_watermark,
schedule_hybrid_cloud_foreign_key_jobs,
schedule_hybrid_cloud_foreign_key_jobs_control,
set_watermark,
)
+from sentry.testutils.cases import TestCase
from sentry.testutils.factories import Factories
+from sentry.testutils.helpers import override_options
from sentry.testutils.helpers.task_runner import BurstTaskRunner
from sentry.testutils.outbox import outbox_runner
from sentry.testutils.pytest.fixtures import django_db_all
-from sentry.testutils.silo import assume_test_silo_mode, control_silo_test
+from sentry.testutils.silo import (
+ assume_test_silo_mode,
+ assume_test_silo_mode_of,
+ control_silo_test,
+ region_silo_test,
+)
from sentry.types.region import find_regions_for_user
@@ -274,3 +287,465 @@ def test_set_null_deletion_behavior(task_runner):
# Deletion set field to null
saved_query = DiscoverSavedQuery.objects.get(id=saved_query.id)
assert saved_query.created_by_id is None
+
+
+def setup_cross_db_deletion_data(
+ desired_user_id: int | None = None,
+ desired_monitor_id: int | None = None,
+):
+ user = Factories.create_user(id=desired_user_id)
+ organization = Factories.create_organization(owner=user, name="Delete Me")
+ project = Factories.create_project(organization=organization)
+ group = Factories.create_group(project=project)
+ with assume_test_silo_mode_of(DiscoverSavedQuery, Monitor):
+ saved_query = DiscoverSavedQuery.objects.create(
+ name="disco-query",
+ organization=organization,
+ created_by_id=user.id,
+ )
+ monitor = Monitor.objects.create(
+ id=desired_monitor_id,
+ organization_id=organization.id,
+ project_id=project.id,
+ slug="test-monitor",
+ name="Test Monitor",
+ owner_user_id=user.id,
+ )
+
+ assert monitor.owner_user_id == user.id
+
+ return dict(
+ user=user,
+ organization=organization,
+ project=project,
+ monitor=monitor,
+ group=group,
+ saved_query=saved_query,
+ )
+
+
+# TODO(Gabe): Enable this test when the multi-db test changes land
+@region_silo_test
[email protected]
+class TestCrossDatabaseTombstoneCascadeBehavior(TestCase):
+ def assert_monitors_unchanged(self, unaffected_data: list[dict]):
+ for u_data in unaffected_data:
+ u_user, u_monitor = itemgetter("user", "monitor")(u_data)
+ queried_monitor = Monitor.objects.get(id=u_monitor.id)
+ # Validate that none of the existing user's monitors have been affected
+ assert u_monitor.owner_user_id is not None
+ assert u_monitor.owner_user_id == queried_monitor.owner_user_id
+ assert u_monitor.owner_user_id == u_user.id
+
+ def assert_monitors_user_ids_null(self, monitors: list[Monitor]):
+ for monitor in monitors:
+ monitor.refresh_from_db()
+ assert monitor.owner_user_id is None
+
+ def run_hybrid_cloud_fk_jobs(self):
+ with override_options({"hybrid_cloud.allow_cross_db_tombstones": True}):
+ with BurstTaskRunner() as burst:
+ schedule_hybrid_cloud_foreign_key_jobs()
+
+ burst()
+
+ def test_raises_when_option_disabled(self):
+ data = setup_cross_db_deletion_data()
+ user, monitor = itemgetter("user", "monitor")(data)
+ with assume_test_silo_mode_of(User), outbox_runner():
+ User.objects.get(id=user.id).delete()
+
+ assert Monitor.objects.filter(id=monitor.id).exists()
+
+ with pytest.raises(Exception) as exc, override_options(
+ {"hybrid_cloud.allow_cross_db_tombstones": False}
+ ):
+ with BurstTaskRunner() as burst:
+ schedule_hybrid_cloud_foreign_key_jobs()
+
+ burst()
+
+ assert exc.match("Cannot process tombstones due to model living in separate database.")
+ assert Monitor.objects.filter(id=monitor.id).exists()
+
+ def test_cross_db_deletion(self):
+ data = setup_cross_db_deletion_data()
+ user, monitor, organization, project = itemgetter(
+ "user", "monitor", "organization", "project"
+ )(data)
+ unaffected_data = [setup_cross_db_deletion_data() for _ in range(3)]
+
+ affected_monitors = [monitor]
+
+ affected_monitors.extend(
+ [
+ Monitor.objects.create(
+ id=5 + i * 2, # Ensure that each monitor is in its own batch
+ organization_id=organization.id,
+ project_id=project.id,
+ slug=f"test-monitor-{i}",
+ name="Test Monitor",
+ owner_user_id=user.id,
+ )
+ for i in range(4)
+ ]
+ )
+
+ with assume_test_silo_mode_of(User), outbox_runner():
+ User.objects.get(id=user.id).delete()
+
+ assert Monitor.objects.filter(id=monitor.id).exists()
+ assert monitor.owner_user_id == user.id
+
+ self.run_hybrid_cloud_fk_jobs()
+
+ self.assert_monitors_unchanged(unaffected_data=unaffected_data)
+ self.assert_monitors_user_ids_null(monitors=affected_monitors)
+
+ def test_deletion_row_after_tombstone(self):
+ data = setup_cross_db_deletion_data()
+ user, monitor, organization, project = itemgetter(
+ "user", "monitor", "organization", "project"
+ )(data)
+ unaffected_data = [setup_cross_db_deletion_data() for _ in range(3)]
+
+ affected_monitors = [monitor]
+
+ with assume_test_silo_mode_of(User), outbox_runner():
+ User.objects.get(id=user.id).delete()
+
+ assert Monitor.objects.filter(id=monitor.id).exists()
+ assert monitor.owner_user_id == user.id
+
+ self.run_hybrid_cloud_fk_jobs()
+
+ self.assert_monitors_unchanged(unaffected_data=unaffected_data)
+ self.assert_monitors_user_ids_null(monitors=affected_monitors)
+
+ # Same as previous test, but this time with monitors created after
+ # the tombstone has been processed
+ affected_monitors.extend(
+ [
+ Monitor.objects.create(
+ id=10 + i * 2, # Ensure that each monitor is in its own batch
+ organization_id=organization.id,
+ project_id=project.id,
+ slug=f"test-monitor-{i}",
+ name="Test Monitor",
+ owner_user_id=user.id,
+ )
+ for i in range(4)
+ ]
+ )
+
+ self.run_hybrid_cloud_fk_jobs()
+
+ self.assert_monitors_unchanged(unaffected_data=unaffected_data)
+ self.assert_monitors_user_ids_null(monitors=affected_monitors)
+
+ def test_empty_tombstones_table(self):
+ unaffected_data = [setup_cross_db_deletion_data() for _ in range(3)]
+ assert RegionTombstone.objects.count() == 0
+
+ self.run_hybrid_cloud_fk_jobs()
+ self.assert_monitors_unchanged(unaffected_data=unaffected_data)
+
+
+@region_silo_test
+class TestGetIdsForTombstoneCascadeCrossDbTombstoneWatermarking(TestCase):
+ def test_get_ids_for_tombstone_cascade_cross_db(self):
+ data = setup_cross_db_deletion_data()
+
+ unaffected_data = []
+ for i in range(3):
+ unaffected_data.append(setup_cross_db_deletion_data())
+
+ user = data["user"]
+ user_id = user.id
+ monitor = data["monitor"]
+ with assume_test_silo_mode_of(User), outbox_runner():
+ user.delete()
+
+ tombstone = RegionTombstone.objects.get(
+ object_identifier=user_id, table_name=User._meta.db_table
+ )
+
+ highest_tombstone_id = RegionTombstone.objects.aggregate(Max("id"))
+ monitor_owner_field = Monitor._meta.get_field("owner_user_id")
+
+ ids, oldest_obj = get_ids_cross_db_for_tombstone_watermark(
+ tombstone_cls=RegionTombstone,
+ model=Monitor,
+ field=monitor_owner_field,
+ tombstone_watermark_batch=WatermarkBatch(
+ low=0,
+ up=highest_tombstone_id["id__max"] + 1,
+ has_more=False,
+ transaction_id="foobar",
+ ),
+ )
+ assert ids == [monitor.id]
+ assert oldest_obj == tombstone.created_at
+
+ def test_get_ids_for_tombstone_cascade_cross_db_watermark_bounds(self):
+ cascade_data = [setup_cross_db_deletion_data() for _ in range(3)]
+
+ # Create some additional filler data
+ [setup_cross_db_deletion_data() for _ in range(3)]
+
+ in_order_tombstones = []
+ for data in cascade_data:
+ user = data["user"]
+ user_id = user.id
+ with assume_test_silo_mode_of(User), outbox_runner():
+ user.delete()
+
+ in_order_tombstones.append(
+ RegionTombstone.objects.get(
+ object_identifier=user_id, table_name=User._meta.db_table
+ )
+ )
+
+ bounds_with_expected_results = [
+ (
+ {"low": 0, "up": in_order_tombstones[1].id},
+ [cascade_data[0]["monitor"].id, cascade_data[1]["monitor"].id],
+ ),
+ (
+ {"low": in_order_tombstones[1].id, "up": in_order_tombstones[2].id},
+ [cascade_data[2]["monitor"].id],
+ ),
+ (
+ {"low": 0, "up": in_order_tombstones[0].id - 1},
+ [],
+ ),
+ (
+ {"low": in_order_tombstones[2].id + 1, "up": in_order_tombstones[2].id + 5},
+ [],
+ ),
+ (
+ {"low": -1, "up": in_order_tombstones[2].id + 1},
+ [
+ cascade_data[0]["monitor"].id,
+ cascade_data[1]["monitor"].id,
+ cascade_data[2]["monitor"].id,
+ ],
+ ),
+ ]
+
+ for bounds, bounds_with_expected_results in bounds_with_expected_results:
+ monitor_owner_field = Monitor._meta.get_field("owner_user_id")
+
+ ids, oldest_obj = get_ids_cross_db_for_tombstone_watermark(
+ tombstone_cls=RegionTombstone,
+ model=Monitor,
+ field=monitor_owner_field,
+ tombstone_watermark_batch=WatermarkBatch(
+ low=bounds["low"],
+ up=bounds["up"],
+ has_more=False,
+ transaction_id="foobar",
+ ),
+ )
+ assert ids == bounds_with_expected_results
+
+ def test_get_ids_for_tombstone_cascade_cross_db_with_multiple_tombstone_types(self):
+ data = setup_cross_db_deletion_data()
+ unaffected_data = [setup_cross_db_deletion_data() for _ in range(3)]
+
+ # Pollute the tombstone data with references to relationships in other
+ # tables matching other User IDs just to ensure we are filtering on the
+ # correct table name.
+ for udata in unaffected_data:
+ unaffected_user = udata["user"]
+ RegionTombstone.objects.create(
+ table_name="something_table", object_identifier=unaffected_user.id
+ )
+
+ user, monitor = itemgetter("user", "monitor")(data)
+ user_id = user.id
+ with assume_test_silo_mode_of(User), outbox_runner():
+ user.delete()
+
+ tombstone = RegionTombstone.objects.get(
+ object_identifier=user_id, table_name=User._meta.db_table
+ )
+
+ highest_tombstone_id = RegionTombstone.objects.aggregate(Max("id"))
+
+ ids, oldest_obj = get_ids_cross_db_for_tombstone_watermark(
+ tombstone_cls=RegionTombstone,
+ model=Monitor,
+ field=Monitor._meta.get_field("owner_user_id"),
+ tombstone_watermark_batch=WatermarkBatch(
+ low=0,
+ up=highest_tombstone_id["id__max"] + 1,
+ has_more=False,
+ transaction_id="foobar",
+ ),
+ )
+ assert ids == [monitor.id]
+ assert oldest_obj == tombstone.created_at
+
+
+@region_silo_test
+class TestGetIdsForTombstoneCascadeCrossDbRowWatermarking(TestCase):
+ def test_with_simple_tombstone_intersection(self):
+ data = setup_cross_db_deletion_data(desired_user_id=10, desired_monitor_id=42)
+ user, monitor = itemgetter("user", "monitor")(data)
+
+ assert user.id == 10
+ user_id = user.id
+ assert monitor.id == 42
+
+ with assume_test_silo_mode_of(User), outbox_runner():
+ user.delete()
+
+ highest_model_id = Monitor.objects.aggregate(Max("id"))
+ tombstone = RegionTombstone.objects.get(
+ object_identifier=user_id, table_name=User._meta.db_table
+ )
+ ids, oldest_obj = get_ids_cross_db_for_row_watermark(
+ tombstone_cls=RegionTombstone,
+ model=Monitor,
+ field=Monitor._meta.get_field("owner_user_id"),
+ row_watermark_batch=WatermarkBatch(
+ low=0,
+ up=highest_model_id["id__max"] + 1,
+ has_more=False,
+ transaction_id="foobar",
+ ),
+ )
+
+ assert ids == [monitor.id]
+ assert oldest_obj == tombstone.created_at
+
+ def test_with_empty_tombstones_table(self):
+ # Set up some sample data that shouldn't be affected
+ with outbox_runner():
+ [setup_cross_db_deletion_data() for _ in range(3)]
+
+ highest_model_id = Monitor.objects.aggregate(Max("id"))["id__max"]
+
+ assert highest_model_id is not None
+ assert not RegionTombstone.objects.filter().exists()
+
+ ids, oldest_obj = get_ids_cross_db_for_row_watermark(
+ tombstone_cls=RegionTombstone,
+ model=Monitor,
+ field=Monitor._meta.get_field("owner_user_id"),
+ row_watermark_batch=WatermarkBatch(
+ low=0,
+ up=highest_model_id + 1,
+ has_more=False,
+ transaction_id="foobar",
+ ),
+ )
+
+ assert ids == []
+
+ def test_row_watermarking_bounds(self):
+ # In testing, the IDs for these models will be low, sequential values
+ # so adding some seed data to space the IDs out gives better insight
+ # on filter correctness.
+ desired_user_and_monitor_ids = [(10, 9), (42, 30), (77, 120)]
+ cascade_data = [
+ setup_cross_db_deletion_data(desired_user_id=user_id, desired_monitor_id=monitor_id)
+ for user_id, monitor_id in desired_user_and_monitor_ids
+ ]
+
+ # Create some additional filler data
+ [setup_cross_db_deletion_data() for _ in range(3)]
+
+ with assume_test_silo_mode_of(User), outbox_runner():
+ for data in cascade_data:
+ user = data["user"]
+ User.objects.get(id=user.id).delete()
+
+ bounds_with_expected_results = [
+ # Get batch containing first 2 monitors
+ (
+ {"low": 0, "up": cascade_data[1]["monitor"].id},
+ [cascade_data[0]["monitor"].id, cascade_data[1]["monitor"].id],
+ ),
+ # Get batch containing only the last monitor
+ (
+ {"low": cascade_data[1]["monitor"].id, "up": cascade_data[2]["monitor"].id},
+ [cascade_data[2]["monitor"].id],
+ ),
+ # Get batch after all current monitors, testing upper bound
+ (
+ {"low": 0, "up": cascade_data[0]["monitor"].id - 1},
+ [],
+ ),
+ # Get batch with all 3 monitors
+ (
+ {"low": -1, "up": cascade_data[2]["monitor"].id + 1},
+ [
+ cascade_data[0]["monitor"].id,
+ cascade_data[1]["monitor"].id,
+ cascade_data[2]["monitor"].id,
+ ],
+ ),
+ # Get batch preceeding all monitors
+ (
+ {"low": cascade_data[1]["monitor"].id, "up": cascade_data[2]["monitor"].id - 1},
+ [],
+ ),
+ ]
+
+ for bounds, bounds_with_expected_results in bounds_with_expected_results:
+ monitor_owner_field = Monitor._meta.get_field("owner_user_id")
+
+ ids, oldest_obj = get_ids_cross_db_for_row_watermark(
+ tombstone_cls=RegionTombstone,
+ model=Monitor,
+ field=monitor_owner_field,
+ row_watermark_batch=WatermarkBatch(
+ low=bounds["low"],
+ up=bounds["up"],
+ has_more=False,
+ transaction_id="foobar",
+ ),
+ )
+ assert (
+ ids == bounds_with_expected_results
+ ), f"Expected IDs '{bounds_with_expected_results}', got '{ids}', for input: '{bounds}'"
+
+ def test_get_ids_for_tombstone_cascade_cross_db_with_multiple_tombstone_types(self):
+ data = setup_cross_db_deletion_data()
+ unaffected_data = [setup_cross_db_deletion_data() for _ in range(3)]
+
+ # Similar to the test in the tombstone watermarking code, we pollute
+ # the data with same user IDs, but different table to ensure we only
+ # select the intersection of IDs from the monitor tombstones.
+ for udata in unaffected_data:
+ unaffected_user = udata["user"]
+ RegionTombstone.objects.create(
+ table_name="something_table", object_identifier=unaffected_user.id
+ )
+
+ user, monitor = itemgetter("user", "monitor")(data)
+ user_id = user.id
+ with assume_test_silo_mode_of(User), outbox_runner():
+ user.delete()
+
+ tombstone = RegionTombstone.objects.get(
+ object_identifier=user_id, table_name=User._meta.db_table
+ )
+
+ highest_model_id = Monitor.objects.aggregate(Max("id"))["id__max"]
+
+ ids, oldest_obj = get_ids_cross_db_for_row_watermark(
+ tombstone_cls=RegionTombstone,
+ model=Monitor,
+ field=Monitor._meta.get_field("owner_user_id"),
+ row_watermark_batch=WatermarkBatch(
+ low=0,
+ up=highest_model_id + 1,
+ has_more=False,
+ transaction_id="foobar",
+ ),
+ )
+ assert ids == [monitor.id]
+ assert oldest_obj == tombstone.created_at
|
8e4412eb485d83ed5e868d92497c84b58445169f
|
2020-09-25 23:28:48
|
Danny Lee
|
ref(ts): Set children on Forms as optional (#20953)
| false
|
Set children on Forms as optional (#20953)
|
ref
|
diff --git a/src/sentry/static/sentry/app/views/settings/components/forms/form.tsx b/src/sentry/static/sentry/app/views/settings/components/forms/form.tsx
index f9a9fd4d671980..ff377b56801aae 100644
--- a/src/sentry/static/sentry/app/views/settings/components/forms/form.tsx
+++ b/src/sentry/static/sentry/app/views/settings/components/forms/form.tsx
@@ -22,7 +22,7 @@ type RenderFunc = (props: RenderProps) => React.ReactNode;
type Props = {
apiMethod?: APIRequestMethod;
apiEndpoint?: string;
- children: React.ReactNode | RenderFunc;
+ children?: React.ReactNode | RenderFunc;
className?: string;
cancelLabel?: string;
submitDisabled?: boolean;
|
0340b9ffe46b135cfa8d041bba72ddc16de29ebe
|
2022-03-03 20:01:14
|
Joris Bayer
|
feat(performance): Expose transaction thresholds in relay config (#32116)
| false
|
Expose transaction thresholds in relay config (#32116)
|
feat
|
diff --git a/src/sentry/relay/config.py b/src/sentry/relay/config.py
index 8c2b6b42dfba14..47e148845289ad 100644
--- a/src/sentry/relay/config.py
+++ b/src/sentry/relay/config.py
@@ -1,11 +1,13 @@
+import logging
import uuid
from datetime import datetime
-from typing import Any, List, Mapping, Optional
+from typing import Any, List, Mapping, Optional, TypedDict
from pytz import utc
from sentry_sdk import Hub, capture_exception
from sentry import features, quotas, utils
+from sentry.api.endpoints.project_transaction_threshold import DEFAULT_THRESHOLD
from sentry.constants import ObjectStatus
from sentry.datascrubbing import get_datascrubbing_settings, get_pii_config
from sentry.grouping.api import get_grouping_config_dict_for_project
@@ -17,6 +19,7 @@
)
from sentry.interfaces.security import DEFAULT_DISALLOWED_SOURCES
from sentry.models import Project
+from sentry.models.transaction_threshold import TRANSACTION_METRICS as TRANSACTION_THRESHOLD_KEYS
from sentry.relay.utils import to_camel_case_name
from sentry.utils import metrics
from sentry.utils.http import get_origins
@@ -28,6 +31,8 @@
"organizations:profiling",
]
+logger = logging.getLogger(__name__)
+
def get_exposed_features(project: Project) -> List[str]:
@@ -397,6 +402,50 @@ def _filter_option_to_config_setting(flt, setting):
)
+class _TransactionThreshold(TypedDict):
+ metric: Optional[str] # Either 'duration' or 'lcp'
+ threshold: float
+
+
+class _TransactionThresholdConfig(TypedDict):
+ #: The project-wide threshold to apply (see `ProjectTransactionThreshold`)
+ projectThreshold: _TransactionThreshold
+ #: Transaction-specific overrides of the project-wide threshold
+ #: (see `ProjectTransactionThresholdOverride`)
+ transactionThresholds: Mapping[str, _TransactionThreshold]
+
+
+def _get_satisfaction_thresholds(project: Project) -> _TransactionThresholdConfig:
+ # Always start with the default threshold, so we do not have to maintain
+ # A separate default in Relay
+ project_threshold: _TransactionThreshold = {
+ "metric": DEFAULT_THRESHOLD["metric"],
+ "threshold": float(DEFAULT_THRESHOLD["threshold"]),
+ }
+
+ # Apply custom project threshold
+ for i, threshold in enumerate(project.projecttransactionthreshold_set.all()):
+ if i > 0:
+ logger.error("More than one transaction threshold exists for project")
+ break
+ project_threshold = {
+ "metric": TRANSACTION_THRESHOLD_KEYS[threshold.metric],
+ "threshold": threshold.threshold,
+ }
+
+ # Apply transaction-specific override
+ return {
+ "projectThreshold": project_threshold,
+ "transactionThresholds": {
+ threshold.transaction: {
+ "metric": TRANSACTION_THRESHOLD_KEYS[threshold.metric],
+ "threshold": threshold.threshold,
+ }
+ for threshold in project.projecttransactionthresholdoverride_set.all()
+ },
+ }
+
+
def get_transaction_metrics_settings(
project: Project, breakdowns_config: Optional[Mapping[str, Any]]
):
@@ -436,4 +485,5 @@ def get_transaction_metrics_settings(
return {
"extractMetrics": metrics,
"extractCustomTags": custom_tags,
+ "satisfactionThresholds": _get_satisfaction_thresholds(project),
}
diff --git a/tests/sentry/relay/snapshots/test_config/test_project_config_satisfaction_thresholds/False/False.pysnap b/tests/sentry/relay/snapshots/test_config/test_project_config_satisfaction_thresholds/False/False.pysnap
new file mode 100644
index 00000000000000..3bb6691b765eab
--- /dev/null
+++ b/tests/sentry/relay/snapshots/test_config/test_project_config_satisfaction_thresholds/False/False.pysnap
@@ -0,0 +1,9 @@
+---
+created: '2022-02-28T13:20:49.317250Z'
+creator: sentry
+source: tests/sentry/relay/test_config.py
+---
+projectThreshold:
+ metric: duration
+ threshold: 300.0
+transactionThresholds: {}
diff --git a/tests/sentry/relay/snapshots/test_config/test_project_config_satisfaction_thresholds/False/True.pysnap b/tests/sentry/relay/snapshots/test_config/test_project_config_satisfaction_thresholds/False/True.pysnap
new file mode 100644
index 00000000000000..b5d2faeafb83b1
--- /dev/null
+++ b/tests/sentry/relay/snapshots/test_config/test_project_config_satisfaction_thresholds/False/True.pysnap
@@ -0,0 +1,9 @@
+---
+created: '2022-02-28T13:20:49.410307Z'
+creator: sentry
+source: tests/sentry/relay/test_config.py
+---
+projectThreshold:
+ metric: lcp
+ threshold: 500
+transactionThresholds: {}
diff --git a/tests/sentry/relay/snapshots/test_config/test_project_config_satisfaction_thresholds/True/False.pysnap b/tests/sentry/relay/snapshots/test_config/test_project_config_satisfaction_thresholds/True/False.pysnap
new file mode 100644
index 00000000000000..2b2bd1354a8dbf
--- /dev/null
+++ b/tests/sentry/relay/snapshots/test_config/test_project_config_satisfaction_thresholds/True/False.pysnap
@@ -0,0 +1,15 @@
+---
+created: '2022-02-28T13:20:49.505288Z'
+creator: sentry
+source: tests/sentry/relay/test_config.py
+---
+projectThreshold:
+ metric: duration
+ threshold: 300.0
+transactionThresholds:
+ bar:
+ metric: lcp
+ threshold: 600
+ foo:
+ metric: duration
+ threshold: 400
diff --git a/tests/sentry/relay/snapshots/test_config/test_project_config_satisfaction_thresholds/True/True.pysnap b/tests/sentry/relay/snapshots/test_config/test_project_config_satisfaction_thresholds/True/True.pysnap
new file mode 100644
index 00000000000000..8fbc4222b79cb2
--- /dev/null
+++ b/tests/sentry/relay/snapshots/test_config/test_project_config_satisfaction_thresholds/True/True.pysnap
@@ -0,0 +1,15 @@
+---
+created: '2022-02-28T13:20:49.611007Z'
+creator: sentry
+source: tests/sentry/relay/test_config.py
+---
+projectThreshold:
+ metric: lcp
+ threshold: 500
+transactionThresholds:
+ bar:
+ metric: lcp
+ threshold: 600
+ foo:
+ metric: duration
+ threshold: 400
diff --git a/tests/sentry/relay/snapshots/test_config/test_project_config_with_breakdown/with_metrics.pysnap b/tests/sentry/relay/snapshots/test_config/test_project_config_with_breakdown/with_metrics.pysnap
index 5ee13f548d3112..c419425c009288 100644
--- a/tests/sentry/relay/snapshots/test_config/test_project_config_with_breakdown/with_metrics.pysnap
+++ b/tests/sentry/relay/snapshots/test_config/test_project_config_with_breakdown/with_metrics.pysnap
@@ -1,5 +1,5 @@
---
-created: '2021-12-15T15:04:19.291385Z'
+created: '2022-02-28T13:20:49.143037Z'
creator: sentry
source: tests/sentry/relay/test_config.py
---
@@ -38,3 +38,8 @@ transactionMetrics:
- sentry.transactions.breakdowns.span_ops.db
- sentry.transactions.breakdowns.span_ops.browser
- sentry.transactions.breakdowns.span_ops.resource
+ satisfactionThresholds:
+ projectThreshold:
+ metric: duration
+ threshold: 300.0
+ transactionThresholds: {}
diff --git a/tests/sentry/relay/test_config.py b/tests/sentry/relay/test_config.py
index 19d12b3da63182..b81f6ec59667be 100644
--- a/tests/sentry/relay/test_config.py
+++ b/tests/sentry/relay/test_config.py
@@ -1,6 +1,7 @@
import pytest
from sentry.models import ProjectKey
+from sentry.models.transaction_threshold import TransactionMetric
from sentry.relay.config import get_project_config
from sentry.testutils.helpers import Feature
from sentry.utils.safe import get_path
@@ -118,6 +119,45 @@ def test_project_config_with_breakdown(default_project, insta_snapshot, transact
)
[email protected]_db
[email protected]("has_project_transaction_threshold", (False, True))
[email protected]("has_project_transaction_threshold_overrides", (False, True))
+def test_project_config_satisfaction_thresholds(
+ default_project,
+ insta_snapshot,
+ has_project_transaction_threshold_overrides,
+ has_project_transaction_threshold,
+):
+ if has_project_transaction_threshold:
+ default_project.projecttransactionthreshold_set.create(
+ organization=default_project.organization,
+ threshold=500,
+ metric=TransactionMetric.LCP.value,
+ )
+ if has_project_transaction_threshold_overrides:
+ default_project.projecttransactionthresholdoverride_set.create(
+ organization=default_project.organization,
+ transaction="foo",
+ threshold=400,
+ metric=TransactionMetric.DURATION.value,
+ )
+ default_project.projecttransactionthresholdoverride_set.create(
+ organization=default_project.organization,
+ transaction="bar",
+ threshold=600,
+ metric=TransactionMetric.LCP.value,
+ )
+ with Feature(
+ {
+ "organizations:transaction-metrics-extraction": True,
+ }
+ ):
+ cfg = get_project_config(default_project, full_config=True)
+
+ cfg = cfg.to_dict()
+ insta_snapshot(cfg["config"]["transactionMetrics"]["satisfactionThresholds"])
+
+
@pytest.mark.django_db
def test_project_config_with_span_attributes(default_project, insta_snapshot):
# The span attributes config is not set with the flag turnd off
|
deebcbcb69f206054bfaef7dc28b7013b13bf231
|
2023-04-11 05:08:21
|
Evan Purkhiser
|
chore(js): Wrap queryClient.setQueryData (#47130)
| false
|
Wrap queryClient.setQueryData (#47130)
|
chore
|
diff --git a/static/app/utils/queryClient.tsx b/static/app/utils/queryClient.tsx
index ee3ae970ac15fe..0c1cf8d81639f6 100644
--- a/static/app/utils/queryClient.tsx
+++ b/static/app/utils/queryClient.tsx
@@ -130,8 +130,17 @@ function useApiQuery<TQueryFnData, TError = RequestError, TData = TQueryFnData>(
return reactQuery.useQuery(queryKey, queryFn, options);
}
+function setApiQueryData<TResponseData>(
+ queryClient: reactQuery.QueryClient,
+ queryKey: ApiQueryKey,
+ updater: reactQuery.Updater<TResponseData | undefined, TResponseData | undefined>,
+ options?: reactQuery.SetDataOptions
+): TResponseData | undefined {
+ return queryClient.setQueryData(queryKey, updater, options);
+}
+
// eslint-disable-next-line import/export
export * from '@tanstack/react-query';
// eslint-disable-next-line import/export
-export {DEFAULT_QUERY_CLIENT_CONFIG, useApiQuery};
+export {DEFAULT_QUERY_CLIENT_CONFIG, useApiQuery, setApiQueryData};
diff --git a/static/app/views/issueList/mutations/useCreateSavedSearch.tsx b/static/app/views/issueList/mutations/useCreateSavedSearch.tsx
index 18a8023127e6d1..435624e6987ba5 100644
--- a/static/app/views/issueList/mutations/useCreateSavedSearch.tsx
+++ b/static/app/views/issueList/mutations/useCreateSavedSearch.tsx
@@ -1,5 +1,10 @@
import {SavedSearch, SavedSearchType, SavedSearchVisibility} from 'sentry/types';
-import {useMutation, UseMutationOptions, useQueryClient} from 'sentry/utils/queryClient';
+import {
+ setApiQueryData,
+ useMutation,
+ UseMutationOptions,
+ useQueryClient,
+} from 'sentry/utils/queryClient';
import RequestError from 'sentry/utils/requestError/requestError';
import useApi from 'sentry/utils/useApi';
import {makeFetchSavedSearchesForOrgQueryKey} from 'sentry/views/issueList/queries/useFetchSavedSearchesForOrg';
@@ -37,7 +42,8 @@ export const useCreateSavedSearch = (
data,
}),
onSuccess: (savedSearch, parameters, context) => {
- queryClient.setQueryData(
+ setApiQueryData(
+ queryClient,
makeFetchSavedSearchesForOrgQueryKey({orgSlug: parameters.orgSlug}),
oldData => {
if (!Array.isArray(oldData)) {
diff --git a/static/app/views/issueList/mutations/useDeleteSavedSearch.tsx b/static/app/views/issueList/mutations/useDeleteSavedSearch.tsx
index 809048a275ef7c..19068de8c64626 100644
--- a/static/app/views/issueList/mutations/useDeleteSavedSearch.tsx
+++ b/static/app/views/issueList/mutations/useDeleteSavedSearch.tsx
@@ -1,7 +1,12 @@
import {addErrorMessage} from 'sentry/actionCreators/indicator';
import {t} from 'sentry/locale';
import {SavedSearch} from 'sentry/types';
-import {useMutation, UseMutationOptions, useQueryClient} from 'sentry/utils/queryClient';
+import {
+ setApiQueryData,
+ useMutation,
+ UseMutationOptions,
+ useQueryClient,
+} from 'sentry/utils/queryClient';
import RequestError from 'sentry/utils/requestError/requestError';
import useApi from 'sentry/utils/useApi';
import {makeFetchSavedSearchesForOrgQueryKey} from 'sentry/views/issueList/queries/useFetchSavedSearchesForOrg';
@@ -46,7 +51,8 @@ export const useDeleteSavedSearchOptimistic = (
makeFetchSavedSearchesForOrgQueryKey({orgSlug: variables.orgSlug})
);
- queryClient.setQueryData(
+ setApiQueryData(
+ queryClient,
makeFetchSavedSearchesForOrgQueryKey({orgSlug: variables.orgSlug}),
oldData => {
if (!Array.isArray(oldData)) {
@@ -65,7 +71,8 @@ export const useDeleteSavedSearchOptimistic = (
addErrorMessage(t('Failed to delete saved search.'));
if (context) {
- queryClient.setQueryData(
+ setApiQueryData(
+ queryClient,
makeFetchSavedSearchesForOrgQueryKey({orgSlug: variables.orgSlug}),
context.previousSavedSearches
);
diff --git a/static/app/views/monitors/details.tsx b/static/app/views/monitors/details.tsx
index 2aa71b55720736..80d927eb193365 100644
--- a/static/app/views/monitors/details.tsx
+++ b/static/app/views/monitors/details.tsx
@@ -8,7 +8,7 @@ import LoadingIndicator from 'sentry/components/loadingIndicator';
import PageFilterBar from 'sentry/components/organizations/pageFilterBar';
import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
import {space} from 'sentry/styles/space';
-import {useApiQuery, useQueryClient} from 'sentry/utils/queryClient';
+import {setApiQueryData, useApiQuery, useQueryClient} from 'sentry/utils/queryClient';
import useOrganization from 'sentry/utils/useOrganization';
import usePageFilters from 'sentry/utils/usePageFilters';
@@ -39,7 +39,7 @@ function MonitorDetails({params, location}: Props) {
const {data: monitor} = useApiQuery<Monitor>(queryKey, {staleTime: 0});
function onUpdate(data: Monitor) {
- queryClient.setQueryData(queryKey, data);
+ setApiQueryData(queryClient, queryKey, data);
}
if (!monitor) {
diff --git a/static/app/views/monitors/edit.tsx b/static/app/views/monitors/edit.tsx
index f432802aaefe79..bc9afc3eac2e98 100644
--- a/static/app/views/monitors/edit.tsx
+++ b/static/app/views/monitors/edit.tsx
@@ -6,7 +6,7 @@ import LoadingError from 'sentry/components/loadingError';
import LoadingIndicator from 'sentry/components/loadingIndicator';
import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
import {t} from 'sentry/locale';
-import {useApiQuery, useQueryClient} from 'sentry/utils/queryClient';
+import {setApiQueryData, useApiQuery, useQueryClient} from 'sentry/utils/queryClient';
import useOrganization from 'sentry/utils/useOrganization';
import {useParams} from 'sentry/utils/useParams';
import {normalizeUrl} from 'sentry/utils/withDomainRequired';
@@ -31,7 +31,7 @@ export default function EditMonitor() {
});
function onSubmitSuccess(data: Monitor) {
- queryClient.setQueryData([queryKeyUrl], data);
+ setApiQueryData(queryClient, [queryKeyUrl], data);
browserHistory.push(
normalizeUrl(`/organizations/${organization.slug}/crons/${data.slug}/`)
);
|
108b6412488367048adc7b557af10f3cd4b016e0
|
2023-12-29 16:08:43
|
Matej Minar
|
feat(ddm): Search by name, type, unit, mri (#62415)
| false
|
Search by name, type, unit, mri (#62415)
|
feat
|
diff --git a/static/app/components/compactSelect/utils.tsx b/static/app/components/compactSelect/utils.tsx
index 71358e7eee0af7..b0551f7bfa29c8 100644
--- a/static/app/components/compactSelect/utils.tsx
+++ b/static/app/components/compactSelect/utils.tsx
@@ -106,7 +106,7 @@ export function getHiddenOptions<Value extends React.Key>(
// First, filter options using `search` value
//
const filterOption = (opt: SelectOption<Value>) =>
- String(opt.label ?? '')
+ `${opt.label ?? ''}${opt.textValue ?? ''}`
.toLowerCase()
.includes(search.toLowerCase());
diff --git a/static/app/views/ddm/queryBuilder.tsx b/static/app/views/ddm/queryBuilder.tsx
index 1bc2810ccf2e89..e7f1f78c2e672c 100644
--- a/static/app/views/ddm/queryBuilder.tsx
+++ b/static/app/views/ddm/queryBuilder.tsx
@@ -121,6 +121,8 @@ export const QueryBuilder = memo(function QueryBuilder({
triggerProps={{prefix: t('Metric'), size: 'sm'}}
options={displayedMetrics.map(metric => ({
label: mriMode ? metric.mri : formatMRI(metric.mri),
+ // enable search by mri, name, unit (millisecond), type (c:), and readable type (counter)
+ textValue: `${metric.mri}${getReadableMetricType(metric.type)}`,
value: metric.mri,
trailingItems: mriMode
? undefined
|
b0fe5a64618cb85bd8ebae22dd0f46c24fb603df
|
2022-01-05 02:37:39
|
Shruthi
|
feat(widget-library): Default to custom widget tab (#30888)
| false
|
Default to custom widget tab (#30888)
|
feat
|
diff --git a/static/app/components/modals/dashboardWidgetLibraryModal/tabsButtonBar.tsx b/static/app/components/modals/dashboardWidgetLibraryModal/tabsButtonBar.tsx
index 8d236903e4e108..3ba56f3720ad15 100644
--- a/static/app/components/modals/dashboardWidgetLibraryModal/tabsButtonBar.tsx
+++ b/static/app/components/modals/dashboardWidgetLibraryModal/tabsButtonBar.tsx
@@ -5,6 +5,7 @@ import {
openAddDashboardWidgetModal,
openDashboardWidgetLibraryModal,
} from 'sentry/actionCreators/modal';
+import FeatureBadge from 'sentry/components/featureBadge';
import {t} from 'sentry/locale';
import space from 'sentry/styles/space';
import {Organization} from 'sentry/types';
@@ -44,8 +45,31 @@ export function TabsButtonBar({
}: Props) {
return (
<StyledButtonBar active={activeTab}>
+ <CustomButton
+ barId={TAB.Custom}
+ onClick={() => {
+ if (activeTab === TAB.Custom) {
+ return;
+ }
+ trackAdvancedAnalyticsEvent('dashboards_views.widget_library.switch_tab', {
+ organization,
+ to: TAB.Custom,
+ });
+ openAddDashboardWidgetModal({
+ organization,
+ dashboard,
+ selectedWidgets,
+ widget: customWidget,
+ source: DashboardWidgetSource.LIBRARY,
+ onAddLibraryWidget: onAddWidget,
+ });
+ }}
+ >
+ {t('Custom Widget')}
+ </CustomButton>
<LibraryButton
barId={TAB.Library}
+ data-test-id="library-tab"
onClick={() => {
if (activeTab === TAB.Library) {
return;
@@ -66,44 +90,24 @@ export function TabsButtonBar({
}}
>
{t('Widget Library')}
+ <FeatureBadge type="beta" />
</LibraryButton>
- <CustomButton
- barId={TAB.Custom}
- onClick={() => {
- if (activeTab === TAB.Custom) {
- return;
- }
- trackAdvancedAnalyticsEvent('dashboards_views.widget_library.switch_tab', {
- organization,
- to: TAB.Custom,
- });
- openAddDashboardWidgetModal({
- organization,
- dashboard,
- selectedWidgets,
- widget: customWidget,
- source: DashboardWidgetSource.LIBRARY,
- onAddLibraryWidget: onAddWidget,
- });
- }}
- >
- {t('Custom Widget')}
- </CustomButton>
</StyledButtonBar>
);
}
const StyledButtonBar = styled(ButtonBar)`
- display: inline;
+ display: inline-flex;
margin-bottom: ${space(2)};
`;
const LibraryButton = styled(Button)`
- border-top-right-radius: 0;
- border-bottom-right-radius: 0;
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
`;
const CustomButton = styled(Button)`
- border-top-left-radius: 0;
- border-bottom-left-radius: 0;
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+ line-height: 17px;
`;
diff --git a/static/app/views/dashboardsV2/dashboard.tsx b/static/app/views/dashboardsV2/dashboard.tsx
index edec81c9f685c4..b2984d372690eb 100644
--- a/static/app/views/dashboardsV2/dashboard.tsx
+++ b/static/app/views/dashboardsV2/dashboard.tsx
@@ -15,10 +15,7 @@ import zip from 'lodash/zip';
import {validateWidget} from 'sentry/actionCreators/dashboards';
import {addErrorMessage} from 'sentry/actionCreators/indicator';
-import {
- openAddDashboardWidgetModal,
- openDashboardWidgetLibraryModal,
-} from 'sentry/actionCreators/modal';
+import {openAddDashboardWidgetModal} from 'sentry/actionCreators/modal';
import {loadOrganizationTags} from 'sentry/actionCreators/tags';
import {Client} from 'sentry/api';
import space from 'sentry/styles/space';
@@ -69,6 +66,7 @@ type Props = {
onUpdate: (widgets: Widget[]) => void;
onSetWidgetToBeUpdated: (widget: Widget) => void;
handleAddLibraryWidgets: (widgets: Widget[]) => void;
+ handleAddCustomWidget: (widget: Widget) => void;
layout: Layout[];
onLayoutChange: (layout: Layout[]) => void;
paramDashboardId?: string;
@@ -132,11 +130,11 @@ class Dashboard extends Component<Props, State> {
}
async addNewWidget() {
- const {api, organization, newWidget} = this.props;
+ const {api, organization, newWidget, handleAddCustomWidget} = this.props;
if (newWidget) {
try {
await validateWidget(api, organization.slug, newWidget);
- this.handleAddComplete(newWidget);
+ handleAddCustomWidget(newWidget);
} catch (error) {
// Don't do anything, widget isn't valid
addErrorMessage(error);
@@ -150,7 +148,13 @@ class Dashboard extends Component<Props, State> {
}
handleStartAdd = () => {
- const {organization, dashboard, selection, handleAddLibraryWidgets} = this.props;
+ const {
+ organization,
+ dashboard,
+ selection,
+ handleAddLibraryWidgets,
+ handleAddCustomWidget,
+ } = this.props;
trackAdvancedAnalyticsEvent('dashboards_views.add_widget_modal.opened', {
organization,
});
@@ -159,10 +163,13 @@ class Dashboard extends Component<Props, State> {
trackAdvancedAnalyticsEvent('dashboards_views.widget_library.opened', {
organization,
});
- openDashboardWidgetLibraryModal({
+ openAddDashboardWidgetModal({
organization,
dashboard,
- onAddWidget: (widgets: Widget[]) => handleAddLibraryWidgets(widgets),
+ selection,
+ onAddWidget: handleAddCustomWidget,
+ onAddLibraryWidget: (widgets: Widget[]) => handleAddLibraryWidgets(widgets),
+ source: DashboardWidgetSource.LIBRARY,
});
return;
}
@@ -170,7 +177,7 @@ class Dashboard extends Component<Props, State> {
organization,
dashboard,
selection,
- onAddWidget: this.handleAddComplete,
+ onAddWidget: handleAddCustomWidget,
source: DashboardWidgetSource.DASHBOARDS,
});
};
@@ -196,14 +203,6 @@ class Dashboard extends Component<Props, State> {
});
};
- handleAddComplete = (widget: Widget) => {
- let newWidget = widget;
- if (this.props.organization.features.includes('dashboard-grid-layout')) {
- newWidget = assignTempId(widget);
- }
- this.props.onUpdate([...this.props.dashboard.widgets, newWidget]);
- };
-
handleUpdateComplete = (prevWidget: Widget) => (nextWidget: Widget) => {
const nextList = [...this.props.dashboard.widgets];
const updateIndex = nextList.indexOf(prevWidget);
@@ -248,6 +247,7 @@ class Dashboard extends Component<Props, State> {
location,
paramDashboardId,
onSetWidgetToBeUpdated,
+ handleAddCustomWidget,
} = this.props;
if (organization.features.includes('metrics')) {
@@ -279,7 +279,7 @@ class Dashboard extends Component<Props, State> {
organization,
widget,
selection,
- onAddWidget: this.handleAddComplete,
+ onAddWidget: handleAddCustomWidget,
onUpdateWidget: this.handleUpdateComplete(widget),
};
openAddDashboardWidgetModal({
diff --git a/static/app/views/dashboardsV2/detail.tsx b/static/app/views/dashboardsV2/detail.tsx
index 42ed4d28ed1e62..31321a0ce99f10 100644
--- a/static/app/views/dashboardsV2/detail.tsx
+++ b/static/app/views/dashboardsV2/detail.tsx
@@ -10,7 +10,7 @@ import {
updateDashboard,
} from 'sentry/actionCreators/dashboards';
import {addSuccessMessage} from 'sentry/actionCreators/indicator';
-import {openDashboardWidgetLibraryModal} from 'sentry/actionCreators/modal';
+import {openAddDashboardWidgetModal} from 'sentry/actionCreators/modal';
import {Client} from 'sentry/api';
import Breadcrumbs from 'sentry/components/breadcrumbs';
import HookOrDefault from 'sentry/components/hookOrDefault';
@@ -34,6 +34,7 @@ import {
DashboardDetails,
DashboardListItem,
DashboardState,
+ DashboardWidgetSource,
MAX_WIDGETS,
Widget,
} from './types';
@@ -300,15 +301,25 @@ class DashboardDetail extends Component<Props, State> {
);
};
+ handleAddCustomWidget = (widget: Widget) => {
+ let newWidget = widget;
+ if (this.props.organization.features.includes('dashboard-grid-layout')) {
+ newWidget = assignTempId(widget);
+ }
+ this.onUpdateWidget([...this.props.dashboard.widgets, newWidget]);
+ };
+
onAddWidget = () => {
const {organization, dashboard} = this.props;
this.setState({
modifiedDashboard: cloneDashboard(dashboard),
});
- openDashboardWidgetLibraryModal({
+ openAddDashboardWidgetModal({
organization,
dashboard,
- onAddWidget: (widgets: Widget[]) => this.handleAddLibraryWidgets(widgets),
+ onAddWidget: (widget: Widget) => this.handleAddCustomWidget(widget),
+ onAddLibraryWidget: (widgets: Widget[]) => this.handleAddLibraryWidgets(widgets),
+ source: DashboardWidgetSource.LIBRARY,
});
};
@@ -536,6 +547,7 @@ class DashboardDetail extends Component<Props, State> {
onUpdate={this.onUpdateWidget}
onSetWidgetToBeUpdated={this.onSetWidgetToBeUpdated}
handleAddLibraryWidgets={this.handleAddLibraryWidgets}
+ handleAddCustomWidget={this.handleAddCustomWidget}
router={router}
location={location}
layout={layout}
@@ -618,6 +630,7 @@ class DashboardDetail extends Component<Props, State> {
widgetLimitReached={widgetLimitReached}
onUpdate={this.onUpdateWidget}
handleAddLibraryWidgets={this.handleAddLibraryWidgets}
+ handleAddCustomWidget={this.handleAddCustomWidget}
onSetWidgetToBeUpdated={this.onSetWidgetToBeUpdated}
router={router}
location={location}
diff --git a/tests/acceptance/test_organization_dashboards.py b/tests/acceptance/test_organization_dashboards.py
index 6ec87b64f27089..91db62be740833 100644
--- a/tests/acceptance/test_organization_dashboards.py
+++ b/tests/acceptance/test_organization_dashboards.py
@@ -89,6 +89,8 @@ def test_widget_library(self):
button = self.browser.element('[data-test-id="add-widget-library"]')
button.click()
+ self.browser.element('[data-test-id="library-tab"]').click()
+
# Edit the first widget.
self.browser.element('[data-test-id="widget-library-card-0"]').click()
self.browser.element('[data-test-id="widget-library-card-2"]').click()
diff --git a/tests/js/spec/components/modals/dashboardWidgetLibraryModal.spec.jsx b/tests/js/spec/components/modals/dashboardWidgetLibraryModal.spec.jsx
index b7a94881aa4683..f4651e48d82af5 100644
--- a/tests/js/spec/components/modals/dashboardWidgetLibraryModal.spec.jsx
+++ b/tests/js/spec/components/modals/dashboardWidgetLibraryModal.spec.jsx
@@ -65,7 +65,7 @@ describe('Modals -> DashboardWidgetLibraryModal', function () {
expect(screen.queryByText('Users Affected by Errors')).toBeInTheDocument();
expect(
- screen.getByRole('button', {name: 'Widget Library', current: true})
+ screen.getByRole('button', {name: 'Widget Library beta', current: true})
).toBeInTheDocument();
expect(
screen.getByRole('button', {name: 'Custom Widget', current: false})
diff --git a/tests/js/spec/views/dashboardsV2/dashboard.spec.tsx b/tests/js/spec/views/dashboardsV2/dashboard.spec.tsx
index 20a1151579ab06..0a70d8a46301c5 100644
--- a/tests/js/spec/views/dashboardsV2/dashboard.spec.tsx
+++ b/tests/js/spec/views/dashboardsV2/dashboard.spec.tsx
@@ -40,15 +40,16 @@ describe('Dashboards > Dashboard', () => {
});
});
it('dashboard adds new widget if component is mounted with newWidget prop', async () => {
- const mock = jest.fn();
+ const mockHandleAddCustomWidget = jest.fn();
const wrapper = mountWithTheme(
<Dashboard
paramDashboardId="1"
dashboard={mockDashboard}
organization={initialData.organization}
isEditing={false}
- onUpdate={mock}
- handleAddLibraryWidgets={mock}
+ onUpdate={() => undefined}
+ handleAddLibraryWidgets={() => undefined}
+ handleAddCustomWidget={mockHandleAddCustomWidget}
onSetWidgetToBeUpdated={() => undefined}
router={initialData.router}
location={initialData.location}
@@ -61,19 +62,20 @@ describe('Dashboards > Dashboard', () => {
);
await tick();
wrapper.update();
- expect(mock).toHaveBeenCalled();
+ expect(mockHandleAddCustomWidget).toHaveBeenCalled();
});
it('dashboard adds new widget if component updated with newWidget prop', async () => {
- const mock = jest.fn();
+ const mockHandleAddCustomWidget = jest.fn();
const wrapper = mountWithTheme(
<Dashboard
paramDashboardId="1"
dashboard={mockDashboard}
organization={initialData.organization}
isEditing={false}
- onUpdate={mock}
- handleAddLibraryWidgets={mock}
+ onUpdate={() => undefined}
+ handleAddLibraryWidgets={() => undefined}
+ handleAddCustomWidget={mockHandleAddCustomWidget}
onSetWidgetToBeUpdated={() => undefined}
router={initialData.router}
location={initialData.location}
@@ -83,11 +85,11 @@ describe('Dashboards > Dashboard', () => {
/>,
initialData.routerContext
);
- expect(mock).not.toHaveBeenCalled();
+ expect(mockHandleAddCustomWidget).not.toHaveBeenCalled();
wrapper.setProps({newWidget});
await tick();
wrapper.update();
- expect(mock).toHaveBeenCalled();
+ expect(mockHandleAddCustomWidget).toHaveBeenCalled();
});
it('displays widgets with drag handle when in edit mode', () => {
@@ -100,6 +102,7 @@ describe('Dashboards > Dashboard', () => {
onUpdate={() => undefined}
onSetWidgetToBeUpdated={() => undefined}
handleAddLibraryWidgets={() => undefined}
+ handleAddCustomWidget={() => undefined}
router={initialData.router}
location={initialData.location}
widgetLimitReached={false}
diff --git a/tests/js/spec/views/dashboardsV2/detail.spec.jsx b/tests/js/spec/views/dashboardsV2/detail.spec.jsx
index 90882f2efc5227..fdd09f59484c03 100644
--- a/tests/js/spec/views/dashboardsV2/detail.spec.jsx
+++ b/tests/js/spec/views/dashboardsV2/detail.spec.jsx
@@ -184,7 +184,6 @@ describe('Dashboards > Detail', function () {
describe('custom dashboards', function () {
let wrapper, initialData, widgets, mockVisit;
- const openLibraryModal = jest.spyOn(modals, 'openDashboardWidgetLibraryModal');
const openEditModal = jest.spyOn(modals, 'openAddDashboardWidgetModal');
beforeEach(function () {
@@ -517,7 +516,12 @@ describe('Dashboards > Detail', function () {
wrapper.find('Controls Button[data-test-id="dashboard-edit"]').simulate('click');
wrapper.update();
wrapper.find('AddButton[data-test-id="widget-add"]').simulate('click');
- expect(openLibraryModal).toHaveBeenCalledTimes(1);
+ expect(openEditModal).toHaveBeenCalledTimes(1);
+ expect(openEditModal).toHaveBeenCalledWith(
+ expect.objectContaining({
+ source: types.DashboardWidgetSource.LIBRARY,
+ })
+ );
});
it('hides add widget option', async function () {
@@ -627,7 +631,7 @@ describe('Dashboards > Detail', function () {
);
});
- it('can add library widgets', async function () {
+ it('opens add widget to custom modal', async function () {
types.MAX_WIDGETS = 10;
initialData = initializeOrg({
@@ -662,7 +666,12 @@ describe('Dashboards > Detail', function () {
.find('Controls Button[data-test-id="add-widget-library"]')
.simulate('click');
- expect(openLibraryModal).toHaveBeenCalledTimes(1);
+ expect(openEditModal).toHaveBeenCalledTimes(1);
+ expect(openEditModal).toHaveBeenCalledWith(
+ expect.objectContaining({
+ source: types.DashboardWidgetSource.LIBRARY,
+ })
+ );
});
it('disables add library widgets when max widgets reached', async function () {
diff --git a/tests/js/spec/views/dashboardsV2/gridLayout/dashboard.spec.tsx b/tests/js/spec/views/dashboardsV2/gridLayout/dashboard.spec.tsx
index 0a72de4afe4e1e..7306723506c22b 100644
--- a/tests/js/spec/views/dashboardsV2/gridLayout/dashboard.spec.tsx
+++ b/tests/js/spec/views/dashboardsV2/gridLayout/dashboard.spec.tsx
@@ -40,15 +40,16 @@ describe('Dashboards > Dashboard', () => {
});
});
it('dashboard adds new widget if component is mounted with newWidget prop', async () => {
- const mock = jest.fn();
+ const mockHandleAddCustomWidget = jest.fn();
const wrapper = mountWithTheme(
<Dashboard
paramDashboardId="1"
dashboard={mockDashboard}
organization={initialData.organization}
isEditing={false}
- onUpdate={mock}
- handleAddLibraryWidgets={mock}
+ onUpdate={() => undefined}
+ handleAddLibraryWidgets={() => undefined}
+ handleAddCustomWidget={mockHandleAddCustomWidget}
onSetWidgetToBeUpdated={() => undefined}
router={initialData.router}
location={initialData.location}
@@ -61,19 +62,20 @@ describe('Dashboards > Dashboard', () => {
);
await tick();
wrapper.update();
- expect(mock).toHaveBeenCalled();
+ expect(mockHandleAddCustomWidget).toHaveBeenCalled();
});
it('dashboard adds new widget if component updated with newWidget prop', async () => {
- const mock = jest.fn();
+ const mockHandleAddCustomWidget = jest.fn();
const wrapper = mountWithTheme(
<Dashboard
paramDashboardId="1"
dashboard={mockDashboard}
organization={initialData.organization}
isEditing={false}
- onUpdate={mock}
- handleAddLibraryWidgets={mock}
+ onUpdate={() => undefined}
+ handleAddLibraryWidgets={() => undefined}
+ handleAddCustomWidget={mockHandleAddCustomWidget}
onSetWidgetToBeUpdated={() => undefined}
router={initialData.router}
location={initialData.location}
@@ -83,10 +85,10 @@ describe('Dashboards > Dashboard', () => {
/>,
initialData.routerContext
);
- expect(mock).not.toHaveBeenCalled();
+ expect(mockHandleAddCustomWidget).not.toHaveBeenCalled();
wrapper.setProps({newWidget});
await tick();
wrapper.update();
- expect(mock).toHaveBeenCalled();
+ expect(mockHandleAddCustomWidget).toHaveBeenCalled();
});
});
diff --git a/tests/js/spec/views/dashboardsV2/gridLayout/detail.spec.jsx b/tests/js/spec/views/dashboardsV2/gridLayout/detail.spec.jsx
index 665100b5901438..8c9963074e545c 100644
--- a/tests/js/spec/views/dashboardsV2/gridLayout/detail.spec.jsx
+++ b/tests/js/spec/views/dashboardsV2/gridLayout/detail.spec.jsx
@@ -126,7 +126,6 @@ describe('Dashboards > Detail', function () {
describe('custom dashboards', function () {
let wrapper, initialData, widgets, mockVisit;
- const openLibraryModal = jest.spyOn(modals, 'openDashboardWidgetLibraryModal');
const openEditModal = jest.spyOn(modals, 'openAddDashboardWidgetModal');
beforeEach(function () {
initialData = initializeOrg({organization});
@@ -391,7 +390,12 @@ describe('Dashboards > Detail', function () {
wrapper.find('Controls Button[data-test-id="dashboard-edit"]').simulate('click');
wrapper.update();
wrapper.find('AddButton[data-test-id="widget-add"]').simulate('click');
- expect(openLibraryModal).toHaveBeenCalledTimes(1);
+ expect(openEditModal).toHaveBeenCalledTimes(1);
+ expect(openEditModal).toHaveBeenCalledWith(
+ expect.objectContaining({
+ source: types.DashboardWidgetSource.LIBRARY,
+ })
+ );
});
it('hides add widget option', async function () {
|
53c0c8f5568d982106a7994b56ba78baeaff44a9
|
2024-04-19 04:41:36
|
Evan Purkhiser
|
feat(crons): Add `unassigned` to owner filter (#69251)
| false
|
Add `unassigned` to owner filter (#69251)
|
feat
|
diff --git a/src/sentry/monitors/endpoints/organization_monitor_index.py b/src/sentry/monitors/endpoints/organization_monitor_index.py
index 8e4c615d9aee18..aca016561c80e7 100644
--- a/src/sentry/monitors/endpoints/organization_monitor_index.py
+++ b/src/sentry/monitors/endpoints/organization_monitor_index.py
@@ -203,9 +203,11 @@ def get(self, request: Request, organization: Organization) -> Response:
if owners:
owners = set(owners)
- # Remove special 'myteams' from owners, this can't be parsed as an ActorTuple
- myteams = ["myteams"] if "myteams" in owners else []
+ # Remove special values from owners, this can't be parsed as an ActorTuple
+ include_myteams = "myteams" in owners
owners.discard("myteams")
+ include_unassigned = "unassigned" in owners
+ owners.discard("unassigned")
actors = [ActorTuple.from_actor_identifier(identifier) for identifier in owners]
@@ -215,13 +217,17 @@ def get(self, request: Request, organization: Organization) -> Response:
teams = get_teams(
request,
organization,
- teams=[*team_ids, *myteams],
+ teams=[*team_ids, *(["myteams"] if include_myteams else [])],
)
team_ids = [team.id for team in teams]
- queryset = queryset.filter(
- Q(owner_user_id__in=user_ids) | Q(owner_team_id__in=team_ids)
- )
+ owner_filter = Q(owner_user_id__in=user_ids) | Q(owner_team_id__in=team_ids)
+
+ if include_unassigned:
+ unassigned_filter = Q(owner_user_id=None) & Q(owner_team_id=None)
+ queryset = queryset.filter(unassigned_filter | owner_filter)
+ else:
+ queryset = queryset.filter(owner_filter)
if query:
tokens = tokenize_query(query)
diff --git a/tests/sentry/monitors/endpoints/test_organization_monitor_index.py b/tests/sentry/monitors/endpoints/test_organization_monitor_index.py
index 8c1bc586168cbb..7a4bfba09013cc 100644
--- a/tests/sentry/monitors/endpoints/test_organization_monitor_index.py
+++ b/tests/sentry/monitors/endpoints/test_organization_monitor_index.py
@@ -216,28 +216,36 @@ def test_filter_owners(self):
team_2 = self.create_team()
self.create_team_membership(team_2, user=self.user)
- mon_1 = self._create_monitor(name="A monitor", owner_user_id=user_1.id)
- mon_2 = self._create_monitor(name="B monitor", owner_user_id=user_2.id)
- mon_3 = self._create_monitor(name="C monitor", owner_user_id=None, owner_team_id=team_1.id)
- mon_4 = self._create_monitor(name="C monitor", owner_user_id=None, owner_team_id=team_2.id)
+ mon_a = self._create_monitor(name="A monitor", owner_user_id=user_1.id)
+ mon_b = self._create_monitor(name="B monitor", owner_user_id=user_2.id)
+ mon_c = self._create_monitor(name="C monitor", owner_user_id=None, owner_team_id=team_1.id)
+ mon_d = self._create_monitor(name="D monitor", owner_user_id=None, owner_team_id=team_2.id)
+ mon_e = self._create_monitor(name="E monitor", owner_user_id=None, owner_team_id=None)
# Monitor by user
response = self.get_success_response(self.organization.slug, owner=[f"user:{user_1.id}"])
- self.check_valid_response(response, [mon_1])
+ self.check_valid_response(response, [mon_a])
# Monitors by users and teams
response = self.get_success_response(
self.organization.slug,
owner=[f"user:{user_1.id}", f"user:{user_2.id}", f"team:{team_1.id}"],
)
- self.check_valid_response(response, [mon_1, mon_2, mon_3])
+ self.check_valid_response(response, [mon_a, mon_b, mon_c])
# myteams
response = self.get_success_response(
self.organization.slug,
owner=["myteams"],
)
- self.check_valid_response(response, [mon_4])
+ self.check_valid_response(response, [mon_d])
+
+ # unassigned monitors
+ response = self.get_success_response(
+ self.organization.slug,
+ owner=["unassigned", f"user:{user_1.id}"],
+ )
+ self.check_valid_response(response, [mon_a, mon_e])
# Invalid user ID
response = self.get_success_response(
|
5a823dca281d3aac0315921514dfdd91afaede90
|
2024-09-26 05:21:37
|
Evan Purkhiser
|
feat(uptime): Assign issues to owners (#78176)
| false
|
Assign issues to owners (#78176)
|
feat
|
diff --git a/src/sentry/uptime/issue_platform.py b/src/sentry/uptime/issue_platform.py
index a74e652812ee6c..f9c622305b37cc 100644
--- a/src/sentry/uptime/issue_platform.py
+++ b/src/sentry/uptime/issue_platform.py
@@ -80,6 +80,7 @@ def build_occurrence_from_result(
culprit="", # TODO: The url?
detection_time=datetime.now(timezone.utc),
level="error",
+ assignee=project_subscription.owner,
)
diff --git a/tests/sentry/uptime/consumers/test_results_consumers.py b/tests/sentry/uptime/consumers/test_results_consumers.py
index c92ce507f7d59d..1affefef3120b9 100644
--- a/tests/sentry/uptime/consumers/test_results_consumers.py
+++ b/tests/sentry/uptime/consumers/test_results_consumers.py
@@ -46,7 +46,8 @@ def setUp(self):
subscription_id=uuid.uuid4().hex, interval_seconds=300
)
self.project_subscription = self.create_project_uptime_subscription(
- uptime_subscription=self.subscription
+ uptime_subscription=self.subscription,
+ owner=self.user,
)
def send_result(self, result: CheckResult):
@@ -122,6 +123,8 @@ def test(self):
hashed_fingerprint = md5(str(self.project_subscription.id).encode("utf-8")).hexdigest()
group = Group.objects.get(grouphash__hash=hashed_fingerprint)
assert group.issue_type == UptimeDomainCheckFailure
+ assignee = group.get_assignee()
+ assert assignee and (assignee.id == self.user.id)
self.project_subscription.refresh_from_db()
assert self.project_subscription.uptime_status == UptimeStatus.FAILED
|
8bb44313ba3b8ac35e6328dcfea444f42365a080
|
2023-07-18 03:53:25
|
Scott Cooper
|
fix(vscode): Add black formatter recommendation (#53016)
| false
|
Add black formatter recommendation (#53016)
|
fix
|
diff --git a/.vscode/extensions.json b/.vscode/extensions.json
index 86145c3e760d59..689d4539d2a825 100644
--- a/.vscode/extensions.json
+++ b/.vscode/extensions.json
@@ -4,9 +4,11 @@
"recommendations": [
"esbenp.prettier-vscode",
"ms-python.python",
+ "ms-python.black-formatter",
"dbaeumer.vscode-eslint",
"lextudio.restructuredtext",
"ziyasal.vscode-open-in-github",
- "timonwong.shellcheck"
+ "timonwong.shellcheck",
+ "tyriar.sort-lines",
]
}
|
5fa4b2ac4c9616ef4fb19d37510b7952d255926f
|
2018-07-18 04:58:23
|
Evan Purkhiser
|
fix(integrations): Correctly pass onAddIntegration (#9081)
| false
|
Correctly pass onAddIntegration (#9081)
|
fix
|
diff --git a/src/sentry/static/sentry/app/views/organizationIntegrations/index.jsx b/src/sentry/static/sentry/app/views/organizationIntegrations/index.jsx
index c6d929f577fd02..6b22299e8ccfff 100644
--- a/src/sentry/static/sentry/app/views/organizationIntegrations/index.jsx
+++ b/src/sentry/static/sentry/app/views/organizationIntegrations/index.jsx
@@ -102,6 +102,12 @@ export default class OrganizationIntegrations extends AsyncComponent {
/>
));
+ const openModal = () =>
+ openIntegrationDetails({
+ provider,
+ onAddIntegration: this.mergeIntegration,
+ });
+
return (
<React.Fragment key={provider.key}>
<PanelItem align="center">
@@ -110,19 +116,11 @@ export default class OrganizationIntegrations extends AsyncComponent {
<ProviderName>{provider.name}</ProviderName>
<ProviderDetails>
<Status enabled={installed.length > 0} />
- <Link onClick={() => openIntegrationDetails({provider})}>Learn More</Link>
+ <Link onClick={openModal}>Learn More</Link>
</ProviderDetails>
</Box>
<Box>
- <Button
- icon="icon-circle-add"
- size="small"
- onClick={() =>
- openIntegrationDetails({
- provider,
- onAddIntegration: this.mergeIntegration,
- })}
- >
+ <Button icon="icon-circle-add" size="small" onClick={openModal}>
{t('Install')}
</Button>
</Box>
|
d75b4f44c144a45abf12d2fcaaa48f0d097db681
|
2020-01-24 00:03:54
|
Lyn Nagara
|
ref: Remove references to EventCommon (#16562)
| false
|
Remove references to EventCommon (#16562)
|
ref
|
diff --git a/src/sentry/integrations/pagerduty/client.py b/src/sentry/integrations/pagerduty/client.py
index 24b2f5e6811a22..e389af9af1e85b 100644
--- a/src/sentry/integrations/pagerduty/client.py
+++ b/src/sentry/integrations/pagerduty/client.py
@@ -1,7 +1,7 @@
from __future__ import absolute_import
from sentry.integrations.client import ApiClient
-from sentry.models import EventCommon
+from sentry.eventstore.models import Event
from sentry.api.serializers import serialize, ExternalEventSerializer
LEVEL_SEVERITY_MAP = {
@@ -31,7 +31,7 @@ def request(self, method, path, headers=None, data=None, params=None):
def send_trigger(self, data):
# expected payload: https://v2.developer.pagerduty.com/docs/send-an-event-events-api-v2
# for now, only construct the payload if data is an event
- if isinstance(data, EventCommon):
+ if isinstance(data, Event):
source = data.transaction or data.culprit or "<unknown>"
group = data.group
level = data.get_tag("level") or "error"
diff --git a/src/sentry/migrations/0001_initial.py b/src/sentry/migrations/0001_initial.py
index ff68f32ec35c75..63b754100bfbf3 100644
--- a/src/sentry/migrations/0001_initial.py
+++ b/src/sentry/migrations/0001_initial.py
@@ -864,7 +864,6 @@ class Migration(migrations.Migration):
'verbose_name': 'message',
'verbose_name_plural': 'messages',
},
- bases=(sentry.models.event.EventCommon, models.Model),
),
migrations.CreateModel(
name='EventAttachment',
diff --git a/src/sentry/tasks/sentry_apps.py b/src/sentry/tasks/sentry_apps.py
index 040ec422f45efe..2731ee73d0fc9a 100644
--- a/src/sentry/tasks/sentry_apps.py
+++ b/src/sentry/tasks/sentry_apps.py
@@ -15,7 +15,6 @@
from sentry.api.serializers import serialize, AppPlatformEvent
from sentry.models import (
SentryAppInstallation,
- EventCommon,
Group,
Project,
Organization,
@@ -112,7 +111,7 @@ def _process_resource_change(action, sender, instance_id, retryer=None, *args, *
model = TYPES[sender]
# The Event model has different hooks for the different event types. The sender
# determines which type eg. Error and therefore the 'name' eg. error
- if issubclass(model, EventCommon):
+ if issubclass(model, Event):
if not kwargs.get("instance"):
extra = {"sender": sender, "action": action, "event_id": instance_id}
logger.info("process_resource_change.event_missing_event", extra=extra)
@@ -131,7 +130,7 @@ def _process_resource_change(action, sender, instance_id, retryer=None, *args, *
# We may run into a race condition where this task executes before the
# transaction that creates the Group has committed.
try:
- if issubclass(model, EventCommon):
+ if issubclass(model, Event):
# XXX:(Meredith): Passing through the entire event was an intentional choice
# to avoid having to query NodeStore again for data we had previously in
# post_process. While this is not ideal, changing this will most likely involve
@@ -151,7 +150,7 @@ def _process_resource_change(action, sender, instance_id, retryer=None, *args, *
org = None
- if isinstance(instance, Group) or issubclass(model, EventCommon):
+ if isinstance(instance, Group) or isinstance(instance, Event):
org = Organization.objects.get_from_cache(
id=Project.objects.get_from_cache(id=instance.project_id).organization_id
)
@@ -163,7 +162,7 @@ def _process_resource_change(action, sender, instance_id, retryer=None, *args, *
for installation in installations:
data = {}
- if issubclass(model, EventCommon):
+ if isinstance(instance, Event):
data[name] = _webhook_event_data(instance, instance.group_id, instance.project_id)
send_webhooks(installation, event, data=data)
else:
|
8ef3656c6d43bc79dad8a175bdcf9f70f4bdc70e
|
2018-05-04 23:33:14
|
Evan Purkhiser
|
feat(integrations): Customize integration noun (#8307)
| false
|
Customize integration noun (#8307)
|
feat
|
diff --git a/src/sentry/integrations/base.py b/src/sentry/integrations/base.py
index 81aabe7e36c7c7..cfc0489b83f6cf 100644
--- a/src/sentry/integrations/base.py
+++ b/src/sentry/integrations/base.py
@@ -11,6 +11,7 @@
IntegrationMetadata = namedtuple('IntegrationMetadata', [
'description', # A markdown description of the integration
'author', # The integration author's name
+ 'noun', # The noun used to identify the integration
'issue_url', # URL where issues should be opened
'source_url', # URL to view the source
'aspects', # A map of integration specific 'aspects' to the aspect config.
diff --git a/src/sentry/integrations/example/integration.py b/src/sentry/integrations/example/integration.py
index 9deb1a50adf852..422d80f4770710 100644
--- a/src/sentry/integrations/example/integration.py
+++ b/src/sentry/integrations/example/integration.py
@@ -31,6 +31,7 @@ def dispatch(self, request, pipeline):
metadata = IntegrationMetadata(
description=DESCRIPTION.strip(),
author='The Sentry Team',
+ noun='example',
issue_url='https://github.com/getsentry/sentry/issues/new',
source_url='https://github.com/getsentry/sentry',
aspects={},
diff --git a/src/sentry/integrations/jira/integration.py b/src/sentry/integrations/jira/integration.py
index adbcd672414f31..b62a2f2546c9fe 100644
--- a/src/sentry/integrations/jira/integration.py
+++ b/src/sentry/integrations/jira/integration.py
@@ -1,5 +1,6 @@
from __future__ import absolute_import
+from django.utils.translation import ugettext_lazy as _
from sentry.integrations import Integration, IntegrationMetadata
@@ -13,6 +14,7 @@
metadata = IntegrationMetadata(
description='Sync Sentry and JIRA issues.',
author='The Sentry Team',
+ noun=_('Instance'),
issue_url='https://github.com/getsentry/sentry/issues/new?title=JIRA%20Integration:%20&labels=Component%3A%20Integrations',
source_url='https://github.com/getsentry/sentry/tree/master/src/sentry/integrations/jira',
aspects={
diff --git a/src/sentry/integrations/slack/integration.py b/src/sentry/integrations/slack/integration.py
index 215ec9450600c8..c456aed04baf50 100644
--- a/src/sentry/integrations/slack/integration.py
+++ b/src/sentry/integrations/slack/integration.py
@@ -1,5 +1,7 @@
from __future__ import absolute_import
+from django.utils.translation import ugettext_lazy as _
+
from sentry import http
from sentry.integrations import Integration, IntegrationMetadata
from sentry.pipeline import NestedPipelineView
@@ -24,6 +26,7 @@
metadata = IntegrationMetadata(
description=DESCRIPTION.strip(),
author='The Sentry Team',
+ noun=_('Workspace'),
issue_url='https://github.com/getsentry/sentry/issues/new?title=Slack%20Integration:%20&labels=Component%3A%20Integrations',
source_url='https://github.com/getsentry/sentry/tree/master/src/sentry/integrations/slack',
aspects={
diff --git a/src/sentry/static/sentry/app/views/organizationIntegrationConfig.jsx b/src/sentry/static/sentry/app/views/organizationIntegrationConfig.jsx
index 0fa07682896331..eb67eca88e3313 100644
--- a/src/sentry/static/sentry/app/views/organizationIntegrationConfig.jsx
+++ b/src/sentry/static/sentry/app/views/organizationIntegrationConfig.jsx
@@ -221,14 +221,13 @@ export default class OrganizationIntegrationConfig extends AsyncView {
const titleIcon = <PluginIcon size={28} pluginId={provider.key} />;
- // TODO(epurkhiser): Workspaces needs to get genericised into the integration
const header = (
<PanelHeader disablePadding hasButtons>
- <Box px={2}>{t('Workspaces')}</Box>
+ <Box px={2}>{provider.metadata.noun}</Box>
{provider.canAdd && (
<Box mr={1}>
<Button size="xsmall" onClick={() => this.handleAddIntegration(provider)}>
- <span className="icon icon-add" /> {t('Add Workspace')}
+ <span className="icon icon-add" /> {t('Add') + ' ' + provider.metadata.noun}
</Button>
</Box>
)}
diff --git a/tests/js/setup.js b/tests/js/setup.js
index 6bd2f0b5ed433b..424938225db6ca 100644
--- a/tests/js/setup.js
+++ b/tests/js/setup.js
@@ -472,6 +472,7 @@ window.TestStubs = {
metadata: {
description: '*markdown* formatted _description_',
author: 'Morty',
+ noun: 'Installation',
issue_url: 'http://example.com/integration_issue_url',
source_url: 'http://example.com/integration_source_url',
aspects: {
diff --git a/tests/js/spec/views/__snapshots__/organizationIntegrationConfig.spec.jsx.snap b/tests/js/spec/views/__snapshots__/organizationIntegrationConfig.spec.jsx.snap
index f9f2febc20fa2a..7cbdc166b69472 100644
--- a/tests/js/spec/views/__snapshots__/organizationIntegrationConfig.spec.jsx.snap
+++ b/tests/js/spec/views/__snapshots__/organizationIntegrationConfig.spec.jsx.snap
@@ -123,7 +123,7 @@ exports[`OrganizationIntegrationConfig render() with one integration renders 1`]
className="css-17pfgr6"
is={null}
>
- Workspaces
+ Installation
</div>
</Base>
</Box>
@@ -189,7 +189,7 @@ exports[`OrganizationIntegrationConfig render() with one integration renders 1`]
className="icon icon-add"
/>
- Add Workspace
+ Add Installation
</div>
</Base>
</Flex>
|
d60486610efac0168a078309e5141f1b0e7a5f33
|
2023-08-02 22:43:14
|
Cathy Teng
|
chore(github-comments): clean up feature flag (#53712)
| false
|
clean up feature flag (#53712)
|
chore
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index 3e9f4abfb8f437..6858eb505d0df9 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -1671,8 +1671,6 @@ def SOCIAL_AUTH_DEFAULT_USERNAME() -> str:
"organizations:org-auth-tokens": False,
# Enable detecting SDK crashes during event processing
"organizations:sdk-crash-detection": False,
- # Enables commenting on PRs from the Sentry comment bot.
- "organizations:pr-comment-bot": True,
# Enables slack channel lookup via schedule message
"organizations:slack-use-new-lookup": False,
# Enable functionality for recap server polling.
diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py
index 2f0073b9527112..13b6ed1dfcfba5 100644
--- a/src/sentry/features/__init__.py
+++ b/src/sentry/features/__init__.py
@@ -258,7 +258,6 @@
default_manager.add("organizations:codecov-commit-sha-from-git-blame", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:ds-sliding-window", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
default_manager.add("organizations:ds-sliding-window-org", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
-default_manager.add("organizations:pr-comment-bot", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:ds-org-recalibration", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
default_manager.add("organizations:slack-use-new-lookup", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:slack-disable-on-broken", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
diff --git a/src/sentry/tasks/commit_context.py b/src/sentry/tasks/commit_context.py
index c74a853f961ac4..c5a40b6c063277 100644
--- a/src/sentry/tasks/commit_context.py
+++ b/src/sentry/tasks/commit_context.py
@@ -6,7 +6,7 @@
from django.utils import timezone
from sentry_sdk import set_tag
-from sentry import analytics, features
+from sentry import analytics
from sentry.api.serializers.models.release import get_users_for_authors
from sentry.integrations.base import IntegrationInstallation
from sentry.integrations.utils.commit_context import find_commit_context_for_event
@@ -361,9 +361,7 @@ def process_commit_context(
}, # Updates date of an existing owner, since we just matched them with this new event
)
- if features.has(
- "organizations:pr-comment-bot", project.organization
- ) and OrganizationOption.objects.get_value(
+ if OrganizationOption.objects.get_value(
organization=project.organization,
key="sentry:github_pr_bot",
default=True,
diff --git a/src/sentry/tasks/integrations/github/pr_comment.py b/src/sentry/tasks/integrations/github/pr_comment.py
index 2e8069885bcb98..a27f483fb3d50d 100644
--- a/src/sentry/tasks/integrations/github/pr_comment.py
+++ b/src/sentry/tasks/integrations/github/pr_comment.py
@@ -11,7 +11,6 @@
from snuba_sdk import Column, Condition, Direction, Entity, Function, Op, OrderBy, Query
from snuba_sdk import Request as SnubaRequest
-from sentry import features
from sentry.integrations.github.client import GitHubAppsClient
from sentry.models import Group, GroupOwnerType, Project
from sentry.models.options.organization_option import OrganizationOption
@@ -187,13 +186,10 @@ def github_comment_workflow(pullrequest_id: int, project_id: int):
metrics.incr(METRICS_BASE.format(key="error"), tags={"type": "missing_org"})
return
- if not (
- features.has("organizations:pr-comment-bot", organization)
- and OrganizationOption.objects.get_value(
- organization=organization,
- key="sentry:github_pr_bot",
- default=True,
- )
+ if not OrganizationOption.objects.get_value(
+ organization=organization,
+ key="sentry:github_pr_bot",
+ default=True,
):
logger.error("github.pr_comment.option_missing", extra={"organization_id": org_id})
return
diff --git a/tests/sentry/api/serializers/test_organization.py b/tests/sentry/api/serializers/test_organization.py
index f81b334b42215d..17f55978c48a74 100644
--- a/tests/sentry/api/serializers/test_organization.py
+++ b/tests/sentry/api/serializers/test_organization.py
@@ -87,7 +87,6 @@ def test_simple(self):
"symbol-sources",
"team-insights",
"team-roles",
- "pr-comment-bot",
"performance-issues-search",
"transaction-name-normalize",
"transaction-name-mark-scrubbed-as-sanitized",
diff --git a/tests/sentry/tasks/integrations/github/test_pr_comment.py b/tests/sentry/tasks/integrations/github/test_pr_comment.py
index 34a13e2066d5e4..d8fc77c031624f 100644
--- a/tests/sentry/tasks/integrations/github/test_pr_comment.py
+++ b/tests/sentry/tasks/integrations/github/test_pr_comment.py
@@ -25,7 +25,6 @@
pr_to_issue_query,
)
from sentry.testutils.cases import IntegrationTestCase, SnubaTestCase, TestCase
-from sentry.testutils.helpers import with_feature
from sentry.testutils.helpers.datetime import before_now, iso_format
from sentry.testutils.silo import region_silo_test
from sentry.utils.cache import cache
@@ -337,7 +336,6 @@ def setUp(self):
@patch("sentry.tasks.integrations.github.pr_comment.get_top_5_issues_by_count")
@patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@patch("sentry.tasks.integrations.github.pr_comment.metrics")
- @with_feature("organizations:pr-comment-bot")
@responses.activate
def test_comment_workflow(self, mock_metrics, get_jwt, mock_issues):
groups = [g.id for g in Group.objects.all()]
@@ -370,7 +368,6 @@ def test_comment_workflow(self, mock_metrics, get_jwt, mock_issues):
@patch("sentry.tasks.integrations.github.pr_comment.get_top_5_issues_by_count")
@patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@patch("sentry.tasks.integrations.github.pr_comment.metrics")
- @with_feature("organizations:pr-comment-bot")
@responses.activate
@freeze_time(datetime(2023, 6, 8, 0, 0, 0, tzinfo=timezone.utc))
def test_comment_workflow_updates_comment(self, mock_metrics, get_jwt, mock_issues):
@@ -420,7 +417,6 @@ def test_comment_workflow_updates_comment(self, mock_metrics, get_jwt, mock_issu
@patch("sentry.tasks.integrations.github.pr_comment.get_top_5_issues_by_count")
@patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@patch("sentry.tasks.integrations.github.pr_comment.metrics")
- @with_feature("organizations:pr-comment-bot")
@responses.activate
def test_comment_workflow_api_error(self, mock_metrics, get_jwt, mock_issues):
cache.set(self.cache_key, True, timedelta(minutes=5).total_seconds())
@@ -448,7 +444,6 @@ def test_comment_workflow_api_error(self, mock_metrics, get_jwt, mock_issues):
@patch("sentry.tasks.integrations.github.pr_comment.get_top_5_issues_by_count")
@patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@patch("sentry.tasks.integrations.github.pr_comment.metrics")
- @with_feature("organizations:pr-comment-bot")
@responses.activate
def test_comment_workflow_api_error_locked_issue(self, mock_metrics, get_jwt, mock_issues):
cache.set(self.cache_key, True, timedelta(minutes=5).total_seconds())
@@ -480,7 +475,6 @@ def test_comment_workflow_api_error_locked_issue(self, mock_metrics, get_jwt, mo
@patch("sentry.tasks.integrations.github.pr_comment.get_top_5_issues_by_count")
@patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@patch("sentry.tasks.integrations.github.pr_comment.metrics")
- @with_feature("organizations:pr-comment-bot")
@responses.activate
def test_comment_workflow_api_error_rate_limited(self, mock_metrics, get_jwt, mock_issues):
cache.set(self.cache_key, True, timedelta(minutes=5).total_seconds())
@@ -526,7 +520,6 @@ def test_comment_workflow_missing_org(self, mock_metrics, mock_issues, mock_issu
"github_pr_comment.error", tags={"type": "missing_org"}
)
- @with_feature("organizations:pr-comment-bot")
@patch("sentry.tasks.integrations.github.pr_comment.get_top_5_issues_by_count")
def test_comment_workflow_missing_org_option(self, mock_issues):
OrganizationOption.objects.set_value(
@@ -539,7 +532,6 @@ def test_comment_workflow_missing_org_option(self, mock_issues):
@patch("sentry.tasks.integrations.github.pr_comment.get_top_5_issues_by_count")
@patch("sentry.models.Project.objects.get_from_cache")
@patch("sentry.tasks.integrations.github.pr_comment.metrics")
- @with_feature("organizations:pr-comment-bot")
def test_comment_workflow_missing_project(self, mock_metrics, mock_project, mock_issues):
# Project.DoesNotExist should trigger the cache to release the key
cache.set(self.cache_key, True, timedelta(minutes=5).total_seconds())
@@ -560,7 +552,6 @@ def test_comment_workflow_missing_project(self, mock_metrics, mock_project, mock
@patch("sentry.models.Repository.objects")
@patch("sentry.tasks.integrations.github.pr_comment.format_comment")
@patch("sentry.tasks.integrations.github.pr_comment.metrics")
- @with_feature("organizations:pr-comment-bot")
def test_comment_workflow_missing_repo(
self, mock_metrics, mock_format_comment, mock_repository, mock_issues
):
@@ -586,7 +577,6 @@ def test_comment_workflow_missing_repo(
)
@patch("sentry.tasks.integrations.github.pr_comment.format_comment")
@patch("sentry.tasks.integrations.github.pr_comment.metrics")
- @with_feature("organizations:pr-comment-bot")
def test_comment_workflow_missing_integration(
self, mock_metrics, mock_format_comment, mock_issues
):
diff --git a/tests/sentry/tasks/test_commit_context.py b/tests/sentry/tasks/test_commit_context.py
index 12311fa20d0f91..641633127c3b5a 100644
--- a/tests/sentry/tasks/test_commit_context.py
+++ b/tests/sentry/tasks/test_commit_context.py
@@ -16,7 +16,6 @@
from sentry.snuba.sessions_v2 import isoformat_z
from sentry.tasks.commit_context import process_commit_context
from sentry.testutils.cases import IntegrationTestCase, TestCase
-from sentry.testutils.helpers import with_feature
from sentry.testutils.helpers.datetime import before_now, iso_format
from sentry.testutils.silo import region_silo_test
from sentry.utils.committers import get_frame_paths
@@ -476,7 +475,6 @@ def add_responses(self):
json=[{"merge_commit_sha": self.pull_request.merge_commit_sha}],
)
- @with_feature("organizations:pr-comment-bot")
def test_gh_comment_not_github(self, mock_comment_workflow):
"""Non github repos shouldn't be commented on"""
self.repo.provider = "integrations:gitlab"
@@ -492,20 +490,6 @@ def test_gh_comment_not_github(self, mock_comment_workflow):
)
assert not mock_comment_workflow.called
- def test_gh_comment_feature_flag(self, mock_comment_workflow):
- """No comments on org with feature flag disabled"""
- with self.tasks():
- event_frames = get_frame_paths(self.event)
- process_commit_context(
- event_id=self.event.event_id,
- event_platform=self.event.platform,
- event_frames=event_frames,
- group_id=self.event.group_id,
- project_id=self.event.project_id,
- )
- assert not mock_comment_workflow.called
-
- @with_feature("organizations:pr-comment-bot")
def test_gh_comment_org_option(self, mock_comment_workflow):
"""No comments on org with organization option disabled"""
OrganizationOption.objects.set_value(
@@ -523,7 +507,6 @@ def test_gh_comment_org_option(self, mock_comment_workflow):
)
assert not mock_comment_workflow.called
- @with_feature("organizations:pr-comment-bot")
@patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@responses.activate
def test_gh_comment_no_pr_from_api(self, get_jwt, mock_comment_workflow):
@@ -553,7 +536,6 @@ def test_gh_comment_no_pr_from_api(self, get_jwt, mock_comment_workflow):
)
assert not mock_comment_workflow.called
- @with_feature("organizations:pr-comment-bot")
@patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@patch("sentry_sdk.capture_exception")
@responses.activate
@@ -584,7 +566,6 @@ def test_gh_comment_api_error(self, mock_capture_exception, get_jwt, mock_commen
assert mock_capture_exception.called
assert not mock_comment_workflow.called
- @with_feature("organizations:pr-comment-bot")
@patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@responses.activate
def test_gh_comment_commit_not_in_default_branch(self, get_jwt, mock_comment_workflow):
@@ -613,7 +594,6 @@ def test_gh_comment_commit_not_in_default_branch(self, get_jwt, mock_comment_wor
)
assert not mock_comment_workflow.called
- @with_feature("organizations:pr-comment-bot")
@patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@responses.activate
def test_gh_comment_no_pr_from_query(self, get_jwt, mock_comment_workflow):
@@ -633,7 +613,6 @@ def test_gh_comment_no_pr_from_query(self, get_jwt, mock_comment_workflow):
)
assert not mock_comment_workflow.called
- @with_feature("organizations:pr-comment-bot")
@patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@responses.activate
def test_gh_comment_pr_too_old(self, get_jwt, mock_comment_workflow):
@@ -655,7 +634,6 @@ def test_gh_comment_pr_too_old(self, get_jwt, mock_comment_workflow):
assert not mock_comment_workflow.called
assert len(PullRequestCommit.objects.all()) == 0
- @with_feature("organizations:pr-comment-bot")
@patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@responses.activate
def test_gh_comment_repeat_issue(self, get_jwt, mock_comment_workflow):
@@ -677,7 +655,6 @@ def test_gh_comment_repeat_issue(self, get_jwt, mock_comment_workflow):
assert not mock_comment_workflow.called
assert len(PullRequestCommit.objects.all()) == 0
- @with_feature("organizations:pr-comment-bot")
@patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@responses.activate
def test_gh_comment_create_queued(self, get_jwt, mock_comment_workflow):
@@ -701,7 +678,6 @@ def test_gh_comment_create_queued(self, get_jwt, mock_comment_workflow):
assert len(pr_commits) == 1
assert pr_commits[0].commit == self.commit
- @with_feature("organizations:pr-comment-bot")
@patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@responses.activate
def test_gh_comment_create_queued_existing_pr_commit(self, get_jwt, mock_comment_workflow):
@@ -728,7 +704,6 @@ def test_gh_comment_create_queued_existing_pr_commit(self, get_jwt, mock_comment
assert len(pr_commits) == 1
assert pr_commits[0] == pr_commit
- @with_feature("organizations:pr-comment-bot")
@patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@responses.activate
def test_gh_comment_update_queue(self, get_jwt, mock_comment_workflow):
@@ -752,7 +727,6 @@ def test_gh_comment_update_queue(self, get_jwt, mock_comment_workflow):
assert len(pr_commits) == 1
assert pr_commits[0].commit == self.commit
- @with_feature("organizations:pr-comment-bot")
def test_gh_comment_no_repo(self, mock_comment_workflow):
"""No comments on suspect commit if no repo row exists"""
self.repo.delete()
@@ -768,7 +742,6 @@ def test_gh_comment_no_repo(self, mock_comment_workflow):
assert not mock_comment_workflow.called
assert len(PullRequestCommit.objects.all()) == 0
- @with_feature("organizations:pr-comment-bot")
@patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@responses.activate
def test_gh_comment_debounces(self, get_jwt, mock_comment_workflow):
|
7faff55a8b71c7d341fc27433a861c80ec4646c5
|
2022-04-06 21:25:35
|
edwardgou-sentry
|
feat(dashboards): Widget Viewer reuse series results from widget card on first render (#33252)
| false
|
Widget Viewer reuse series results from widget card on first render (#33252)
|
feat
|
diff --git a/static/app/components/modals/widgetViewerModal.tsx b/static/app/components/modals/widgetViewerModal.tsx
index 43c7d09647d81a..630f8044f25e85 100644
--- a/static/app/components/modals/widgetViewerModal.tsx
+++ b/static/app/components/modals/widgetViewerModal.tsx
@@ -29,9 +29,11 @@ import Tooltip from 'sentry/components/tooltip';
import {t, tct} from 'sentry/locale';
import space from 'sentry/styles/space';
import {Organization, PageFilters, SelectValue} from 'sentry/types';
+import {Series} from 'sentry/types/echarts';
import {defined} from 'sentry/utils';
import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
import {getUtcDateString} from 'sentry/utils/dates';
+import {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
import EventView from 'sentry/utils/discover/eventView';
import {getAggregateAlias, isAggregateField} from 'sentry/utils/discover/fields';
import parseLinkHeader from 'sentry/utils/parseLinkHeader';
@@ -45,6 +47,7 @@ import {
getWidgetDiscoverUrl,
getWidgetIssueUrl,
} from 'sentry/views/dashboardsV2/utils';
+import WidgetCardChart from 'sentry/views/dashboardsV2/widgetCard/chart';
import IssueWidgetQueries from 'sentry/views/dashboardsV2/widgetCard/issueWidgetQueries';
import {WidgetCardChartContainer} from 'sentry/views/dashboardsV2/widgetCard/widgetCardChartContainer';
import WidgetQueries from 'sentry/views/dashboardsV2/widgetCard/widgetQueries';
@@ -61,6 +64,8 @@ export type WidgetViewerModalOptions = {
organization: Organization;
widget: Widget;
onEdit?: () => void;
+ seriesData?: Series[];
+ tableData?: TableDataWithTitle[];
};
type Props = ModalRenderProps &
@@ -94,6 +99,18 @@ const MemoizedWidgetCardChartContainer = React.memo(
}
);
+const MemoizedWidgetCardChart = React.memo(WidgetCardChart, (prevProps, props) => {
+ return (
+ props.selection === prevProps.selection &&
+ props.location.query[WidgetViewerQueryField.QUERY] ===
+ prevProps.location.query[WidgetViewerQueryField.QUERY] &&
+ props.location.query[WidgetViewerQueryField.SORT] ===
+ prevProps.location.query[WidgetViewerQueryField.SORT] &&
+ props.location.query[WidgetViewerQueryField.WIDTH] ===
+ prevProps.location.query[WidgetViewerQueryField.WIDTH]
+ );
+});
+
async function fetchDiscoverTotal(
api: Client,
organization: Organization,
@@ -131,6 +148,8 @@ function WidgetViewerModal(props: Props) {
router,
routes,
params,
+ seriesData,
+ tableData,
} = props;
// Get widget zoom from location
// We use the start and end query params for just the initial state
@@ -144,6 +163,9 @@ function WidgetViewerModal(props: Props) {
datetime: {start, end, period: null, utc: null},
}
: selection;
+
+ const [chartUnmodified, setChartUnmodified] = React.useState<boolean>(true);
+
const [modalSelection, setModalSelection] =
React.useState<PageFilters>(locationPageFilter);
@@ -313,6 +335,56 @@ function WidgetViewerModal(props: Props) {
getDiscoverTotals();
}, [selectedQueryIndex]);
+ function onLegendSelectChanged({selected}: {selected: Record<string, boolean>}) {
+ setDisabledLegends(selected);
+ router.replace({
+ pathname: location.pathname,
+ query: {
+ ...location.query,
+ [WidgetViewerQueryField.LEGEND]: Object.keys(selected).filter(
+ key => !selected[key]
+ ),
+ },
+ });
+ trackAdvancedAnalyticsEvent('dashboards_views.widget_viewer.toggle_legend', {
+ organization,
+ widget_type: widget.widgetType ?? WidgetType.DISCOVER,
+ display_type: widget.displayType,
+ });
+ }
+
+ function onZoom(_evt, chart) {
+ // @ts-ignore getModel() is private but we need this to retrieve datetime values of zoomed in region
+ const model = chart.getModel();
+ const {startValue, endValue} = model._payload.batch[0];
+ const newStart = getUtcDateString(moment.utc(startValue));
+ const newEnd = getUtcDateString(moment.utc(endValue));
+ setModalSelection({
+ ...modalSelection,
+ datetime: {
+ ...modalSelection.datetime,
+ start: newStart,
+ end: newEnd,
+ period: null,
+ },
+ });
+ router.push({
+ pathname: location.pathname,
+ query: {
+ ...location.query,
+ [WidgetViewerQueryField.START]: newStart,
+ [WidgetViewerQueryField.END]: newEnd,
+ },
+ });
+ trackAdvancedAnalyticsEvent('dashboards_views.widget_viewer.zoom', {
+ organization,
+ widget_type: widget.widgetType ?? WidgetType.DISCOVER,
+ display_type: widget.displayType,
+ });
+ }
+
+ const shouldUseDataFromProps = (!!seriesData || !!tableData) && chartUnmodified;
+
function renderWidgetViewer() {
return (
<React.Fragment>
@@ -322,68 +394,70 @@ function WidgetViewerModal(props: Props) {
widget.displayType !== DisplayType.BIG_NUMBER ? HALF_CONTAINER_HEIGHT : null
}
>
- <MemoizedWidgetCardChartContainer
- location={location}
- router={router}
- routes={routes}
- params={params}
- api={api}
- organization={organization}
- selection={modalSelection}
- // Top N charts rely on the orderby of the table
- widget={primaryWidget}
- onZoom={(_evt, chart) => {
- // @ts-ignore getModel() is private but we need this to retrieve datetime values of zoomed in region
- const model = chart.getModel();
- const {startValue, endValue} = model._payload.batch[0];
- const newStart = getUtcDateString(moment.utc(startValue));
- const newEnd = getUtcDateString(moment.utc(endValue));
- setModalSelection({
- ...modalSelection,
- datetime: {
- ...modalSelection.datetime,
- start: newStart,
- end: newEnd,
- period: null,
- },
- });
- router.push({
- pathname: location.pathname,
- query: {
- ...location.query,
- [WidgetViewerQueryField.START]: newStart,
- [WidgetViewerQueryField.END]: newEnd,
- },
- });
- trackAdvancedAnalyticsEvent('dashboards_views.widget_viewer.zoom', {
- organization,
- widget_type: widget.widgetType ?? WidgetType.DISCOVER,
- display_type: widget.displayType,
- });
- }}
- onLegendSelectChanged={({selected}) => {
- setDisabledLegends(selected);
- router.replace({
- pathname: location.pathname,
- query: {
- ...location.query,
- [WidgetViewerQueryField.LEGEND]: Object.keys(selected).filter(
- key => !selected[key]
- ),
- },
- });
- trackAdvancedAnalyticsEvent(
- 'dashboards_views.widget_viewer.toggle_legend',
- {
+ {shouldUseDataFromProps ? (
+ <MemoizedWidgetCardChart
+ timeseriesResults={seriesData}
+ tableResults={tableData}
+ errorMessage={undefined}
+ loading={false}
+ location={location}
+ widget={widget}
+ selection={selection}
+ router={router}
+ organization={organization}
+ onZoom={(_evt, chart) => {
+ onZoom(_evt, chart);
+ setChartUnmodified(false);
+ }}
+ onLegendSelectChanged={onLegendSelectChanged}
+ legendOptions={{selected: disabledLegends}}
+ expandNumbers
+ />
+ ) : (
+ <MemoizedWidgetCardChartContainer
+ location={location}
+ router={router}
+ routes={routes}
+ params={params}
+ api={api}
+ organization={organization}
+ selection={modalSelection}
+ // Top N charts rely on the orderby of the table
+ widget={primaryWidget}
+ onZoom={(_evt, chart) => {
+ // @ts-ignore getModel() is private but we need this to retrieve datetime values of zoomed in region
+ const model = chart.getModel();
+ const {startValue, endValue} = model._payload.batch[0];
+ const newStart = getUtcDateString(moment.utc(startValue));
+ const newEnd = getUtcDateString(moment.utc(endValue));
+ setModalSelection({
+ ...modalSelection,
+ datetime: {
+ ...modalSelection.datetime,
+ start: newStart,
+ end: newEnd,
+ period: null,
+ },
+ });
+ router.push({
+ pathname: location.pathname,
+ query: {
+ ...location.query,
+ [WidgetViewerQueryField.START]: newStart,
+ [WidgetViewerQueryField.END]: newEnd,
+ },
+ });
+ trackAdvancedAnalyticsEvent('dashboards_views.widget_viewer.zoom', {
organization,
widget_type: widget.widgetType ?? WidgetType.DISCOVER,
display_type: widget.displayType,
- }
- );
- }}
- legendOptions={{selected: disabledLegends}}
- expandNumbers
- />
+ });
+ }}
+ onLegendSelectChanged={onLegendSelectChanged}
+ legendOptions={{selected: disabledLegends}}
+ expandNumbers
+ />
+ )}
</Container>
)}
{widget.queries.length > 1 && (
@@ -505,14 +579,18 @@ function WidgetViewerModal(props: Props) {
columnSortBy={columnSortBy}
grid={{
renderHeadCell: renderIssueGridHeaderCell({
- ...props,
+ location,
+ organization,
+ selection,
widget: tableWidget,
}) as (
column: GridColumnOrder,
columnIndex: number
) => React.ReactNode,
renderBodyCell: renderGridBodyCell({
- ...props,
+ location,
+ organization,
+ selection,
widget: tableWidget,
}),
onResizeColumn,
@@ -587,6 +665,7 @@ function WidgetViewerModal(props: Props) {
...props,
widget: tableWidget,
tableData: tableResults?.[0],
+ onHeaderClick: () => setChartUnmodified(false),
}) as (
column: GridColumnOrder,
columnIndex: number
diff --git a/static/app/components/modals/widgetViewerModal/widgetViewerTableCell.tsx b/static/app/components/modals/widgetViewerModal/widgetViewerTableCell.tsx
index 7cdad338502f55..8af0c6a5abeab3 100644
--- a/static/app/components/modals/widgetViewerModal/widgetViewerTableCell.tsx
+++ b/static/app/components/modals/widgetViewerModal/widgetViewerTableCell.tsx
@@ -43,6 +43,7 @@ type Props = {
selection: PageFilters;
widget: Widget;
isFirstPage?: boolean;
+ onHeaderClick?: () => void;
tableData?: TableDataWithTitle;
};
@@ -82,7 +83,7 @@ export const renderIssueGridHeaderCell =
};
export const renderDiscoverGridHeaderCell =
- ({location, selection, widget, tableData, organization}: Props) =>
+ ({location, selection, widget, tableData, organization, onHeaderClick}: Props) =>
(column: TableColumn<keyof TableDataRow>, _columnIndex: number): React.ReactNode => {
const eventView = eventViewFromWidget(
widget.title,
@@ -126,6 +127,7 @@ export const renderDiscoverGridHeaderCell =
canSort={canSort}
generateSortLink={generateSortLink}
onClick={() => {
+ onHeaderClick?.();
trackAdvancedAnalyticsEvent('dashboards_views.widget_viewer.sort', {
organization,
widget_type: widget.widgetType ?? WidgetType.DISCOVER,
diff --git a/static/app/views/dashboardsV2/detail.tsx b/static/app/views/dashboardsV2/detail.tsx
index abda10afdd1c4e..99775952b35e77 100644
--- a/static/app/views/dashboardsV2/detail.tsx
+++ b/static/app/views/dashboardsV2/detail.tsx
@@ -40,6 +40,10 @@ import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAna
import withApi from 'sentry/utils/withApi';
import withOrganization from 'sentry/utils/withOrganization';
+import {
+ WidgetViewerContext,
+ WidgetViewerContextProps,
+} from './widgetViewer/widgetViewerContext';
import Controls from './controls';
import Dashboard from './dashboard';
import {DEFAULT_STATS_PERIOD} from './data';
@@ -87,13 +91,16 @@ type State = {
dashboardState: DashboardState;
modifiedDashboard: DashboardDetails | null;
widgetLimitReached: boolean;
-};
+} & WidgetViewerContextProps;
class DashboardDetail extends Component<Props, State> {
state: State = {
dashboardState: this.props.initialState,
modifiedDashboard: this.updateModifiedDashboard(this.props.initialState),
widgetLimitReached: this.props.dashboard.widgets.length >= MAX_WIDGETS,
+ setData: data => {
+ this.setState(data);
+ },
};
componentDidMount() {
@@ -119,6 +126,7 @@ class DashboardDetail extends Component<Props, State> {
location,
router,
} = this.props;
+ const {seriesData, tableData} = this.state;
if (isWidgetViewerPath(location.pathname)) {
const widget =
defined(widgetId) &&
@@ -128,6 +136,8 @@ class DashboardDetail extends Component<Props, State> {
openWidgetViewerModal({
organization,
widget,
+ seriesData,
+ tableData,
onClose: () => {
// Filter out Widget Viewer Modal query params when exiting the Modal
const query = omit(location.query, Object.values(WidgetViewerQueryField));
@@ -665,7 +675,8 @@ class DashboardDetail extends Component<Props, State> {
newWidget,
onSetNewWidget,
} = this.props;
- const {modifiedDashboard, dashboardState, widgetLimitReached} = this.state;
+ const {modifiedDashboard, dashboardState, widgetLimitReached, seriesData, setData} =
+ this.state;
const {dashboardId} = params;
const hasPageFilters = organization.features.includes('selection-filters-v2');
@@ -730,21 +741,23 @@ class DashboardDetail extends Component<Props, State> {
<DatePageFilter alignDropdown="right" />
</DashboardPageFilterBar>
)}
- <Dashboard
- paramDashboardId={dashboardId}
- dashboard={modifiedDashboard ?? dashboard}
- organization={organization}
- isEditing={this.isEditing}
- widgetLimitReached={widgetLimitReached}
- onUpdate={this.onUpdateWidget}
- handleUpdateWidgetList={this.handleUpdateWidgetList}
- handleAddCustomWidget={this.handleAddCustomWidget}
- router={router}
- location={location}
- newWidget={newWidget}
- onSetNewWidget={onSetNewWidget}
- isPreview={this.isPreview}
- />
+ <WidgetViewerContext.Provider value={{seriesData, setData}}>
+ <Dashboard
+ paramDashboardId={dashboardId}
+ dashboard={modifiedDashboard ?? dashboard}
+ organization={organization}
+ isEditing={this.isEditing}
+ widgetLimitReached={widgetLimitReached}
+ onUpdate={this.onUpdateWidget}
+ handleUpdateWidgetList={this.handleUpdateWidgetList}
+ handleAddCustomWidget={this.handleAddCustomWidget}
+ router={router}
+ location={location}
+ newWidget={newWidget}
+ onSetNewWidget={onSetNewWidget}
+ isPreview={this.isPreview}
+ />
+ </WidgetViewerContext.Provider>
</Layout.Main>
</Layout.Body>
</NoProjectMessage>
diff --git a/static/app/views/dashboardsV2/widgetCard/index.tsx b/static/app/views/dashboardsV2/widgetCard/index.tsx
index 96f82263db218a..00507dbfe57ce5 100644
--- a/static/app/views/dashboardsV2/widgetCard/index.tsx
+++ b/static/app/views/dashboardsV2/widgetCard/index.tsx
@@ -17,6 +17,8 @@ import {t} from 'sentry/locale';
import overflowEllipsis from 'sentry/styles/overflowEllipsis';
import space from 'sentry/styles/space';
import {Organization, PageFilters} from 'sentry/types';
+import {Series} from 'sentry/types/echarts';
+import {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
import withApi from 'sentry/utils/withApi';
import withOrganization from 'sentry/utils/withOrganization';
import withPageFilters from 'sentry/utils/withPageFilters';
@@ -55,7 +57,10 @@ type Props = WithRouterProps & {
windowWidth?: number;
};
-class WidgetCard extends React.Component<Props> {
+type State = {seriesData?: Series[]; tableData?: TableDataWithTitle[]};
+
+class WidgetCard extends React.Component<Props, State> {
+ state: State = {};
renderToolbar() {
const {
onEdit,
@@ -131,6 +136,8 @@ class WidgetCard extends React.Component<Props> {
index,
} = this.props;
+ const {seriesData, tableData} = this.state;
+
if (isEditing) {
return null;
}
@@ -150,10 +157,22 @@ class WidgetCard extends React.Component<Props> {
router={router}
location={location}
index={index}
+ seriesData={seriesData}
+ tableData={tableData}
/>
);
}
+ setData = ({
+ tableResults,
+ timeseriesResults,
+ }: {
+ tableResults?: TableDataWithTitle[];
+ timeseriesResults?: Series[];
+ }) => {
+ this.setState({seriesData: timeseriesResults, tableData: tableResults});
+ };
+
render() {
const {
api,
@@ -187,6 +206,7 @@ class WidgetCard extends React.Component<Props> {
renderErrorMessage={renderErrorMessage}
tableItemLimit={tableItemLimit}
windowWidth={windowWidth}
+ onDataFetched={this.setData}
/>
) : (
<LazyLoad once resize height={200}>
@@ -199,6 +219,7 @@ class WidgetCard extends React.Component<Props> {
renderErrorMessage={renderErrorMessage}
tableItemLimit={tableItemLimit}
windowWidth={windowWidth}
+ onDataFetched={this.setData}
/>
</LazyLoad>
)}
diff --git a/static/app/views/dashboardsV2/widgetCard/widgetCardChartContainer.tsx b/static/app/views/dashboardsV2/widgetCard/widgetCardChartContainer.tsx
index 7fea4a577c42cb..118ad928af6303 100644
--- a/static/app/views/dashboardsV2/widgetCard/widgetCardChartContainer.tsx
+++ b/static/app/views/dashboardsV2/widgetCard/widgetCardChartContainer.tsx
@@ -12,7 +12,7 @@ import Placeholder from 'sentry/components/placeholder';
import {IconWarning} from 'sentry/icons';
import space from 'sentry/styles/space';
import {Organization, PageFilters} from 'sentry/types';
-import {EChartDataZoomHandler, EChartEventHandler} from 'sentry/types/echarts';
+import {EChartDataZoomHandler, EChartEventHandler, Series} from 'sentry/types/echarts';
import {defined} from 'sentry/utils';
import {getIssueFieldRenderer} from 'sentry/utils/dashboards/issueFieldRenderers';
import {TableDataRow} from 'sentry/utils/discover/discoverQuery';
@@ -41,6 +41,7 @@ type Props = WithRouterProps & {
expandNumbers?: boolean;
isMobile?: boolean;
legendOptions?: LegendComponentOption;
+ onDataFetched?: (results: {timeseriesResults?: Series[]}) => void;
onLegendSelectChanged?: EChartEventHandler<{
name: string;
selected: Record<string, boolean>;
@@ -67,6 +68,7 @@ export function WidgetCardChartContainer({
onLegendSelectChanged,
legendOptions,
expandNumbers,
+ onDataFetched,
}: Props) {
function issueTableResultComponent({
loading,
@@ -187,6 +189,7 @@ export function WidgetCardChartContainer({
widget={widget}
selection={selection}
limit={tableItemLimit}
+ onDataFetched={onDataFetched}
>
{({tableResults, timeseriesResults, errorMessage, loading}) => {
return (
diff --git a/static/app/views/dashboardsV2/widgetCard/widgetCardContextMenu.tsx b/static/app/views/dashboardsV2/widgetCard/widgetCardContextMenu.tsx
index 3b018e3c356217..862eda415855c2 100644
--- a/static/app/views/dashboardsV2/widgetCard/widgetCardContextMenu.tsx
+++ b/static/app/views/dashboardsV2/widgetCard/widgetCardContextMenu.tsx
@@ -12,10 +12,13 @@ import {IconEllipsis, IconExpand} from 'sentry/icons';
import {t} from 'sentry/locale';
import space from 'sentry/styles/space';
import {Organization, PageFilters} from 'sentry/types';
+import {Series} from 'sentry/types/echarts';
import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
+import {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
import {getWidgetDiscoverUrl, getWidgetIssueUrl} from 'sentry/views/dashboardsV2/utils';
import {Widget, WidgetType} from '../types';
+import {WidgetViewerContext} from '../widgetViewer/widgetViewerContext';
type Props = {
location: Location;
@@ -29,8 +32,10 @@ type Props = {
onDelete?: () => void;
onDuplicate?: () => void;
onEdit?: () => void;
+ seriesData?: Series[];
showContextMenu?: boolean;
showWidgetViewerButton?: boolean;
+ tableData?: TableDataWithTitle[];
};
function WidgetCardContextMenu({
@@ -47,6 +52,8 @@ function WidgetCardContextMenu({
router,
location,
index,
+ seriesData,
+ tableData,
}: Props) {
if (!showContextMenu) {
return null;
@@ -68,34 +75,43 @@ function WidgetCardContextMenu({
if (isPreview) {
return (
- <ContextWrapper>
- <StyledDropdownMenuControlV2
- items={[
- {
- key: 'preview',
- label: t('This is a preview only. To edit, you must add this dashboard.'),
- },
- ]}
- triggerProps={{
- 'aria-label': t('Widget actions'),
- size: 'xsmall',
- borderless: true,
- showChevron: false,
- icon: <IconEllipsis direction="down" size="sm" />,
- }}
- placement="bottom right"
- disabledKeys={['preview']}
- />
- {showWidgetViewerButton && (
- <OpenWidgetViewerButton
- aria-label={t('Open Widget Viewer')}
- priority="link"
- size="zero"
- icon={<IconExpand size="xs" />}
- onClick={() => openWidgetViewerPath(index)}
- />
+ <WidgetViewerContext.Consumer>
+ {({setData}) => (
+ <ContextWrapper>
+ <StyledDropdownMenuControlV2
+ items={[
+ {
+ key: 'preview',
+ label: t(
+ 'This is a preview only. To edit, you must add this dashboard.'
+ ),
+ },
+ ]}
+ triggerProps={{
+ 'aria-label': t('Widget actions'),
+ size: 'xsmall',
+ borderless: true,
+ showChevron: false,
+ icon: <IconEllipsis direction="down" size="sm" />,
+ }}
+ placement="bottom right"
+ disabledKeys={['preview']}
+ />
+ {showWidgetViewerButton && (
+ <OpenWidgetViewerButton
+ aria-label={t('Open Widget Viewer')}
+ priority="link"
+ size="zero"
+ icon={<IconExpand size="xs" />}
+ onClick={() => {
+ (seriesData || tableData) && setData({seriesData, tableData});
+ openWidgetViewerPath(index);
+ }}
+ />
+ )}
+ </ContextWrapper>
)}
- </ContextWrapper>
+ </WidgetViewerContext.Consumer>
);
}
@@ -172,29 +188,36 @@ function WidgetCardContextMenu({
}
return (
- <ContextWrapper>
- <StyledDropdownMenuControlV2
- items={menuOptions}
- triggerProps={{
- 'aria-label': t('Widget actions'),
- size: 'xsmall',
- borderless: true,
- showChevron: false,
- icon: <IconEllipsis direction="down" size="sm" />,
- }}
- placement="bottom right"
- disabledKeys={disabledKeys}
- />
- {showWidgetViewerButton && (
- <OpenWidgetViewerButton
- aria-label={t('Open Widget Viewer')}
- priority="link"
- size="zero"
- icon={<IconExpand size="xs" />}
- onClick={() => openWidgetViewerPath(widget.id ?? index)}
- />
+ <WidgetViewerContext.Consumer>
+ {({setData}) => (
+ <ContextWrapper>
+ <StyledDropdownMenuControlV2
+ items={menuOptions}
+ triggerProps={{
+ 'aria-label': t('Widget actions'),
+ size: 'xsmall',
+ borderless: true,
+ showChevron: false,
+ icon: <IconEllipsis direction="down" size="sm" />,
+ }}
+ placement="bottom right"
+ disabledKeys={disabledKeys}
+ />
+ {showWidgetViewerButton && (
+ <OpenWidgetViewerButton
+ aria-label={t('Open Widget Viewer')}
+ priority="link"
+ size="zero"
+ icon={<IconExpand size="xs" />}
+ onClick={() => {
+ (seriesData || tableData) && setData({seriesData, tableData});
+ openWidgetViewerPath(widget.id ?? index);
+ }}
+ />
+ )}
+ </ContextWrapper>
)}
- </ContextWrapper>
+ </WidgetViewerContext.Consumer>
);
}
diff --git a/static/app/views/dashboardsV2/widgetCard/widgetQueries.tsx b/static/app/views/dashboardsV2/widgetCard/widgetQueries.tsx
index ff15e3195c1205..ae2f3bc2cacd11 100644
--- a/static/app/views/dashboardsV2/widgetCard/widgetQueries.tsx
+++ b/static/app/views/dashboardsV2/widgetCard/widgetQueries.tsx
@@ -140,6 +140,10 @@ type Props = {
widget: Widget;
cursor?: string;
limit?: number;
+ onDataFetched?: (results: {
+ tableResults?: TableDataWithTitle[];
+ timeseriesResults?: Series[];
+ }) => void;
pagination?: boolean;
};
@@ -253,7 +257,16 @@ class WidgetQueries extends React.Component<Props, State> {
private _isMounted: boolean = false;
fetchEventData(queryFetchID: symbol) {
- const {selection, api, organization, widget, limit, cursor, pagination} = this.props;
+ const {
+ selection,
+ api,
+ organization,
+ widget,
+ limit,
+ cursor,
+ pagination,
+ onDataFetched,
+ } = this.props;
let tableResults: TableDataWithTitle[] = [];
// Table, world map, and stat widgets use table results and need
@@ -306,6 +319,8 @@ class WidgetQueries extends React.Component<Props, State> {
return;
}
+ onDataFetched?.({tableResults});
+
this.setState(prevState => {
if (prevState.queryFetchID !== queryFetchID) {
// invariant: a different request was initiated after this request
@@ -342,7 +357,7 @@ class WidgetQueries extends React.Component<Props, State> {
}
fetchTimeseriesData(queryFetchID: symbol, displayType: DisplayType) {
- const {selection, api, organization, widget} = this.props;
+ const {selection, api, organization, widget, onDataFetched} = this.props;
const widgetBuilderNewDesign = organization.features.includes(
'new-widget-builder-experience-design'
);
@@ -440,6 +455,8 @@ class WidgetQueries extends React.Component<Props, State> {
const rawResultsClone = cloneDeep(prevState.rawResults ?? []);
rawResultsClone[requestIndex] = rawResults;
+ onDataFetched?.({timeseriesResults});
+
return {
...prevState,
timeseriesResults,
diff --git a/static/app/views/dashboardsV2/widgetViewer/widgetViewerContext.tsx b/static/app/views/dashboardsV2/widgetViewer/widgetViewerContext.tsx
new file mode 100644
index 00000000000000..ece756bc00c6eb
--- /dev/null
+++ b/static/app/views/dashboardsV2/widgetViewer/widgetViewerContext.tsx
@@ -0,0 +1,14 @@
+import {createContext} from 'react';
+
+import {Series} from 'sentry/types/echarts';
+import {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
+
+export type WidgetViewerContextProps = {
+ setData: (data: {seriesData?: Series[]; tableData?: TableDataWithTitle[]}) => void;
+ seriesData?: Series[];
+ tableData?: TableDataWithTitle[];
+};
+
+export const WidgetViewerContext = createContext<WidgetViewerContextProps>({
+ setData: () => undefined,
+});
diff --git a/tests/js/spec/components/modals/widgetViewerModal.spec.tsx b/tests/js/spec/components/modals/widgetViewerModal.spec.tsx
index 24305c80bd4695..fabd471ba2e52b 100644
--- a/tests/js/spec/components/modals/widgetViewerModal.spec.tsx
+++ b/tests/js/spec/components/modals/widgetViewerModal.spec.tsx
@@ -7,6 +7,8 @@ import {ModalRenderProps} from 'sentry/actionCreators/modal';
import WidgetViewerModal from 'sentry/components/modals/widgetViewerModal';
import MemberListStore from 'sentry/stores/memberListStore';
import space from 'sentry/styles/space';
+import {Series} from 'sentry/types/echarts';
+import {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
import {DisplayType, WidgetType} from 'sentry/views/dashboardsV2/types';
jest.mock('echarts-for-react/lib/core', () => {
@@ -31,7 +33,17 @@ const waitForMetaToHaveBeenCalled = async () => {
});
};
-async function renderModal({initialData: {organization, routerContext}, widget}) {
+async function renderModal({
+ initialData: {organization, routerContext},
+ widget,
+ seriesData,
+ tableData,
+}: {
+ initialData: any;
+ widget: any;
+ seriesData?: Series[];
+ tableData?: TableDataWithTitle[];
+}) {
const rendered = render(
<div style={{padding: space(4)}}>
<WidgetViewerModal
@@ -43,6 +55,8 @@ async function renderModal({initialData: {organization, routerContext}, widget})
organization={organization}
widget={widget}
onEdit={() => undefined}
+ seriesData={seriesData}
+ tableData={tableData}
/>
</div>,
{
@@ -468,10 +482,27 @@ describe('Modals -> WidgetViewerModal', function () {
await waitForMetaToHaveBeenCalled();
expect(await screen.findByText('Next Page Test Error')).toBeInTheDocument();
});
+
+ it('uses provided seriesData and does not make an events-stats requests', async function () {
+ await renderModal({initialData, widget: mockWidget, seriesData: []});
+ expect(eventsStatsMock).not.toHaveBeenCalled();
+ });
+
+ it('makes events-stats requests when table is sorted', async function () {
+ await renderModal({
+ initialData,
+ widget: mockWidget,
+ seriesData: [],
+ });
+ expect(eventsStatsMock).not.toHaveBeenCalled();
+ userEvent.click(screen.getByText('count()'));
+ await waitForMetaToHaveBeenCalled();
+ expect(eventsStatsMock).toHaveBeenCalledTimes(1);
+ });
});
describe('Discover World Map Chart Widget', function () {
- let eventsMock;
+ let eventsMock, eventsGeoMock;
const mockQuery = {
conditions: 'title:/organizations/:orgId/performance/summary/',
fields: ['p75(measurements.lcp)'],
@@ -513,7 +544,7 @@ describe('Modals -> WidgetViewerModal', function () {
url: '/organizations/org-slug/eventsv2/',
body: eventsBody,
});
- MockApiClient.addMockResponse({
+ eventsGeoMock = MockApiClient.addMockResponse({
url: '/organizations/org-slug/events-geo/',
body: eventsBody,
});
@@ -536,6 +567,11 @@ describe('Modals -> WidgetViewerModal', function () {
const {container} = await renderModal({initialData, widget: mockWidget});
expect(container).toSnapshot();
});
+
+ it('uses provided tableData and does not make an eventsv2 requests', async function () {
+ await renderModal({initialData, widget: mockWidget, tableData: []});
+ expect(eventsGeoMock).not.toHaveBeenCalled();
+ });
});
describe('Issue Table Widget', function () {
|
f56dd97d3bab16fbb8fa065fab6a3d409b880fb1
|
2022-01-28 21:15:23
|
Tony Xiao
|
test(performance): Native platform should use all transactions (#31423)
| false
|
Native platform should use all transactions (#31423)
|
test
|
diff --git a/tests/js/spec/views/performance/landing/utils.spec.jsx b/tests/js/spec/views/performance/landing/utils.spec.jsx
index 7380ffac1a5b81..5548af5aebaffc 100644
--- a/tests/js/spec/views/performance/landing/utils.spec.jsx
+++ b/tests/js/spec/views/performance/landing/utils.spec.jsx
@@ -55,6 +55,13 @@ describe('Utils', function () {
getCurrentLandingDisplay(data.router.location, projects, data.eventView).label
).toEqual('Backend');
});
+ it('returns all display for native platform', function () {
+ const projects = [TestStubs.Project({id: '22', platform: 'native'})];
+ const data = initializeData(projects, {project: [22]});
+ expect(
+ getCurrentLandingDisplay(data.router.location, projects, data.eventView).label
+ ).toEqual('All Transactions');
+ });
it('returns all display if multiple projects', function () {
const projects = [TestStubs.Project()];
const data = initializeData(projects, {project: [1, 2]});
|
7829e6b36eec77a5ed3596307fb3f92b317e0d9f
|
2023-11-03 20:54:55
|
dependabot[bot]
|
chore(deps): bump django from 3.2.20 to 3.2.23 (#59324)
| false
|
bump django from 3.2.20 to 3.2.23 (#59324)
|
chore
|
diff --git a/requirements-dev-frozen.txt b/requirements-dev-frozen.txt
index d0ff6c70ff3603..de7e12e0e5c2f4 100644
--- a/requirements-dev-frozen.txt
+++ b/requirements-dev-frozen.txt
@@ -39,7 +39,7 @@ datadog==0.29.3
decorator==5.1.1
dictpath==0.1.3
distlib==0.3.4
-django==3.2.20
+django==3.2.23
django-crispy-forms==1.14.0
django-csp==3.7
django-pg-zero-downtime-migrations==0.13
diff --git a/requirements-frozen.txt b/requirements-frozen.txt
index e30342569da9aa..4482a7625a84e3 100644
--- a/requirements-frozen.txt
+++ b/requirements-frozen.txt
@@ -31,7 +31,7 @@ cssselect==1.0.3
cssutils==2.4.0
datadog==0.29.3
decorator==5.1.1
-django==3.2.20
+django==3.2.23
django-crispy-forms==1.14.0
django-csp==3.7
django-pg-zero-downtime-migrations==0.13
|
c5bc40f57126155184ecf37d2e482306d27c0bb7
|
2023-09-06 22:24:09
|
Cathy Teng
|
chore(github-growth): add column for file language in CommitFileChange (#55732)
| false
|
add column for file language in CommitFileChange (#55732)
|
chore
|
diff --git a/migrations_lockfile.txt b/migrations_lockfile.txt
index f24868c19af2a7..61170ecf80c13d 100644
--- a/migrations_lockfile.txt
+++ b/migrations_lockfile.txt
@@ -7,5 +7,5 @@ will then be regenerated, and you should be able to merge without conflicts.
nodestore: 0002_nodestore_no_dictfield
replays: 0003_add_size_to_recording_segment
-sentry: 0541_add_replicated_auth_models
+sentry: 0542_add_commitfilechange_language_col
social_auth: 0002_default_auto_field
diff --git a/src/sentry/migrations/0542_add_commitfilechange_language_col.py b/src/sentry/migrations/0542_add_commitfilechange_language_col.py
new file mode 100644
index 00000000000000..8e402930150447
--- /dev/null
+++ b/src/sentry/migrations/0542_add_commitfilechange_language_col.py
@@ -0,0 +1,31 @@
+# Generated by Django 3.2.20 on 2023-08-31 21:46
+
+from django.db import migrations, models
+
+from sentry.new_migrations.migrations import CheckedMigration
+
+
+class Migration(CheckedMigration):
+ # This flag is used to mark that a migration shouldn't be automatically run in production. For
+ # the most part, this should only be used for operations where it's safe to run the migration
+ # after your code has deployed. So this should not be used for most operations that alter the
+ # schema of a table.
+ # Here are some things that make sense to mark as dangerous:
+ # - Large data migrations. Typically we want these to be run manually by ops so that they can
+ # be monitored and not block the deploy for a long period of time while they run.
+ # - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to
+ # have ops run this and not block the deploy. Note that while adding an index is a schema
+ # change, it's completely safe to run the operation after the code has deployed.
+ is_dangerous = False
+
+ dependencies = [
+ ("sentry", "0541_add_replicated_auth_models"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="commitfilechange",
+ name="language",
+ field=models.CharField(default=None, max_length=255, null=True),
+ ),
+ ]
diff --git a/src/sentry/models/commitfilechange.py b/src/sentry/models/commitfilechange.py
index 7ac9d91ef69006..b227184188e9c2 100644
--- a/src/sentry/models/commitfilechange.py
+++ b/src/sentry/models/commitfilechange.py
@@ -31,6 +31,7 @@ class CommitFileChange(Model):
type = models.CharField(
max_length=1, choices=(("A", "Added"), ("D", "Deleted"), ("M", "Modified"))
)
+ language = models.CharField(default=None, null=True, max_length=255)
objects = CommitFileChangeManager()
|
c5be112c63c66a417a6f4a4f4c5a5816a98bc124
|
2023-03-16 05:00:02
|
Evan Purkhiser
|
ref(monitors): Use _create_monitor in more tests (#45893)
| false
|
Use _create_monitor in more tests (#45893)
|
ref
|
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 e60e1580e931fc..71abd5af17ffa3 100644
--- a/tests/sentry/monitors/endpoints/test_monitor_ingest_checkin_index.py
+++ b/tests/sentry/monitors/endpoints/test_monitor_ingest_checkin_index.py
@@ -123,14 +123,7 @@ def test_failing(self):
def test_disabled(self):
for path_func in self._get_path_functions():
- monitor = Monitor.objects.create(
- organization_id=self.organization.id,
- project_id=self.project.id,
- next_checkin=timezone.now() - timedelta(minutes=1),
- type=MonitorType.CRON_JOB,
- status=MonitorStatus.DISABLED,
- config={"schedule": "* * * * *"},
- )
+ monitor = self._create_monitor(status=MonitorStatus.DISABLED)
path = path_func(monitor.guid)
resp = self.client.post(path, {"status": "error"}, **self.token_auth_headers)
@@ -152,14 +145,7 @@ def test_disabled(self):
)
def test_pending_deletion(self):
- monitor = Monitor.objects.create(
- organization_id=self.organization.id,
- project_id=self.project.id,
- next_checkin=timezone.now() - timedelta(minutes=1),
- type=MonitorType.CRON_JOB,
- status=MonitorStatus.PENDING_DELETION,
- config={"schedule": "* * * * *"},
- )
+ monitor = self._create_monitor(status=MonitorStatus.PENDING_DELETION)
for path_func in self._get_path_functions():
path = path_func(monitor.guid)
@@ -168,14 +154,7 @@ def test_pending_deletion(self):
assert resp.status_code == 404
def test_deletion_in_progress(self):
- monitor = Monitor.objects.create(
- organization_id=self.organization.id,
- project_id=self.project.id,
- next_checkin=timezone.now() - timedelta(minutes=1),
- type=MonitorType.CRON_JOB,
- status=MonitorStatus.DELETION_IN_PROGRESS,
- config={"schedule": "* * * * *"},
- )
+ monitor = self._create_monitor(status=MonitorStatus.DELETION_IN_PROGRESS)
for path_func in self._get_path_functions():
path = path_func(monitor.guid)
|
0419bfc948391ce0a062e5921fd846f711716fa3
|
2024-07-27 00:08:25
|
Andrew Liu
|
feat(replay): add feedback button to HE modal, using pause/unpause focus (#74927)
| false
|
add feedback button to HE modal, using pause/unpause focus (#74927)
|
feat
|
diff --git a/static/app/components/feedback/widget/feedbackWidgetButton.tsx b/static/app/components/feedback/widget/feedbackWidgetButton.tsx
index 551e6dd08e2936..153aa3287d5dcf 100644
--- a/static/app/components/feedback/widget/feedbackWidgetButton.tsx
+++ b/static/app/components/feedback/widget/feedbackWidgetButton.tsx
@@ -1,13 +1,18 @@
import {useRef} from 'react';
import {Button} from 'sentry/components/button';
+import type {UseFeedbackOptions} from 'sentry/components/feedback/widget/useFeedback';
import useFeedbackWidget from 'sentry/components/feedback/widget/useFeedbackWidget';
import {IconMegaphone} from 'sentry/icons/iconMegaphone';
import {t} from 'sentry/locale';
-export default function FeedbackWidgetButton() {
+export default function FeedbackWidgetButton({
+ optionOverrides,
+}: {
+ optionOverrides?: UseFeedbackOptions;
+}) {
const buttonRef = useRef<HTMLButtonElement>(null);
- const feedback = useFeedbackWidget({buttonRef});
+ const feedback = useFeedbackWidget({buttonRef, optionOverrides});
// Do not show button if Feedback integration is not enabled
if (!feedback) {
diff --git a/static/app/components/feedback/widget/useFeedback.tsx b/static/app/components/feedback/widget/useFeedback.tsx
index 1f46ae58a8de09..c186620af3b85a 100644
--- a/static/app/components/feedback/widget/useFeedback.tsx
+++ b/static/app/components/feedback/widget/useFeedback.tsx
@@ -14,7 +14,10 @@ export function useFeedback({
formTitle,
messagePlaceholder,
tags,
-}: NonNullable<UseFeedbackOptions>) {
+}: NonNullable<UseFeedbackOptions>): {
+ feedback: FeedbackIntegration | undefined;
+ options: NonNullable<UseFeedbackOptions>;
+} {
const config = useLegacyStore(ConfigStore);
const {state} = useAsyncSDKIntegrationStore();
diff --git a/static/app/components/feedback/widget/useFeedbackWidget.tsx b/static/app/components/feedback/widget/useFeedbackWidget.tsx
index 921b4d9b162a1b..ad60f82a85bf01 100644
--- a/static/app/components/feedback/widget/useFeedbackWidget.tsx
+++ b/static/app/components/feedback/widget/useFeedbackWidget.tsx
@@ -1,26 +1,41 @@
import type {RefObject} from 'react';
import {useEffect} from 'react';
+import type {UseFeedbackOptions} from 'sentry/components/feedback/widget/useFeedback';
import {useFeedback} from 'sentry/components/feedback/widget/useFeedback';
interface Props {
buttonRef?: RefObject<HTMLButtonElement> | RefObject<HTMLAnchorElement>;
formTitle?: string;
messagePlaceholder?: string;
+ optionOverrides?: UseFeedbackOptions;
}
export default function useFeedbackWidget({
buttonRef,
formTitle,
messagePlaceholder,
+ optionOverrides,
}: Props) {
- const {feedback, options} = useFeedback({formTitle, messagePlaceholder});
+ const {feedback, options: defaultOptions} = useFeedback({
+ formTitle,
+ messagePlaceholder,
+ });
useEffect(() => {
if (!feedback) {
return undefined;
}
+ const options = {
+ ...defaultOptions,
+ ...optionOverrides,
+ tags: {
+ ...defaultOptions.tags,
+ ...optionOverrides?.tags,
+ },
+ };
+
if (buttonRef) {
if (buttonRef.current) {
return feedback.attachTo(buttonRef.current, options);
@@ -33,7 +48,7 @@ export default function useFeedbackWidget({
}
return undefined;
- }, [buttonRef, feedback, options]);
+ }, [buttonRef, feedback, defaultOptions, optionOverrides]);
return feedback;
}
diff --git a/static/app/components/globalModal/index.tsx b/static/app/components/globalModal/index.tsx
index 52aa0b6274a2e4..e363242cb52e9a 100644
--- a/static/app/components/globalModal/index.tsx
+++ b/static/app/components/globalModal/index.tsx
@@ -151,6 +151,7 @@ function GlobalModal({onClose}: Props) {
escapeDeactivates: false,
fallbackFocus: portal,
});
+ ModalStore.setFocusTrap(focusTrap.current);
}, [portal]);
useEffect(() => {
diff --git a/static/app/components/replays/breadcrumbs/replayComparisonModal.tsx b/static/app/components/replays/breadcrumbs/replayComparisonModal.tsx
index 95b85b6e62a7fb..96d0729abd2b9d 100644
--- a/static/app/components/replays/breadcrumbs/replayComparisonModal.tsx
+++ b/static/app/components/replays/breadcrumbs/replayComparisonModal.tsx
@@ -2,9 +2,11 @@ import styled from '@emotion/styled';
import type {ModalRenderProps} from 'sentry/actionCreators/modal';
import FeatureBadge from 'sentry/components/badge/featureBadge';
-import {GithubFeedbackButton} from 'sentry/components/githubFeedbackButton';
+import FeedbackWidgetButton from 'sentry/components/feedback/widget/feedbackWidgetButton';
import ReplayDiffChooser from 'sentry/components/replays/diff/replayDiffChooser';
-import {t, tct} from 'sentry/locale';
+import {tct} from 'sentry/locale';
+import ModalStore from 'sentry/stores/modalStore';
+import {useLegacyStore} from 'sentry/stores/useLegacyStore';
import {space} from 'sentry/styles/space';
import type {Organization} from 'sentry/types/organization';
import type ReplayReader from 'sentry/utils/replays/replayReader';
@@ -25,6 +27,10 @@ export default function ReplayComparisonModal({
replay,
rightOffsetMs,
}: Props) {
+ // Callbacks set by GlobalModal on-render.
+ // We need these to interact with feedback opened while a modal is active.
+ const {focusTrap} = useLegacyStore(ModalStore);
+
return (
<OrganizationContext.Provider value={organization}>
<Header closeButton>
@@ -33,14 +39,18 @@ export default function ReplayComparisonModal({
Hydration Error
<FeatureBadge type="beta" />
</h4>
- <GithubFeedbackButton
- href="https://github.com/getsentry/sentry/discussions/62097"
- label={t('Discussion')}
- title={null}
- analyticsEventKey="replay.details-hydration-discussion-clicked"
- analyticsEventName="Replay Details Hydration Discussion Clicked"
- priority="primary"
- />
+ {focusTrap ? (
+ <FeedbackWidgetButton
+ optionOverrides={{
+ onFormOpen: () => {
+ focusTrap.pause();
+ },
+ onFormClose: () => {
+ focusTrap.unpause();
+ },
+ }}
+ />
+ ) : null}
</ModalHeader>
</Header>
<Body>
diff --git a/static/app/stores/modalStore.tsx b/static/app/stores/modalStore.tsx
index 01787e203ec638..b573d15f697e71 100644
--- a/static/app/stores/modalStore.tsx
+++ b/static/app/stores/modalStore.tsx
@@ -1,3 +1,4 @@
+import type {FocusTrap} from 'focus-trap';
import {createStore} from 'reflux';
import type {ModalOptions, ModalRenderProps} from 'sentry/actionCreators/modal';
@@ -9,6 +10,7 @@ type Renderer = (renderProps: ModalRenderProps) => React.ReactNode;
type State = {
options: ModalOptions;
renderer: Renderer | null;
+ focusTrap?: FocusTrap;
};
interface ModalStoreDefinition extends StrictStoreDefinition<State> {
@@ -16,6 +18,7 @@ interface ModalStoreDefinition extends StrictStoreDefinition<State> {
init(): void;
openModal(renderer: Renderer, options: ModalOptions): void;
reset(): void;
+ setFocusTrap(focusTrap: FocusTrap): void;
}
const storeConfig: ModalStoreDefinition = {
@@ -35,6 +38,7 @@ const storeConfig: ModalStoreDefinition = {
this.state = {
renderer: null,
options: {},
+ focusTrap: this.state.focusTrap,
};
},
@@ -44,9 +48,16 @@ const storeConfig: ModalStoreDefinition = {
},
openModal(renderer: Renderer, options: ModalOptions) {
- this.state = {renderer, options};
+ this.state = {renderer, options, focusTrap: this.state.focusTrap};
this.trigger(this.state);
},
+
+ setFocusTrap(focusTrap: FocusTrap) {
+ this.state = {
+ ...this.state,
+ focusTrap,
+ };
+ },
};
const ModalStore = createStore(storeConfig);
diff --git a/static/app/views/app/asyncSDKIntegrationProvider.tsx b/static/app/views/app/asyncSDKIntegrationProvider.tsx
index 3163d9f1b239a9..386feb7099da79 100644
--- a/static/app/views/app/asyncSDKIntegrationProvider.tsx
+++ b/static/app/views/app/asyncSDKIntegrationProvider.tsx
@@ -5,10 +5,12 @@ type Integration = Parameters<typeof addIntegration>[0];
type State = Record<string, Integration | undefined>;
-const context = createContext<{
+type Context = {
setState: React.Dispatch<React.SetStateAction<State>>;
state: State;
-}>({
+};
+
+const context = createContext<Context>({
setState: () => {},
state: {},
});
@@ -19,10 +21,9 @@ export function AsyncSDKIntegrationContextProvider({
children: React.ReactNode;
}) {
const [state, setState] = useState<State>({});
-
return <context.Provider value={{setState, state}}>{children}</context.Provider>;
}
-export default function useAsyncSDKIntegrationStore() {
+export default function useAsyncSDKIntegrationStore(): Context {
return useContext(context);
}
|
ec81e9f5fbe43a648008c951029690e71de89286
|
2023-06-29 00:46:19
|
Dominik Buszowiecki
|
feat(starfish): add max range of 7 day starfish (#51727)
| false
|
add max range of 7 day starfish (#51727)
|
feat
|
diff --git a/static/app/components/calendar/dateRangePicker.tsx b/static/app/components/calendar/dateRangePicker.tsx
index c8281be63c5f0d..c142e909ecb882 100644
--- a/static/app/components/calendar/dateRangePicker.tsx
+++ b/static/app/components/calendar/dateRangePicker.tsx
@@ -7,6 +7,7 @@ export interface DateRangePickerProps
extends Omit<DateRangeProps, 'ranges' | 'onChange'> {
onChange: (range: Range) => void;
endDate?: Date;
+ maxDateRange?: number;
startDate?: Date;
}
diff --git a/static/app/components/organizations/timeRangeSelector/dateRange.tsx b/static/app/components/organizations/timeRangeSelector/dateRange.tsx
index 4dcd4bb1c6606a..b40355613f89f5 100644
--- a/static/app/components/organizations/timeRangeSelector/dateRange.tsx
+++ b/static/app/components/organizations/timeRangeSelector/dateRange.tsx
@@ -66,6 +66,11 @@ type Props = WithRouterProps & {
className?: string;
+ /**
+ * The largest date range (ie. end date - start date) allowed
+ */
+ maxDateRange?: number;
+
/**
* Should we have a time selector?
*/
@@ -95,7 +100,6 @@ class BaseDateRange extends Component<Props, State> {
handleSelectDateRange = (range: Range) => {
const {onChange} = this.props;
const {startDate, endDate} = range;
-
const end = endDate ? getEndOfDay(endDate) : endDate;
onChange({
@@ -167,7 +171,8 @@ class BaseDateRange extends Component<Props, State> {
};
render() {
- const {className, maxPickableDays, utc, showTimePicker, onChangeUtc} = this.props;
+ const {className, maxPickableDays, utc, showTimePicker, onChangeUtc, maxDateRange} =
+ this.props;
const {hasStartErrors, hasEndErrors} = this.state;
const start = this.props.start ?? '';
const end = this.props.end ?? '';
@@ -182,17 +187,26 @@ class BaseDateRange extends Component<Props, State> {
// Subtract additional day because we force the end date to be inclusive,
// so when you pick Jan 1 the time becomes Jan 1 @ 23:59:59,
// (or really, Jan 2 @ 00:00:00 - 1 second), while the start time is at 00:00
- const minDate = getStartOfPeriodAgo(
- 'days',
- (maxPickableDays ?? MAX_PICKABLE_DAYS) - 2
- );
- const maxDate = new Date();
+ let minDate = getStartOfPeriodAgo('days', (maxPickableDays ?? MAX_PICKABLE_DAYS) - 2);
+
+ let maxDate = new Date();
+
+ // if the start and end date are the same, it means the user can still select another date,
+ // at this point we want to apply the maxDateRange
+ const startDate = moment(start).local();
+ const endDate = moment(end).local();
+ const isSameDay = startDate.isSame(endDate, 'day');
+ if (maxDateRange && isSameDay) {
+ minDate = moment(new Date(start)).subtract(maxDateRange, 'days').toDate();
+ const newMaxDate = moment(new Date(end)).add(maxDateRange, 'days').toDate();
+ maxDate = newMaxDate > maxDate ? maxDate : newMaxDate;
+ }
return (
<div className={className} data-test-id="date-range">
<DateRangePicker
- startDate={moment(start).local().toDate()}
- endDate={moment(end).local().toDate()}
+ startDate={startDate.toDate()}
+ endDate={endDate.toDate()}
minDate={minDate}
maxDate={maxDate}
onChange={this.handleSelectDateRange}
diff --git a/static/app/components/organizations/timeRangeSelector/index.tsx b/static/app/components/organizations/timeRangeSelector/index.tsx
index 896f6afb024970..9428fac0271b3b 100644
--- a/static/app/components/organizations/timeRangeSelector/index.tsx
+++ b/static/app/components/organizations/timeRangeSelector/index.tsx
@@ -158,6 +158,10 @@ type Props = WithRouterProps & {
*/
label?: React.ReactNode;
+ /**
+ * The maximum range (ie. endDate - startDate) allowed to be selected
+ */
+ maxDateRange?: number;
/**
* The maximum number of days in the past you can pick
*/
@@ -433,6 +437,7 @@ class TimeRangeSelector extends PureComponent<Props, State> {
label,
relativeOptions,
maxPickableDays,
+ maxDateRange,
customDropdownButton,
detached,
disabled,
@@ -509,6 +514,7 @@ class TimeRangeSelector extends PureComponent<Props, State> {
onChange={this.handleSelectDateRange}
onChangeUtc={this.handleUseUtc}
maxPickableDays={maxPickableDays}
+ maxDateRange={maxDateRange}
/>
<SubmitRow>
<MultipleSelectorSubmitRow
diff --git a/static/app/components/timeRangeSelector.tsx b/static/app/components/timeRangeSelector.tsx
index 097f2f2ba83e98..1288053ea69648 100644
--- a/static/app/components/timeRangeSelector.tsx
+++ b/static/app/components/timeRangeSelector.tsx
@@ -83,6 +83,10 @@ export interface TimeRangeSelectorProps
* End date value for absolute date selector
*/
end?: DateString;
+ /**
+ * The largest date range (ie. end date - start date) allowed
+ */
+ maxDateRange?: number;
/**
* The maximum number of days in the past you can pick
*/
@@ -136,6 +140,7 @@ export function TimeRangeSelector({
defaultAbsolute,
defaultPeriod = DEFAULT_STATS_PERIOD,
maxPickableDays = 90,
+ maxDateRange,
disallowArbitraryRelativeRanges = false,
trigger,
menuWidth,
@@ -385,6 +390,7 @@ export function TimeRangeSelector({
});
}}
maxPickableDays={maxPickableDays}
+ maxDateRange={maxDateRange}
/>
</AbsoluteDateRangeWrap>
)}
diff --git a/static/app/views/starfish/components/datePicker.tsx b/static/app/views/starfish/components/datePicker.tsx
new file mode 100644
index 00000000000000..08ae88f63247e3
--- /dev/null
+++ b/static/app/views/starfish/components/datePicker.tsx
@@ -0,0 +1,23 @@
+import DatePageFilter from 'sentry/components/datePageFilter';
+import {t} from 'sentry/locale';
+import {MAXIMUM_DATE_RANGE} from 'sentry/views/starfish/components/pageFilterContainer';
+
+function StarfishDatePicker() {
+ return (
+ <DatePageFilter
+ maxDateRange={MAXIMUM_DATE_RANGE}
+ disallowArbitraryRelativeRanges
+ relativeOptions={{
+ '1h': t('Last hour'),
+ '12h': t('Last 12 hours'),
+ '24h': t('Last 24 hours'),
+ '3d': t('Last 3 days'),
+ '7d': t('Last 7 days'),
+ }}
+ defaultPeriod="24h"
+ alignDropdown="left"
+ />
+ );
+}
+
+export default StarfishDatePicker;
diff --git a/static/app/views/starfish/components/pageFilterContainer.tsx b/static/app/views/starfish/components/pageFilterContainer.tsx
new file mode 100644
index 00000000000000..4dd5f91f195103
--- /dev/null
+++ b/static/app/views/starfish/components/pageFilterContainer.tsx
@@ -0,0 +1,21 @@
+import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
+import usePageFilters from 'sentry/utils/usePageFilters';
+import {getDateFilters} from 'sentry/views/starfish/utils/getDateFilters';
+
+export const MAXIMUM_DATE_RANGE = 7;
+
+function StarfishPageFilterContainer(props: {children: React.ReactNode}) {
+ const {selection} = usePageFilters();
+ const datetime = selection.datetime;
+
+ const {endTime, startTime} = getDateFilters(selection);
+ if (endTime.diff(startTime, 'days') > MAXIMUM_DATE_RANGE) {
+ datetime.period = '24h';
+ datetime.start = null;
+ datetime.end = null;
+ }
+
+ return <PageFiltersContainer>{props.children}</PageFiltersContainer>;
+}
+
+export default StarfishPageFilterContainer;
diff --git a/static/app/views/starfish/modules/DBModule.tsx b/static/app/views/starfish/modules/DBModule.tsx
index 1daab8ded94302..c2878914b5029c 100644
--- a/static/app/views/starfish/modules/DBModule.tsx
+++ b/static/app/views/starfish/modules/DBModule.tsx
@@ -1,10 +1,10 @@
import * as Layout from 'sentry/components/layouts/thirds';
-import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
import {t} from 'sentry/locale';
import {
PageErrorAlert,
PageErrorProvider,
} from 'sentry/utils/performance/contexts/pageError';
+import StarfishPageFilterContainer from 'sentry/views/starfish/components/pageFilterContainer';
import {ModuleName} from 'sentry/views/starfish/types';
import SpansView from 'sentry/views/starfish/views/spans/spansView';
@@ -21,9 +21,9 @@ export default function DBModule() {
<Layout.Body>
<Layout.Main fullWidth>
<PageErrorAlert />
- <PageFiltersContainer>
+ <StarfishPageFilterContainer>
<SpansView moduleName={ModuleName.DB} />
- </PageFiltersContainer>
+ </StarfishPageFilterContainer>
</Layout.Main>
</Layout.Body>
</PageErrorProvider>
diff --git a/static/app/views/starfish/modules/HTTPModule.tsx b/static/app/views/starfish/modules/HTTPModule.tsx
index 23a376ca4c5cab..6b91135c43bf80 100644
--- a/static/app/views/starfish/modules/HTTPModule.tsx
+++ b/static/app/views/starfish/modules/HTTPModule.tsx
@@ -1,10 +1,10 @@
import * as Layout from 'sentry/components/layouts/thirds';
-import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
import {t} from 'sentry/locale';
import {
PageErrorAlert,
PageErrorProvider,
} from 'sentry/utils/performance/contexts/pageError';
+import StarfishPageFilterContainer from 'sentry/views/starfish/components/pageFilterContainer';
import {ModuleName} from 'sentry/views/starfish/types';
import SpansView from 'sentry/views/starfish/views/spans/spansView';
@@ -21,9 +21,9 @@ export default function HTTPModule() {
<Layout.Body>
<Layout.Main fullWidth>
<PageErrorAlert />
- <PageFiltersContainer>
+ <StarfishPageFilterContainer>
<SpansView moduleName={ModuleName.HTTP} />
- </PageFiltersContainer>
+ </StarfishPageFilterContainer>
</Layout.Main>
</Layout.Body>
</PageErrorProvider>
diff --git a/static/app/views/starfish/views/definitionsView/index.tsx b/static/app/views/starfish/views/definitionsView/index.tsx
index adc28fc02e6e21..5f82f5ea5c7564 100644
--- a/static/app/views/starfish/views/definitionsView/index.tsx
+++ b/static/app/views/starfish/views/definitionsView/index.tsx
@@ -1,14 +1,14 @@
import * as Layout from 'sentry/components/layouts/thirds';
-import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
import {
PageErrorAlert,
PageErrorProvider,
} from 'sentry/utils/performance/contexts/pageError';
+import StarfishPageFilterContainer from 'sentry/views/starfish/components/pageFilterContainer';
function DefinitionsView() {
return (
<Layout.Page>
- <PageFiltersContainer>
+ <StarfishPageFilterContainer>
<PageErrorProvider>
<Layout.Header>
<Layout.HeaderContent>
@@ -27,7 +27,7 @@ function DefinitionsView() {
</Layout.Main>
</Layout.Body>
</PageErrorProvider>
- </PageFiltersContainer>
+ </StarfishPageFilterContainer>
</Layout.Page>
);
}
diff --git a/static/app/views/starfish/views/spanSummaryPage/index.tsx b/static/app/views/starfish/views/spanSummaryPage/index.tsx
index 87834726f38bc4..4627cdd1320fda 100644
--- a/static/app/views/starfish/views/spanSummaryPage/index.tsx
+++ b/static/app/views/starfish/views/spanSummaryPage/index.tsx
@@ -6,7 +6,6 @@ import * as qs from 'query-string';
import Breadcrumbs, {Crumb} from 'sentry/components/breadcrumbs';
import DatePageFilter from 'sentry/components/datePageFilter';
import * as Layout from 'sentry/components/layouts/thirds';
-import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
import {Panel, PanelBody} from 'sentry/components/panels';
import QuestionTooltip from 'sentry/components/questionTooltip';
import {t} from 'sentry/locale';
@@ -22,6 +21,7 @@ import {normalizeUrl} from 'sentry/utils/withDomainRequired';
import {P95_COLOR, THROUGHPUT_COLOR} from 'sentry/views/starfish/colours';
import Chart, {useSynchronizeCharts} from 'sentry/views/starfish/components/chart';
import ChartPanel from 'sentry/views/starfish/components/chartPanel';
+import StarfishPageFilterContainer from 'sentry/views/starfish/components/pageFilterContainer';
import {SpanDescription} from 'sentry/views/starfish/components/spanDescription';
import DurationCell from 'sentry/views/starfish/components/tableCells/durationCell';
import ThroughputCell from 'sentry/views/starfish/components/tableCells/throughputCell';
@@ -134,7 +134,7 @@ function SpanSummaryPage({params, location}: Props) {
return (
<Layout.Page>
- <PageFiltersContainer>
+ <StarfishPageFilterContainer>
<PageErrorProvider>
<Layout.Header>
<Layout.HeaderContent>
@@ -255,7 +255,7 @@ function SpanSummaryPage({params, location}: Props) {
</Layout.Main>
</Layout.Body>
</PageErrorProvider>
- </PageFiltersContainer>
+ </StarfishPageFilterContainer>
</Layout.Page>
);
}
diff --git a/static/app/views/starfish/views/spans/index.tsx b/static/app/views/starfish/views/spans/index.tsx
index e106b71fe79572..3e4f20f0221835 100644
--- a/static/app/views/starfish/views/spans/index.tsx
+++ b/static/app/views/starfish/views/spans/index.tsx
@@ -1,11 +1,11 @@
import * as Layout from 'sentry/components/layouts/thirds';
-import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
import {t} from 'sentry/locale';
import {
PageErrorAlert,
PageErrorProvider,
} from 'sentry/utils/performance/contexts/pageError';
import {useLocation} from 'sentry/utils/useLocation';
+import StarfishPageFilterContainer from 'sentry/views/starfish/components/pageFilterContainer';
import {ModuleName} from 'sentry/views/starfish/types';
import SpansView from './spansView';
@@ -38,9 +38,9 @@ export default function Spans() {
<Layout.Body>
<Layout.Main fullWidth>
<PageErrorAlert />
- <PageFiltersContainer>
+ <StarfishPageFilterContainer>
<SpansView moduleName={moduleName} spanCategory={spanCategory} />
- </PageFiltersContainer>
+ </StarfishPageFilterContainer>
</Layout.Main>
</Layout.Body>
</PageErrorProvider>
diff --git a/static/app/views/starfish/views/spans/spansView.tsx b/static/app/views/starfish/views/spans/spansView.tsx
index cf8d8a5a242b34..5f9ee08e519d5a 100644
--- a/static/app/views/starfish/views/spans/spansView.tsx
+++ b/static/app/views/starfish/views/spans/spansView.tsx
@@ -2,11 +2,11 @@ import {Fragment} from 'react';
import styled from '@emotion/styled';
import pick from 'lodash/pick';
-import DatePageFilter from 'sentry/components/datePageFilter';
import {space} from 'sentry/styles/space';
import {fromSorts} from 'sentry/utils/discover/eventView';
import type {Sort} from 'sentry/utils/discover/fields';
import {useLocation} from 'sentry/utils/useLocation';
+import StarfishDatePicker from 'sentry/views/starfish/components/datePicker';
import {ModuleName} from 'sentry/views/starfish/types';
import {QueryParameterNames} from 'sentry/views/starfish/views/queryParameters';
import {ActionSelector} from 'sentry/views/starfish/views/spans/selectors/actionSelector';
@@ -51,7 +51,7 @@ export default function SpansView(props: Props) {
return (
<Fragment>
<FilterOptionsContainer>
- <DatePageFilter alignDropdown="left" />
+ <StarfishDatePicker />
</FilterOptionsContainer>
<PaddedContainer>
diff --git a/static/app/views/starfish/views/webServiceView/endpointOverview/index.tsx b/static/app/views/starfish/views/webServiceView/endpointOverview/index.tsx
index b4f3bba5ec8771..4d204af34976d7 100644
--- a/static/app/views/starfish/views/webServiceView/endpointOverview/index.tsx
+++ b/static/app/views/starfish/views/webServiceView/endpointOverview/index.tsx
@@ -10,7 +10,6 @@ import {getInterval} from 'sentry/components/charts/utils';
import DatePageFilter from 'sentry/components/datePageFilter';
import * as Layout from 'sentry/components/layouts/thirds';
import PageFilterBar from 'sentry/components/organizations/pageFilterBar';
-import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
import {PerformanceLayoutBodyRow} from 'sentry/components/performance/layouts';
import Placeholder from 'sentry/components/placeholder';
import {SegmentedControl} from 'sentry/components/segmentedControl';
@@ -31,6 +30,7 @@ import {normalizeUrl} from 'sentry/utils/withDomainRequired';
import {SidebarSpacer} from 'sentry/views/performance/transactionSummary/utils';
import {ERRORS_COLOR, THROUGHPUT_COLOR} from 'sentry/views/starfish/colours';
import Chart from 'sentry/views/starfish/components/chart';
+import StarfishPageFilterContainer from 'sentry/views/starfish/components/pageFilterContainer';
import {TransactionSamplesTable} from 'sentry/views/starfish/components/samplesTable/transactionSamplesTable';
import {ModuleName} from 'sentry/views/starfish/types';
import formatThroughput from 'sentry/views/starfish/utils/chartValueFormatters/formatThroughput';
@@ -226,7 +226,7 @@ export default function EndpointOverview() {
};
return (
- <PageFiltersContainer>
+ <StarfishPageFilterContainer>
<Layout.Page>
<Layout.Header>
<Layout.HeaderContent>
@@ -326,7 +326,7 @@ export default function EndpointOverview() {
</Layout.Side>
</Layout.Body>
</Layout.Page>
- </PageFiltersContainer>
+ </StarfishPageFilterContainer>
);
}
diff --git a/static/app/views/starfish/views/webServiceView/index.tsx b/static/app/views/starfish/views/webServiceView/index.tsx
index 238a087ca5f4c2..5d762a99510707 100644
--- a/static/app/views/starfish/views/webServiceView/index.tsx
+++ b/static/app/views/starfish/views/webServiceView/index.tsx
@@ -4,7 +4,6 @@ import {Location} from 'history';
import isEqual from 'lodash/isEqual';
import {loadOrganizationTags} from 'sentry/actionCreators/tags';
-import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
import {t} from 'sentry/locale';
import {PageFilters} from 'sentry/types';
@@ -14,11 +13,9 @@ import useOrganization from 'sentry/utils/useOrganization';
import usePrevious from 'sentry/utils/usePrevious';
import useProjects from 'sentry/utils/useProjects';
import withPageFilters from 'sentry/utils/withPageFilters';
+import StarfishPageFilterContainer from 'sentry/views/starfish/components/pageFilterContainer';
-import {
- generateWebServiceEventView,
- getDefaultStatsPeriod,
-} from '../../utils/generatePerformanceEventView';
+import {generateWebServiceEventView} from '../../utils/generatePerformanceEventView';
import {StarfishLanding} from './starfishLanding';
@@ -65,16 +62,7 @@ function WebServiceView({selection, location, router}: Props) {
return (
<SentryDocumentTitle title={t('Starfish')} orgSlug={organization.slug}>
- <PageFiltersContainer
- defaultSelection={{
- datetime: {
- start: null,
- end: null,
- utc: false,
- period: getDefaultStatsPeriod(organization),
- },
- }}
- >
+ <StarfishPageFilterContainer>
<StarfishLanding
router={router}
eventView={eventView}
@@ -84,7 +72,7 @@ function WebServiceView({selection, location, router}: Props) {
selection={selection}
withStaticFilters={withStaticFilters}
/>
- </PageFiltersContainer>
+ </StarfishPageFilterContainer>
</SentryDocumentTitle>
);
}
diff --git a/static/app/views/starfish/views/webServiceView/starfishLanding.tsx b/static/app/views/starfish/views/webServiceView/starfishLanding.tsx
index 71e7e05f22e521..afa1f5a41370d2 100644
--- a/static/app/views/starfish/views/webServiceView/starfishLanding.tsx
+++ b/static/app/views/starfish/views/webServiceView/starfishLanding.tsx
@@ -3,7 +3,6 @@ import {InjectedRouter} from 'react-router';
import styled from '@emotion/styled';
import {Location} from 'history';
-import DatePageFilter from 'sentry/components/datePageFilter';
import * as Layout from 'sentry/components/layouts/thirds';
import PageFilterBar from 'sentry/components/organizations/pageFilterBar';
import ProjectPageFilter from 'sentry/components/projectPageFilter';
@@ -15,6 +14,7 @@ import {
PageErrorAlert,
PageErrorProvider,
} from 'sentry/utils/performance/contexts/pageError';
+import StarfishDatePicker from 'sentry/views/starfish/components/datePicker';
import {StarfishView} from './starfishView';
@@ -32,7 +32,7 @@ export function StarfishLanding(props: Props) {
const pageFilters: React.ReactNode = (
<PageFilterBar condensed>
<ProjectPageFilter />
- <DatePageFilter alignDropdown="left" />
+ <StarfishDatePicker />
</PageFilterBar>
);
|
190105f71e76679597848ef1c43a13afc4f9d5bf
|
2025-02-21 03:19:07
|
Malachi Willey
|
feat(nav): Open what's new in an overlay instead of drawer (#85582)
| false
|
Open what's new in an overlay instead of drawer (#85582)
|
feat
|
diff --git a/static/app/components/nav/primary/whatsNew.spec.tsx b/static/app/components/nav/primary/whatsNew.spec.tsx
index 22d4d0754cd336..6600e9fdc9bd41 100644
--- a/static/app/components/nav/primary/whatsNew.spec.tsx
+++ b/static/app/components/nav/primary/whatsNew.spec.tsx
@@ -64,7 +64,7 @@ describe('WhatsNew', function () {
render(<WhatsNew />);
- expect(await screen.findByTestId('whats-new-badge')).toBeInTheDocument();
+ expect(await screen.findByTestId('whats-new-unread-indicator')).toBeInTheDocument();
MockApiClient.addMockResponse({
url: `/organizations/org-slug/broadcasts/`,
diff --git a/static/app/components/nav/primary/whatsNew.tsx b/static/app/components/nav/primary/whatsNew.tsx
index f151ff454ecfc6..5b70533b2072d8 100644
--- a/static/app/components/nav/primary/whatsNew.tsx
+++ b/static/app/components/nav/primary/whatsNew.tsx
@@ -1,6 +1,8 @@
-import {Fragment, useEffect, useMemo, useRef} from 'react';
+import {Fragment, useEffect, useMemo} from 'react';
+import {useTheme} from '@emotion/react';
+import styled from '@emotion/styled';
+import {FocusScope} from '@react-aria/focus';
-import useDrawer from 'sentry/components/globalDrawer';
import InteractionStateLayer from 'sentry/components/interactionStateLayer';
import LoadingIndicator from 'sentry/components/loadingIndicator';
import {useNavContext} from 'sentry/components/nav/context';
@@ -10,6 +12,7 @@ import {
SidebarItemUnreadIndicator,
} from 'sentry/components/nav/primary/components';
import {NavLayout} from 'sentry/components/nav/types';
+import {Overlay, PositionWrapper} from 'sentry/components/overlay';
import {BroadcastPanelItem} from 'sentry/components/sidebar/broadcastPanelItem';
import SidebarPanelEmpty from 'sentry/components/sidebar/sidebarPanelEmpty';
import {IconBroadcast} from 'sentry/icons';
@@ -25,6 +28,7 @@ import {
} from 'sentry/utils/queryClient';
import useApi from 'sentry/utils/useApi';
import useOrganization from 'sentry/utils/useOrganization';
+import useOverlay from 'sentry/utils/useOverlay';
const MARK_SEEN_DELAY = 1000;
@@ -114,8 +118,6 @@ function WhatsNewContent({unseenPostIds}: {unseenPostIds: string[]}) {
}
export function WhatsNew() {
- const ref = useRef<HTMLButtonElement>(null);
- const {openDrawer, isDrawerOpen, closeDrawer} = useDrawer();
const {data: broadcasts = []} = useFetchBroadcasts();
const unseenPostIds = useMemo(
() => broadcasts.filter(item => !item.hasSeen).map(item => item.id),
@@ -124,21 +126,22 @@ export function WhatsNew() {
const {layout} = useNavContext();
const showLabel = layout === NavLayout.MOBILE;
+ const theme = useTheme();
+
+ const {
+ isOpen,
+ triggerProps: overlayTriggerProps,
+ overlayProps,
+ } = useOverlay({
+ offset: 8,
+ position: 'right-end',
+ isDismissable: true,
+ });
return (
<SidebarItem>
<NavButton
- ref={ref}
- onClick={() => {
- if (isDrawerOpen) {
- closeDrawer();
- } else {
- openDrawer(() => <WhatsNewContent unseenPostIds={unseenPostIds} />, {
- ariaLabel: t("What's New"),
- shouldCloseOnInteractOutside: el => !ref.current?.contains(el),
- });
- }
- }}
+ {...overlayTriggerProps}
aria-label={showLabel ? undefined : t("What's New")}
isMobile={layout === NavLayout.MOBILE}
>
@@ -146,9 +149,24 @@ export function WhatsNew() {
<IconBroadcast />
{showLabel && <span>{t("What's New")}</span>}
{unseenPostIds.length > 0 && (
- <SidebarItemUnreadIndicator data-test-id="whats-new-badge" />
+ <SidebarItemUnreadIndicator data-test-id="whats-new-unread-indicator" />
)}
</NavButton>
+ {isOpen && (
+ <FocusScope autoFocus restoreFocus>
+ <PositionWrapper zIndex={theme.zIndex.dropdown} {...overlayProps}>
+ <ScrollableOverlay>
+ <WhatsNewContent unseenPostIds={unseenPostIds} />
+ </ScrollableOverlay>
+ </PositionWrapper>
+ </FocusScope>
+ )}
</SidebarItem>
);
}
+
+const ScrollableOverlay = styled(Overlay)`
+ max-height: 60vh;
+ width: 400px;
+ overflow-y: auto;
+`;
diff --git a/static/app/components/sidebar/broadcastPanelItem.tsx b/static/app/components/sidebar/broadcastPanelItem.tsx
index 5fc8ec30086095..f540ec9f4034fd 100644
--- a/static/app/components/sidebar/broadcastPanelItem.tsx
+++ b/static/app/components/sidebar/broadcastPanelItem.tsx
@@ -53,7 +53,6 @@ export function BroadcastPanelItem({
const SidebarPanelItemRoot = styled('div')`
line-height: 1.5;
- background: ${p => p.theme.background};
margin: 0 ${space(3)};
padding: ${space(2)} 0;
|
233e65e568f5d6c89ed6b8d29b5785fb01e380f1
|
2024-07-03 22:28:01
|
anthony sottile
|
ref: use concrete dict in HC payloads (#73744)
| false
|
use concrete dict in HC payloads (#73744)
|
ref
|
diff --git a/src/sentry/auth/services/auth/model.py b/src/sentry/auth/services/auth/model.py
index b93cfb55c89853..6fdf721e5ed2f7 100644
--- a/src/sentry/auth/services/auth/model.py
+++ b/src/sentry/auth/services/auth/model.py
@@ -192,7 +192,7 @@ class RpcAuthProvider(RpcModel):
organization_id: int = -1
provider: str = ""
flags: RpcAuthProviderFlags = Field(default_factory=lambda: RpcAuthProviderFlags())
- config: Mapping[str, Any]
+ config: dict[str, Any]
default_role: int = -1
default_global_access: bool = False
@@ -218,7 +218,7 @@ class RpcAuthIdentity(RpcModel):
user_id: int = -1
auth_provider_id: int = -1
ident: str = ""
- data: Mapping[str, Any] = Field(default_factory=dict)
+ data: dict[str, Any] = Field(default_factory=dict)
last_verified: datetime.datetime = Field(default_factory=datetime.datetime.now)
|
f5dfe6b63a74039ec81614f9f07e2814ffa45dad
|
2024-03-13 22:12:33
|
anthony sottile
|
ref: fix flakiness of test_issue_velocity by freezing time (#66872)
| false
|
fix flakiness of test_issue_velocity by freezing time (#66872)
|
ref
|
diff --git a/tests/sentry/issues/test_issue_velocity.py b/tests/sentry/issues/test_issue_velocity.py
index 4f72ace02097c1..0a6ee2715a9f4b 100644
--- a/tests/sentry/issues/test_issue_velocity.py
+++ b/tests/sentry/issues/test_issue_velocity.py
@@ -18,13 +18,14 @@
)
from sentry.tasks.post_process import locks
from sentry.testutils.cases import SnubaTestCase, TestCase
-from sentry.testutils.helpers.datetime import iso_format
+from sentry.testutils.helpers.datetime import freeze_time, iso_format
from sentry.testutils.silo import region_silo_test
WEEK_IN_HOURS = 7 * 24
@region_silo_test
+@freeze_time()
class IssueVelocityTests(TestCase, SnubaTestCase):
def setUp(self):
self.now = timezone.now()
@@ -182,7 +183,7 @@ def test_get_latest_threshold_outdated(self, mock_update):
redis_client.set(THRESHOLD_KEY.format(project_id=self.project.id), 1.2)
redis_client.set(
STALE_DATE_KEY.format(project_id=self.project.id),
- str(self.utcnow - timedelta(days=1)),
+ str(self.utcnow - timedelta(days=1, seconds=1)),
)
mock_update.return_value = 1.5
assert get_latest_threshold(self.project) == 1.5
@@ -244,8 +245,7 @@ def test_update_threshold_simple(self, mock_calculation):
assert redis_client.get("threshold-key") == "5"
stored_date = redis_client.get("date-key")
assert isinstance(stored_date, str)
- # self.utcnow and the datetime.utcnow() used in the update method may vary in milliseconds so we can't do a direct comparison
- assert 0 <= (datetime.fromisoformat(stored_date) - self.utcnow).total_seconds() < 1
+ assert datetime.fromisoformat(stored_date) == self.utcnow
assert redis_client.ttl("threshold-key") == DEFAULT_TTL
assert redis_client.ttl("date-key") == DEFAULT_TTL
@@ -280,7 +280,7 @@ def test_update_threshold_nan(self, mock_calculation):
assert redis_client.get("threshold-key") == "0"
stored_date = redis_client.get("date-key")
assert isinstance(stored_date, str)
- assert 0 <= (datetime.fromisoformat(stored_date) - self.utcnow).total_seconds() < 1
+ assert datetime.fromisoformat(stored_date) == self.utcnow
assert redis_client.ttl("threshold-key") == DEFAULT_TTL
def test_fallback_to_stale(self):
@@ -295,17 +295,10 @@ def test_fallback_to_stale(self):
assert redis_client.get("threshold-key") == "0.5"
stored_date = redis_client.get("date-key")
assert isinstance(stored_date, str)
- assert (
- 0
- <= (
- datetime.fromisoformat(stored_date)
- - (
- self.utcnow
- - timedelta(seconds=TIME_TO_USE_EXISTING_THRESHOLD)
- + timedelta(seconds=FALLBACK_TTL)
- )
- ).total_seconds()
- < 1
+ assert datetime.fromisoformat(stored_date) == (
+ self.utcnow
+ - timedelta(seconds=TIME_TO_USE_EXISTING_THRESHOLD)
+ + timedelta(seconds=FALLBACK_TTL)
)
assert redis_client.ttl("threshold-key") == 86400
@@ -321,17 +314,10 @@ def test_fallback_to_zero(self):
assert redis_client.get("threshold-key") == "0"
stored_date = redis_client.get("date-key")
assert isinstance(stored_date, str)
- assert (
- 0
- <= (
- datetime.fromisoformat(stored_date)
- - (
- self.utcnow
- - timedelta(seconds=TIME_TO_USE_EXISTING_THRESHOLD)
- + timedelta(seconds=FALLBACK_TTL)
- )
- ).total_seconds()
- < 1
+ assert datetime.fromisoformat(stored_date) == (
+ self.utcnow
+ - timedelta(seconds=TIME_TO_USE_EXISTING_THRESHOLD)
+ + timedelta(seconds=FALLBACK_TTL)
)
assert redis_client.ttl("threshold-key") == FALLBACK_TTL
assert redis_client.ttl("date-key") == FALLBACK_TTL
@@ -346,17 +332,10 @@ def test_fallback_to_stale_zero_ttl(self):
assert redis_client.get("threshold-key") == "0"
stored_date = redis_client.get("date-key")
assert isinstance(stored_date, str)
- assert (
- 0
- <= (
- datetime.fromisoformat(stored_date)
- - (
- self.utcnow
- - timedelta(seconds=TIME_TO_USE_EXISTING_THRESHOLD)
- + timedelta(seconds=FALLBACK_TTL)
- )
- ).total_seconds()
- < 1
+ assert datetime.fromisoformat(stored_date) == (
+ self.utcnow
+ - timedelta(seconds=TIME_TO_USE_EXISTING_THRESHOLD)
+ + timedelta(seconds=FALLBACK_TTL)
)
assert redis_client.ttl("threshold-key") == FALLBACK_TTL
|
fcc3dd168a0b654c0225da516d0e2630d9955995
|
2018-02-21 06:52:47
|
Armin Ronacher
|
feat: Kill transaction atomicity in assemble_dif (#7331)
| false
|
Kill transaction atomicity in assemble_dif (#7331)
|
feat
|
diff --git a/src/sentry/tasks/assemble.py b/src/sentry/tasks/assemble.py
index 95c83363dcd52c..bb643ae8422010 100644
--- a/src/sentry/tasks/assemble.py
+++ b/src/sentry/tasks/assemble.py
@@ -3,7 +3,6 @@
import os
import logging
-from django.db import transaction
from sentry.tasks.base import instrumented_task
logger = logging.getLogger(__name__)
@@ -15,66 +14,65 @@ def assemble_dif(project_id, name, checksum, chunks, **kwargs):
ProjectDSymFile, set_assemble_status, BadDif
from sentry.reprocessing import bump_reprocessing_revision
- with transaction.atomic():
- project = Project.objects.filter(id=project_id).get()
- set_assemble_status(project, checksum, ChunkFileState.ASSEMBLING)
-
- # Assemble the chunks into files
- rv = assemble_file(project, name, checksum, chunks,
- file_type='project.dsym')
-
- # If not file has been created this means that the file failed to
- # assemble because of bad input data. Return.
- if rv is None:
- return
-
- file, temp_file = rv
- delete_file = True
- try:
- with temp_file:
- # We only permit split difs to hit this endpoint. The
- # client is required to split them up first or we error.
- try:
- result = dsymfile.detect_dif_from_path(temp_file.name)
- except BadDif as e:
- set_assemble_status(project, checksum, ChunkFileState.ERROR,
- detail=e.args[0])
- return
+ project = Project.objects.filter(id=project_id).get()
+ set_assemble_status(project, checksum, ChunkFileState.ASSEMBLING)
+
+ # Assemble the chunks into files
+ rv = assemble_file(project, name, checksum, chunks,
+ file_type='project.dsym')
- if len(result) != 1:
+ # If not file has been created this means that the file failed to
+ # assemble because of bad input data. Return.
+ if rv is None:
+ return
+
+ file, temp_file = rv
+ delete_file = True
+ try:
+ with temp_file:
+ # We only permit split difs to hit this endpoint. The
+ # client is required to split them up first or we error.
+ try:
+ result = dsymfile.detect_dif_from_path(temp_file.name)
+ except BadDif as e:
+ set_assemble_status(project, checksum, ChunkFileState.ERROR,
+ detail=e.args[0])
+ return
+
+ if len(result) != 1:
+ set_assemble_status(project, checksum, ChunkFileState.ERROR,
+ detail='Contained wrong number of '
+ 'architectures (expected one, got %s)'
+ % len(result))
+ return
+
+ dsym_type, cpu, file_uuid, filename = result[0]
+ dsym, created = dsymfile.create_dsym_from_uuid(
+ project, dsym_type, cpu, file_uuid,
+ os.path.basename(name),
+ file=file)
+ delete_file = False
+ bump_reprocessing_revision(project)
+
+ indicate_success = True
+
+ # If we need to write a symcache we can use the
+ # `generate_symcache` method to attempt to write one.
+ # This way we can also capture down the error if we need
+ # to.
+ if dsym.supports_symcache:
+ symcache, error = ProjectDSymFile.dsymcache.generate_symcache(
+ project, dsym, temp_file)
+ if error is not None:
set_assemble_status(project, checksum, ChunkFileState.ERROR,
- detail='Contained wrong number of '
- 'architectures (expected one, got %s)'
- % len(result))
- return
-
- dsym_type, cpu, file_uuid, filename = result[0]
- dsym, created = dsymfile.create_dsym_from_uuid(
- project, dsym_type, cpu, file_uuid,
- os.path.basename(name),
- file=file)
- delete_file = False
- bump_reprocessing_revision(project)
-
- indicate_success = True
-
- # If we need to write a symcache we can use the
- # `generate_symcache` method to attempt to write one.
- # This way we can also capture down the error if we need
- # to.
- if dsym.supports_symcache:
- symcache, error = ProjectDSymFile.dsymcache.generate_symcache(
- project, dsym, temp_file)
- if error is not None:
- set_assemble_status(project, checksum, ChunkFileState.ERROR,
- detail=error)
- indicate_success = False
-
- if indicate_success:
- set_assemble_status(project, checksum, ChunkFileState.OK)
- finally:
- if delete_file:
- file.delete()
+ detail=error)
+ indicate_success = False
+
+ if indicate_success:
+ set_assemble_status(project, checksum, ChunkFileState.OK)
+ finally:
+ if delete_file:
+ file.delete()
def assemble_file(project, name, checksum, chunks, file_type):
|
89e57bf43554c86bebd9559ba51db0b30ad7c13c
|
2024-10-28 20:38:00
|
anthony sottile
|
ref: avoid clobbering `def redirect` from BaseView (#79756)
| false
|
avoid clobbering `def redirect` from BaseView (#79756)
|
ref
|
diff --git a/pyproject.toml b/pyproject.toml
index 826243d795666e..0a933ee9ee04e2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -336,7 +336,6 @@ module = [
"sentry.utils.services",
"sentry.web.forms.accounts",
"sentry.web.frontend.auth_login",
- "sentry.web.frontend.auth_logout",
"sentry.web.frontend.auth_organization_login",
"sentry.web.frontend.base",
"sentry.web.frontend.group_plugin_action",
diff --git a/src/sentry/web/frontend/auth_logout.py b/src/sentry/web/frontend/auth_logout.py
index f5483ee840263c..e3fbfcddabd6e1 100644
--- a/src/sentry/web/frontend/auth_logout.py
+++ b/src/sentry/web/frontend/auth_logout.py
@@ -12,11 +12,11 @@
class AuthLogoutView(BaseView):
auth_required = False
- def redirect(self, request: HttpRequest) -> HttpResponseBase:
+ def _redirect(self, request: HttpRequest) -> HttpResponseBase:
next_url = request.GET.get(REDIRECT_FIELD_NAME, "")
if not url_has_allowed_host_and_scheme(next_url, allowed_hosts=(request.get_host(),)):
next_url = auth.get_login_url()
- return super().redirect(next_url)
+ return self.redirect(next_url)
def get(self, request: HttpRequest) -> HttpResponseBase:
return self.respond("sentry/logout.html")
@@ -24,4 +24,4 @@ def get(self, request: HttpRequest) -> HttpResponseBase:
def post(self, request: HttpRequest) -> HttpResponseBase:
logout(request)
request.user = AnonymousUser()
- return self.redirect(request)
+ return self._redirect(request)
|
d0de18291cf76827a4f0cccb1ee10a90d3c8756f
|
2023-09-19 02:56:47
|
Evan Purkhiser
|
ref(crons): Move checkin processing logic to a function (#56424)
| false
|
Move checkin processing logic to a function (#56424)
|
ref
|
diff --git a/src/sentry/monitors/consumers/monitor_consumer.py b/src/sentry/monitors/consumers/monitor_consumer.py
index a54053e4129af6..ba2de4939a4921 100644
--- a/src/sentry/monitors/consumers/monitor_consumer.py
+++ b/src/sentry/monitors/consumers/monitor_consumer.py
@@ -234,363 +234,368 @@ def transform_checkin_uuid(
return check_in_guid, use_latest_checkin
-def _process_message(ts: datetime, wrapper: CheckinMessage | ClockPulseMessage) -> None:
- # XXX: Relay does not attach a message type, to properly discriminate the
- # type we add it by default here. This can be removed once the message_type
- # is guaranteed
- if "message_type" not in wrapper:
- wrapper["message_type"] = "check_in"
-
- try:
- try_monitor_tasks_trigger(ts)
- except Exception:
- logger.exception("Failed to trigger monitor tasks", exc_info=True)
-
- # Nothing else to do with clock pulses
- if wrapper["message_type"] == "clock_pulse":
- return
-
- with sentry_sdk.start_transaction(
- op="_process_message",
- name="monitors.monitor_consumer",
- ) as txn:
- params: CheckinPayload = json.loads(wrapper["payload"])
- start_time = to_datetime(float(wrapper["start_time"]))
- project_id = int(wrapper["project_id"])
- source_sdk = wrapper["sdk"]
+def _process_checkin(
+ params: CheckinPayload,
+ start_time: datetime,
+ project_id: int,
+ source_sdk: str,
+ txn: Transaction | Span,
+):
- # Ensure the monitor_slug is slugified, since we are not running this
- # through the MonitorValidator we must do this here.
- monitor_slug = slugify(params["monitor_slug"])[:MAX_SLUG_LENGTH].strip("-")
+ # Ensure the monitor_slug is slugified, since we are not running this
+ # through the MonitorValidator we must do this here.
+ monitor_slug = slugify(params["monitor_slug"])[:MAX_SLUG_LENGTH].strip("-")
- environment = params.get("environment")
- project = Project.objects.get_from_cache(id=project_id)
+ environment = params.get("environment")
+ project = Project.objects.get_from_cache(id=project_id)
- # Strip sdk version to reduce metric cardinality
- sdk_platform = source_sdk.split("/")[0] if source_sdk else "none"
+ # Strip sdk version to reduce metric cardinality
+ sdk_platform = source_sdk.split("/")[0] if source_sdk else "none"
- metric_kwargs = {
- "source": "consumer",
- "sdk_platform": sdk_platform,
- }
+ metric_kwargs = {
+ "source": "consumer",
+ "sdk_platform": sdk_platform,
+ }
- if check_killswitch(metric_kwargs, project, monitor_slug):
- return
+ if check_killswitch(metric_kwargs, project, monitor_slug):
+ return
- if check_ratelimit(metric_kwargs, project, monitor_slug, environment):
- return
+ if check_ratelimit(metric_kwargs, project, monitor_slug, environment):
+ return
- guid, use_latest_checkin = transform_checkin_uuid(
- txn,
- metric_kwargs,
- monitor_slug,
- params["check_in_id"],
- )
+ guid, use_latest_checkin = transform_checkin_uuid(
+ txn,
+ metric_kwargs,
+ monitor_slug,
+ params["check_in_id"],
+ )
- if guid is None:
- return
+ if guid is None:
+ return
- def update_existing_check_in(
- existing_check_in: MonitorCheckIn,
- updated_status: CheckInStatus,
- updated_duration: float,
- new_date_updated: datetime,
+ def update_existing_check_in(
+ existing_check_in: MonitorCheckIn,
+ updated_status: CheckInStatus,
+ updated_duration: float,
+ new_date_updated: datetime,
+ ):
+ if (
+ existing_check_in.project_id != project_id
+ or existing_check_in.monitor_id != monitor.id
+ or existing_check_in.monitor_environment_id != monitor_environment.id
):
- if (
- existing_check_in.project_id != project_id
- or existing_check_in.monitor_id != monitor.id
- or existing_check_in.monitor_environment_id != monitor_environment.id
- ):
- metrics.incr(
- "monitors.checkin.result",
- tags={"source": "consumer", "status": "guid_mismatch"},
- )
- txn.set_tag("result", "guid_mismatch")
- logger.info(
- "monitors.consumer.guid_exists",
- extra={
- "guid": existing_check_in.guid.hex,
- "slug": existing_check_in.monitor.slug,
- "payload_slug": monitor.slug,
- },
- )
- return
-
- if existing_check_in.status in CheckInStatus.FINISHED_VALUES:
- metrics.incr(
- "monitors.checkin.result",
- tags={**metric_kwargs, "status": "checkin_finished"},
- )
- txn.set_tag("result", "checkin_finished")
- logger.info(
- "monitors.consumer.check_in_closed",
- extra={
- "guid": existing_check_in.guid.hex,
- "slug": existing_check_in.monitor.slug,
- "status": existing_check_in.status,
- "updated_status": updated_status,
- },
- )
- return
-
- if updated_duration is None:
- updated_duration = int(
- (start_time - existing_check_in.date_added).total_seconds() * 1000
- )
-
- if not valid_duration(updated_duration):
- metrics.incr(
- "monitors.checkin.result",
- tags={**metric_kwargs, "status": "failed_duration_check"},
- )
- txn.set_tag("result", "failed_duration_check")
- logger.info(
- "monitors.consumer.invalid_implicit_duration",
- extra={
- "guid": existing_check_in.guid.hex,
- "slug": existing_check_in.monitor.slug,
- "duration": updated_duration,
- },
- )
- return
-
- # update date_added for heartbeat
- date_updated = existing_check_in.date_updated
- if updated_status == CheckInStatus.IN_PROGRESS:
- date_updated = new_date_updated
-
- updated_timeout_at = get_new_timeout_at(
- existing_check_in, updated_status, new_date_updated
+ metrics.incr(
+ "monitors.checkin.result",
+ tags={"source": "consumer", "status": "guid_mismatch"},
)
-
- existing_check_in.update(
- status=updated_status,
- duration=updated_duration,
- date_updated=date_updated,
- timeout_at=updated_timeout_at,
+ txn.set_tag("result", "guid_mismatch")
+ logger.info(
+ "monitors.consumer.guid_exists",
+ extra={
+ "guid": existing_check_in.guid.hex,
+ "slug": existing_check_in.monitor.slug,
+ "payload_slug": monitor.slug,
+ },
)
-
return
- try:
- monitor_config = params.pop("monitor_config", None)
-
- params["duration"] = (
- # Duration is specified in seconds from the client, it is
- # stored in the checkin model as milliseconds
- int(params["duration"] * 1000)
- if params.get("duration") is not None
- else None
+ if existing_check_in.status in CheckInStatus.FINISHED_VALUES:
+ metrics.incr(
+ "monitors.checkin.result",
+ tags={**metric_kwargs, "status": "checkin_finished"},
)
-
- validator = MonitorCheckInValidator(
- data=params,
- partial=True,
- context={
- "project": project,
+ txn.set_tag("result", "checkin_finished")
+ logger.info(
+ "monitors.consumer.check_in_closed",
+ extra={
+ "guid": existing_check_in.guid.hex,
+ "slug": existing_check_in.monitor.slug,
+ "status": existing_check_in.status,
+ "updated_status": updated_status,
},
)
+ return
- if not validator.is_valid():
- metrics.incr(
- "monitors.checkin.result",
- tags={**metric_kwargs, "status": "failed_checkin_validation"},
- )
- txn.set_tag("result", "failed_checkin_validation")
- logger.info(
- "monitors.consumer.checkin_validation_failed",
- extra={"guid": guid.hex, **params},
- )
- return
-
- validated_params = validator.validated_data
-
- monitor = _ensure_monitor_with_config(
- project,
- monitor_slug,
- params["monitor_slug"],
- monitor_config,
+ if updated_duration is None:
+ updated_duration = int(
+ (start_time - existing_check_in.date_added).total_seconds() * 1000
)
- if not monitor:
- metrics.incr(
- "monitors.checkin.result",
- tags={**metric_kwargs, "status": "failed_validation"},
- )
- txn.set_tag("result", "failed_validation")
- logger.info(
- "monitors.consumer.monitor_validation_failed",
- extra={"guid": guid.hex, **params},
- )
- return
- except MonitorLimitsExceeded:
+ if not valid_duration(updated_duration):
metrics.incr(
"monitors.checkin.result",
- tags={**metric_kwargs, "status": "failed_monitor_limits"},
+ tags={**metric_kwargs, "status": "failed_duration_check"},
)
- txn.set_tag("result", "failed_monitor_limits")
+ txn.set_tag("result", "failed_duration_check")
logger.info(
- "monitors.consumer.monitor_limit_exceeded",
- extra={"guid": guid.hex, "project": project.id, "slug": monitor_slug},
+ "monitors.consumer.invalid_implicit_duration",
+ extra={
+ "guid": existing_check_in.guid.hex,
+ "slug": existing_check_in.monitor.slug,
+ "duration": updated_duration,
+ },
)
return
- try:
- monitor_environment = MonitorEnvironment.objects.ensure_environment(
- project, monitor, environment
- )
- except MonitorEnvironmentLimitsExceeded:
+ # update date_added for heartbeat
+ date_updated = existing_check_in.date_updated
+ if updated_status == CheckInStatus.IN_PROGRESS:
+ date_updated = new_date_updated
+
+ updated_timeout_at = get_new_timeout_at(existing_check_in, updated_status, new_date_updated)
+
+ existing_check_in.update(
+ status=updated_status,
+ duration=updated_duration,
+ date_updated=date_updated,
+ timeout_at=updated_timeout_at,
+ )
+
+ return
+
+ try:
+ monitor_config = params.pop("monitor_config", None)
+
+ params["duration"] = (
+ # Duration is specified in seconds from the client, it is
+ # stored in the checkin model as milliseconds
+ int(params["duration"] * 1000)
+ if params.get("duration") is not None
+ else None
+ )
+
+ validator = MonitorCheckInValidator(
+ data=params,
+ partial=True,
+ context={
+ "project": project,
+ },
+ )
+
+ if not validator.is_valid():
metrics.incr(
"monitors.checkin.result",
- tags={**metric_kwargs, "status": "failed_monitor_environment_limits"},
+ tags={**metric_kwargs, "status": "failed_checkin_validation"},
)
- txn.set_tag("result", "failed_monitor_environment_limits")
+ txn.set_tag("result", "failed_checkin_validation")
logger.info(
- "monitors.consumer.monitor_environment_limit_exceeded",
- extra={
- "guid": guid.hex,
- "project": project.id,
- "slug": monitor_slug,
- "environment": environment,
- },
+ "monitors.consumer.checkin_validation_failed",
+ extra={"guid": guid.hex, **params},
)
return
- except MonitorEnvironmentValidationFailed:
+
+ validated_params = validator.validated_data
+
+ monitor = _ensure_monitor_with_config(
+ project,
+ monitor_slug,
+ params["monitor_slug"],
+ monitor_config,
+ )
+
+ if not monitor:
metrics.incr(
"monitors.checkin.result",
- tags={**metric_kwargs, "status": "failed_monitor_environment_name_length"},
+ tags={**metric_kwargs, "status": "failed_validation"},
)
- txn.set_tag("result", "failed_monitor_environment_name_length")
+ txn.set_tag("result", "failed_validation")
logger.info(
- "monitors.consumer.monitor_environment_validation_failed",
- extra={
- "guid": guid.hex,
- "project": project.id,
- "slug": monitor_slug,
- "environment": environment,
- },
+ "monitors.consumer.monitor_validation_failed",
+ extra={"guid": guid.hex, **params},
)
return
+ except MonitorLimitsExceeded:
+ metrics.incr(
+ "monitors.checkin.result",
+ tags={**metric_kwargs, "status": "failed_monitor_limits"},
+ )
+ txn.set_tag("result", "failed_monitor_limits")
+ logger.info(
+ "monitors.consumer.monitor_limit_exceeded",
+ extra={"guid": guid.hex, "project": project.id, "slug": monitor_slug},
+ )
+ return
- lock = locks.get(
- f"checkin-creation:{guid.hex}", duration=LOCK_TIMEOUT, name="checkin_creation"
+ try:
+ monitor_environment = MonitorEnvironment.objects.ensure_environment(
+ project, monitor, environment
)
- try:
- # use lock.blocking_acquire() as default lock.acquire() fast fails if lock is in use
- with lock.blocking_acquire(
- INITIAL_LOCK_DELAY, float(LOCK_TIMEOUT), exp_base=LOCK_EXP_BASE
- ), transaction.atomic(router.db_for_write(Monitor)):
- status = getattr(CheckInStatus, validated_params["status"].upper())
- trace_id = validated_params.get("contexts", {}).get("trace", {}).get("trace_id")
-
- try:
- if use_latest_checkin:
- check_in = (
- MonitorCheckIn.objects.select_for_update()
- .filter(monitor_environment=monitor_environment)
- .exclude(status__in=CheckInStatus.FINISHED_VALUES)
- .order_by("-date_added")[:1]
- .get()
- )
- else:
- check_in = MonitorCheckIn.objects.select_for_update().get(
- guid=guid,
- )
+ except MonitorEnvironmentLimitsExceeded:
+ metrics.incr(
+ "monitors.checkin.result",
+ tags={**metric_kwargs, "status": "failed_monitor_environment_limits"},
+ )
+ txn.set_tag("result", "failed_monitor_environment_limits")
+ logger.info(
+ "monitors.consumer.monitor_environment_limit_exceeded",
+ extra={
+ "guid": guid.hex,
+ "project": project.id,
+ "slug": monitor_slug,
+ "environment": environment,
+ },
+ )
+ return
+ except MonitorEnvironmentValidationFailed:
+ metrics.incr(
+ "monitors.checkin.result",
+ tags={**metric_kwargs, "status": "failed_monitor_environment_name_length"},
+ )
+ txn.set_tag("result", "failed_monitor_environment_name_length")
+ logger.info(
+ "monitors.consumer.monitor_environment_validation_failed",
+ extra={
+ "guid": guid.hex,
+ "project": project.id,
+ "slug": monitor_slug,
+ "environment": environment,
+ },
+ )
+ return
- if check_in.monitor_environment_id != monitor_environment.id:
- metrics.incr(
- "monitors.checkin.result",
- tags={
- **metric_kwargs,
- "status": "failed_monitor_environment_guid_match",
- },
- )
- txn.set_tag("result", "failed_monitor_environment_guid_match")
- logger.info(
- "monitors.consumer.monitor_environment_mismatch",
- extra={
- "guid": guid.hex,
- "slug": monitor_slug,
- "organization_id": project.organization_id,
- "environment": monitor_environment.id,
- "payload_environment": check_in.monitor_environment_id,
- },
- )
- return
-
- txn.set_tag("outcome", "process_existing_checkin")
- update_existing_check_in(
- check_in, status, validated_params["duration"], start_time
- )
+ lock = locks.get(f"checkin-creation:{guid.hex}", duration=LOCK_TIMEOUT, name="checkin_creation")
+ try:
+ # use lock.blocking_acquire() as default lock.acquire() fast fails if lock is in use
+ with lock.blocking_acquire(
+ INITIAL_LOCK_DELAY, float(LOCK_TIMEOUT), exp_base=LOCK_EXP_BASE
+ ), transaction.atomic(router.db_for_write(Monitor)):
+ status = getattr(CheckInStatus, validated_params["status"].upper())
+ trace_id = validated_params.get("contexts", {}).get("trace", {}).get("trace_id")
- except MonitorCheckIn.DoesNotExist:
- # Infer the original start time of the check-in from the duration.
- # Note that the clock of this worker may be off from what Relay is reporting.
- date_added = start_time
- duration = validated_params["duration"]
- if duration is not None:
- date_added -= timedelta(milliseconds=duration)
-
- # When was this check-in expected to have happened?
- expected_time = monitor_environment.next_checkin
-
- monitor_config = monitor.get_validated_config()
- timeout_at = get_timeout_at(monitor_config, status, date_added)
-
- check_in, created = MonitorCheckIn.objects.get_or_create(
- defaults={
- "duration": duration,
- "status": status,
- "date_added": date_added,
- "date_updated": start_time,
- "expected_time": expected_time,
- "timeout_at": timeout_at,
- "monitor_config": monitor_config,
- "trace_id": trace_id,
- },
- project_id=project_id,
- monitor=monitor,
- monitor_environment=monitor_environment,
- guid=guid,
- )
- if not created:
- txn.set_tag("outcome", "process_existing_checkin_race_condition")
- update_existing_check_in(check_in, status, duration, start_time)
- else:
- txn.set_tag("outcome", "create_new_checkin")
- signal_first_checkin(project, monitor)
-
- if check_in.status == CheckInStatus.ERROR:
- mark_failed(
- monitor_environment,
- start_time,
- occurrence_context={"trace_id": trace_id},
+ try:
+ if use_latest_checkin:
+ check_in = (
+ MonitorCheckIn.objects.select_for_update()
+ .filter(monitor_environment=monitor_environment)
+ .exclude(status__in=CheckInStatus.FINISHED_VALUES)
+ .order_by("-date_added")[:1]
+ .get()
)
else:
- mark_ok(check_in, start_time)
+ check_in = MonitorCheckIn.objects.select_for_update().get(
+ guid=guid,
+ )
- metrics.incr(
- "monitors.checkin.result",
- tags={**metric_kwargs, "status": "complete"},
+ if check_in.monitor_environment_id != monitor_environment.id:
+ metrics.incr(
+ "monitors.checkin.result",
+ tags={
+ **metric_kwargs,
+ "status": "failed_monitor_environment_guid_match",
+ },
+ )
+ txn.set_tag("result", "failed_monitor_environment_guid_match")
+ logger.info(
+ "monitors.consumer.monitor_environment_mismatch",
+ extra={
+ "guid": guid.hex,
+ "slug": monitor_slug,
+ "organization_id": project.organization_id,
+ "environment": monitor_environment.id,
+ "payload_environment": check_in.monitor_environment_id,
+ },
+ )
+ return
+
+ txn.set_tag("outcome", "process_existing_checkin")
+ update_existing_check_in(check_in, status, validated_params["duration"], start_time)
+
+ except MonitorCheckIn.DoesNotExist:
+ # Infer the original start time of the check-in from the duration.
+ # Note that the clock of this worker may be off from what Relay is reporting.
+ date_added = start_time
+ duration = validated_params["duration"]
+ if duration is not None:
+ date_added -= timedelta(milliseconds=duration)
+
+ # When was this check-in expected to have happened?
+ expected_time = monitor_environment.next_checkin
+
+ monitor_config = monitor.get_validated_config()
+ timeout_at = get_timeout_at(monitor_config, status, date_added)
+
+ check_in, created = MonitorCheckIn.objects.get_or_create(
+ defaults={
+ "duration": duration,
+ "status": status,
+ "date_added": date_added,
+ "date_updated": start_time,
+ "expected_time": expected_time,
+ "timeout_at": timeout_at,
+ "monitor_config": monitor_config,
+ "trace_id": trace_id,
+ },
+ project_id=project_id,
+ monitor=monitor,
+ monitor_environment=monitor_environment,
+ guid=guid,
)
- except UnableToAcquireLock:
- metrics.incr(
- "monitors.checkin.result",
- tags={**metric_kwargs, "status": "failed_checkin_creation_lock"},
- )
- txn.set_tag("result", "failed_checkin_creation_lock")
- logger.info(
- "monitors.consumer.lock_failed",
- extra={"guid": guid.hex, "slug": monitor_slug},
- )
- except Exception:
- # Skip this message and continue processing in the consumer.
+ if not created:
+ txn.set_tag("outcome", "process_existing_checkin_race_condition")
+ update_existing_check_in(check_in, status, duration, start_time)
+ else:
+ txn.set_tag("outcome", "create_new_checkin")
+ signal_first_checkin(project, monitor)
+
+ if check_in.status == CheckInStatus.ERROR:
+ mark_failed(
+ monitor_environment,
+ start_time,
+ occurrence_context={"trace_id": trace_id},
+ )
+ else:
+ mark_ok(check_in, start_time)
+
metrics.incr(
"monitors.checkin.result",
- tags={**metric_kwargs, "status": "error"},
+ tags={**metric_kwargs, "status": "complete"},
)
- txn.set_tag("result", "error")
- logger.exception("Failed to process check-in", exc_info=True)
+ except UnableToAcquireLock:
+ metrics.incr(
+ "monitors.checkin.result",
+ tags={**metric_kwargs, "status": "failed_checkin_creation_lock"},
+ )
+ txn.set_tag("result", "failed_checkin_creation_lock")
+ logger.info(
+ "monitors.consumer.lock_failed",
+ extra={"guid": guid.hex, "slug": monitor_slug},
+ )
+ except Exception:
+ # Skip this message and continue processing in the consumer.
+ metrics.incr(
+ "monitors.checkin.result",
+ tags={**metric_kwargs, "status": "error"},
+ )
+ txn.set_tag("result", "error")
+ logger.exception("Failed to process check-in", exc_info=True)
+
+
+def _process_message(ts: datetime, wrapper: CheckinMessage | ClockPulseMessage) -> None:
+ # XXX: Relay does not attach a message type, to properly discriminate the
+ # type we add it by default here. This can be removed once the message_type
+ # is guaranteed
+ if "message_type" not in wrapper:
+ wrapper["message_type"] = "check_in"
+
+ try:
+ try_monitor_tasks_trigger(ts)
+ except Exception:
+ logger.exception("Failed to trigger monitor tasks", exc_info=True)
+
+ # Nothing else to do with clock pulses
+ if wrapper["message_type"] == "clock_pulse":
+ return
+
+ with sentry_sdk.start_transaction(
+ op="_process_message",
+ name="monitors.monitor_consumer",
+ ) as txn:
+ params: CheckinPayload = json.loads(wrapper["payload"])
+ start_time = to_datetime(float(wrapper["start_time"]))
+ project_id = int(wrapper["project_id"])
+ source_sdk = wrapper["sdk"]
+
+ _process_checkin(params, start_time, project_id, source_sdk, txn)
class StoreMonitorCheckInStrategyFactory(ProcessingStrategyFactory[KafkaPayload]):
|
dd2ae197f552460765e1cf2fd2a78fcf4e20d30b
|
2022-11-10 06:30:01
|
Vu Luong
|
ref(inputField): Use InputGroup to show ControlState (#40741)
| false
|
Use InputGroup to show ControlState (#40741)
|
ref
|
diff --git a/docs-ui/stories/components/form-fields.stories.js b/docs-ui/stories/components/form-fields.stories.js
index aaf35c5db0a61f..b3fdfabd8cd60b 100644
--- a/docs-ui/stories/components/form-fields.stories.js
+++ b/docs-ui/stories/components/form-fields.stories.js
@@ -37,6 +37,12 @@ export const _TextField = () => (
label="Simple Text Field with Placeholder"
placeholder="This is placeholder text"
/>
+ <TextField
+ name="textfieldrequired"
+ label="Required Text Field"
+ placeholder="Type text and then delete it"
+ required
+ />
<TextField
name="simpletextfieldvaluedisabled"
label="Disabled - Simple Text Field with Value"
@@ -50,13 +56,6 @@ export const _TextField = () => (
placeholder="This is placeholder text in a disabled field"
disabled
/>
- <TextField
- name="textfieldflexiblecontrol"
- label="Text Field With Flexible Control State Size"
- placeholder="Type text and then delete it"
- required
- flexibleControlStateSize
- />
<TextField
name="textfielddisabled"
label="Text field with disabled reason"
diff --git a/static/app/components/forms/fields/inputField.tsx b/static/app/components/forms/fields/inputField.tsx
index 6e5339183ed5aa..b0e527a0ab39e9 100644
--- a/static/app/components/forms/fields/inputField.tsx
+++ b/static/app/components/forms/fields/inputField.tsx
@@ -1,5 +1,12 @@
import FormField, {FormFieldProps} from 'sentry/components/forms/formField';
-import Input, {InputProps} from 'sentry/components/input';
+import FormFieldControlState from 'sentry/components/forms/formField/controlState';
+import FormModel from 'sentry/components/forms/model';
+import {
+ Input,
+ InputGroup,
+ InputProps,
+ InputTrailingItems,
+} from 'sentry/components/inputGroup';
export interface InputFieldProps
extends Omit<FormFieldProps, 'children'>,
@@ -28,19 +35,33 @@ function defaultField({
onChange,
onBlur,
onKeyDown,
+ model,
+ name,
+ hideControlState,
...rest
}: {
+ model: FormModel;
+ name: string;
onBlur: OnEvent;
onChange: OnEvent;
onKeyDown: OnEvent;
+ hideControlState?: boolean;
}) {
return (
- <Input
- onBlur={e => onBlur(e.target.value, e)}
- onKeyDown={e => onKeyDown((e.target as any).value, e)}
- onChange={e => onChange(e.target.value, e)}
- {...rest}
- />
+ <InputGroup>
+ <Input
+ onBlur={e => onBlur(e.target.value, e)}
+ onKeyDown={e => onKeyDown((e.target as any).value, e)}
+ onChange={e => onChange(e.target.value, e)}
+ name={name}
+ {...rest}
+ />
+ {!hideControlState && (
+ <InputTrailingItems>
+ <FormFieldControlState model={model} name={name} />
+ </InputTrailingItems>
+ )}
+ </InputGroup>
);
}
@@ -48,10 +69,12 @@ function defaultField({
* InputField should be thought of as a "base" field, and generally not used
* within the Form itself.
*/
-function InputField({field = defaultField, ...props}: InputFieldProps) {
+function InputField({field = defaultField, hideControlState, ...props}: InputFieldProps) {
return (
- <FormField {...props}>
- {({children: _children, ...otherFieldProps}) => field(otherFieldProps)}
+ <FormField {...props} hideControlState flexibleControlStateSize>
+ {({children: _children, ...otherFieldProps}) =>
+ field({...otherFieldProps, hideControlState})
+ }
</FormField>
);
}
diff --git a/static/app/views/settings/organizationDeveloperSettings/sentryApplicationDetails.spec.jsx b/static/app/views/settings/organizationDeveloperSettings/sentryApplicationDetails.spec.jsx
index d4e76ee5b34024..ff0c6d1723fb53 100644
--- a/static/app/views/settings/organizationDeveloperSettings/sentryApplicationDetails.spec.jsx
+++ b/static/app/views/settings/organizationDeveloperSettings/sentryApplicationDetails.spec.jsx
@@ -16,7 +16,7 @@ describe('Sentry Application Details', function () {
let editAppRequest;
const verifyInstallToggle = 'Switch[name="verifyInstall"]';
- const redirectUrlInput = 'Input[name="redirectUrl"]';
+ const redirectUrlInput = 'input[name="redirectUrl"]';
const maskedValue = '*'.repeat(64);
beforeEach(() => {
@@ -61,15 +61,15 @@ describe('Sentry Application Details', function () {
it('saves', function () {
wrapper
- .find('Input[name="name"]')
+ .find('input[name="name"]')
.simulate('change', {target: {value: 'Test App'}});
wrapper
- .find('Input[name="author"]')
+ .find('input[name="author"]')
.simulate('change', {target: {value: 'Sentry'}});
wrapper
- .find('Input[name="webhookUrl"]')
+ .find('input[name="webhookUrl"]')
.simulate('change', {target: {value: 'https://webhook.com'}});
wrapper
@@ -324,7 +324,7 @@ describe('Sentry Application Details', function () {
it('removing webhookURL unsets isAlertable and changes webhookDisabled to true', () => {
expect(wrapper.find(PermissionsObserver).prop('webhookDisabled')).toBe(false);
expect(wrapper.find('Switch[name="isAlertable"]').prop('isActive')).toBe(true);
- wrapper.find('Input[name="webhookUrl"]').simulate('change', {target: {value: ''}});
+ wrapper.find('input[name="webhookUrl"]').simulate('change', {target: {value: ''}});
expect(wrapper.find('Switch[name="isAlertable"]').prop('isActive')).toBe(false);
expect(wrapper.find(PermissionsObserver).prop('webhookDisabled')).toBe(true);
expect(wrapper.find(JsonForm).prop('additionalFieldProps')).toEqual({
|
179f40582ea09cf12f58bb94787401cec3e8301a
|
2022-02-07 23:26:49
|
Vu Luong
|
feat(test): Add triggerPress and selectDropdownMenuItem test utility functions (#31591)
| false
|
Add triggerPress and selectDropdownMenuItem test utility functions (#31591)
|
feat
|
diff --git a/static/app/components/actions/ignore.tsx b/static/app/components/actions/ignore.tsx
index 7c5251af8a1d3c..424d05c3288ce2 100644
--- a/static/app/components/actions/ignore.tsx
+++ b/static/app/components/actions/ignore.tsx
@@ -157,7 +157,7 @@ const IgnoreActions = ({
],
})),
{
- key: 'for-custom',
+ key: 'until-reoccur-custom',
label: t('Custom'),
onAction: () => openCustomIgnoreCount(),
},
@@ -193,7 +193,7 @@ const IgnoreActions = ({
],
})),
{
- key: 'for-custom',
+ key: 'until-affect-custom',
label: t('Custom'),
onAction: () => openCustomIgnoreUserCount(),
},
diff --git a/static/app/components/dropdownMenuItemV2.tsx b/static/app/components/dropdownMenuItemV2.tsx
index 956cdc0fe2ff7e..b30c82ed0fc588 100644
--- a/static/app/components/dropdownMenuItemV2.tsx
+++ b/static/app/components/dropdownMenuItemV2.tsx
@@ -208,6 +208,7 @@ const MenuItem = withRouter(
ref={ref}
as={renderAs}
isDisabled={isDisabled}
+ data-test-id={item.key}
{...props}
{...(isSubmenuTrigger && {role: 'menuitemradio'})}
>
diff --git a/tests/js/sentry-test/dropdownMenu.tsx b/tests/js/sentry-test/dropdownMenu.tsx
new file mode 100644
index 00000000000000..12c6e573d5421b
--- /dev/null
+++ b/tests/js/sentry-test/dropdownMenu.tsx
@@ -0,0 +1,92 @@
+import {act} from 'react-dom/test-utils';
+import {ReactWrapper} from 'enzyme'; // eslint-disable-line no-restricted-imports
+
+import {triggerPress} from 'sentry-test/utils';
+
+type SelectDropdownItemProps = {
+ /**
+ * They key(s) of menu item(s) to select. If the item is nested inside a
+ * sub-menu, then this must be an array containing the keys of ancestor
+ * items, with the highest-level item first, and the last item to select
+ * last.
+ */
+ itemKey: string | string[];
+ /**
+ * The root node wrapper, must be provided to run wrapper.update() after
+ * each step.
+ */
+ wrapper: ReactWrapper;
+ /**
+ * Optional arguments to help the function better locate the dropdown
+ * control. Useful if there are more than one control inside `wrapper`. If
+ * provided, before each selection, the function will first call
+ * wrapper.find([prefix])[.first()/.last()/.at([at])]
+ */
+ specifiers?: {
+ prefix: string;
+ at?: number;
+ first?: boolean;
+ last?: boolean;
+ };
+ /**
+ * Selector for the dropdown's trigger button, useful for custom trigger
+ * components whose display name is different from 'TriggerButton'.
+ */
+ triggerSelector?: string;
+};
+
+/**
+ * Select a dropdown menu item. This function works for both top-level and
+ * nested items.
+ */
+export async function selectDropdownMenuItem({
+ wrapper,
+ itemKey,
+ specifiers,
+ triggerSelector = 'DropdownTrigger',
+}: SelectDropdownItemProps) {
+ /**
+ * Returns a ReactWrapper which we'll use to find the
+ * dropdown menu control. If `specifiers` is not provided, returns the root
+ * wrapper by default.
+ */
+ function getSpecifiedWrap(): ReactWrapper {
+ if (!specifiers) {
+ return wrapper;
+ }
+ const prefixedWrap = wrapper.find(specifiers.prefix);
+
+ if (specifiers.first) {
+ return prefixedWrap.first();
+ }
+ if (specifiers.last) {
+ return prefixedWrap.last();
+ }
+ if (typeof specifiers.at === 'number') {
+ return prefixedWrap.at(specifiers.at);
+ }
+ return prefixedWrap;
+ }
+
+ // Open the top-level dropdown menu
+ await act(async () => {
+ triggerPress(getSpecifiedWrap().find(triggerSelector));
+
+ await tick();
+ wrapper.update();
+ });
+
+ // Select menu item(s) via itemKey
+ await act(async () => {
+ const keys = Array.isArray(itemKey) ? itemKey : [itemKey];
+
+ for (const key of keys) {
+ triggerPress(
+ getSpecifiedWrap().find(`MenuWrap MenuItemWrap[data-test-id="${key}"]`)
+ );
+
+ await tick();
+ wrapper.update();
+ }
+ });
+}
diff --git a/tests/js/sentry-test/utils.tsx b/tests/js/sentry-test/utils.tsx
index 09055650135780..b1b05561adf8ad 100644
--- a/tests/js/sentry-test/utils.tsx
+++ b/tests/js/sentry-test/utils.tsx
@@ -27,3 +27,23 @@ export function textWithMarkupMatcher(textMatch: string | RegExp) {
return findTextWithMarkup(element, textMatch);
};
}
+
+/**
+ * Trigger onPress events on components that use react-aria (e.g. the dropdown
+ * menu). These components require more complex events than what enzyme can
+ * simulate with `.simulate('click')`. Preferably, we should use the
+ * 'user-event' library from react testing library. This function is a
+ * workaround for test files that still use enzyme. Read more:
+ * https://react-spectrum.adobe.com/react-spectrum/testing.html#triggering-events
+ */
+export function triggerPress(element) {
+ element.prop('onClick')({
+ button: 0,
+ detail: 0,
+ nativeEvent: {detail: 0},
+ currentTarget: element.getDOMNode(),
+ target: element.getDOMNode(),
+ stopPropagation: () => {},
+ preventDefault: () => {},
+ });
+}
diff --git a/tests/js/spec/components/actions/resolve.spec.jsx b/tests/js/spec/components/actions/resolve.spec.jsx
index 45031d5523e4ee..8216b57a5acfb9 100644
--- a/tests/js/spec/components/actions/resolve.spec.jsx
+++ b/tests/js/spec/components/actions/resolve.spec.jsx
@@ -1,6 +1,6 @@
import {Fragment} from 'react';
-import {act} from 'react-dom/test-utils';
+import {selectDropdownMenuItem} from 'sentry-test/dropdownMenu';
import {mountWithTheme} from 'sentry-test/enzyme';
import {selectByValue} from 'sentry-test/select-new';
@@ -207,27 +207,9 @@ describe('ResolveActions', function () {
TestStubs.routerContext()
);
- // Necessary wrapper to simulate click event on dropdown menu buttons,
- // see: https://react-spectrum.adobe.com/react-spectrum/testing.html#triggering-events
- const triggerPress = element => {
- element.prop('onClick')({
- button: 0,
- detail: 0,
- nativeEvent: {detail: 0},
- currentTarget: element.getDOMNode(),
- target: element.getDOMNode(),
- stopPropagation: () => {},
- });
- };
-
- await act(async () => {
- triggerPress(wrapper.find('DropdownTrigger'));
- await tick();
- wrapper.update();
-
- triggerPress(wrapper.find('MenuItemWrap').last());
- await tick();
- wrapper.update();
+ await selectDropdownMenuItem({
+ wrapper,
+ itemKey: 'another-release',
});
expect(wrapper.find('CustomResolutionModal Select').prop('options')).toEqual([
diff --git a/tests/js/spec/views/issueList/actions.spec.jsx b/tests/js/spec/views/issueList/actions.spec.jsx
index 676d0a55b9cfd7..68fde106ab70e6 100644
--- a/tests/js/spec/views/issueList/actions.spec.jsx
+++ b/tests/js/spec/views/issueList/actions.spec.jsx
@@ -1,5 +1,4 @@
-import {act} from 'react-dom/test-utils';
-
+import {selectDropdownMenuItem} from 'sentry-test/dropdownMenu';
import {mountWithTheme} from 'sentry-test/enzyme';
import {initializeOrg} from 'sentry-test/initializeOrg';
import {mountGlobalModal} from 'sentry-test/modal';
@@ -227,40 +226,10 @@ describe('IssueListActions', function () {
.find('IssueListActions')
.setState({allInQuerySelected: false, anySelected: true});
- // Necessary wrapper to simulate click event on dropdown menu buttons,
- // see: https://react-spectrum.adobe.com/react-spectrum/testing.html#triggering-events
- const triggerPress = element => {
- element.prop('onClick')({
- button: 0,
- detail: 0,
- nativeEvent: {detail: 0},
- currentTarget: element.getDOMNode(),
- target: element.getDOMNode(),
- stopPropagation: () => {},
- });
- };
-
- // Open ignore dropdown menu
- await act(async () => {
- triggerPress(wrapper.find('IgnoreActions DropdownTrigger'));
-
- await tick();
- wrapper.update();
- });
-
- // Open the last sub-menu and select the last menu item
- await act(async () => {
- triggerPress(wrapper.find('IgnoreActions MenuWrap MenuItemWrap').last());
-
- await tick();
- wrapper.update();
-
- triggerPress(
- wrapper.find('IgnoreActions MenuWrap MenuWrap MenuItemWrap').last()
- );
-
- await tick();
- wrapper.update();
+ await selectDropdownMenuItem({
+ wrapper,
+ specifiers: {prefix: 'IgnoreActions'},
+ itemKey: ['until-affect', 'until-affect-custom'],
});
const modal = await mountGlobalModal();
|
8f4bda000e0405dc18f611e09191aa8d6073d181
|
2020-09-04 00:10:23
|
Evan Purkhiser
|
ref(py3): Normalize signing byte / string usage (#20549)
| false
|
Normalize signing byte / string usage (#20549)
|
ref
|
diff --git a/src/sentry/integrations/msteams/link_identity.py b/src/sentry/integrations/msteams/link_identity.py
index 27bb8ef0c5e905..6ea26c784e24c6 100644
--- a/src/sentry/integrations/msteams/link_identity.py
+++ b/src/sentry/integrations/msteams/link_identity.py
@@ -35,7 +35,7 @@ class MsTeamsLinkIdentityView(BaseView):
@transaction_start("MsTeamsLinkIdentityView")
@never_cache
def handle(self, request, signed_params):
- params = unsign(signed_params.encode("ascii", errors="ignore"))
+ params = unsign(signed_params)
organization, integration, idp = get_identity(
request.user, params["organization_id"], params["integration_id"]
diff --git a/src/sentry/integrations/msteams/unlink_identity.py b/src/sentry/integrations/msteams/unlink_identity.py
index 3dfcdda21e83cc..abff256ed59195 100644
--- a/src/sentry/integrations/msteams/unlink_identity.py
+++ b/src/sentry/integrations/msteams/unlink_identity.py
@@ -31,7 +31,7 @@ class MsTeamsUnlinkIdentityView(BaseView):
@transaction_start("MsTeamsUnlinkIdentityView")
@never_cache
def handle(self, request, signed_params):
- params = unsign(signed_params.encode("ascii", errors="ignore"))
+ params = unsign(signed_params)
if request.method != "POST":
return render_to_response(
diff --git a/src/sentry/integrations/slack/link_identity.py b/src/sentry/integrations/slack/link_identity.py
index 039540031b7ef2..4eeee1f8bfabea 100644
--- a/src/sentry/integrations/slack/link_identity.py
+++ b/src/sentry/integrations/slack/link_identity.py
@@ -37,7 +37,7 @@ class SlackLinkIdentityView(BaseView):
@transaction_start("SlackLinkIdentityView")
@never_cache
def handle(self, request, signed_params):
- params = unsign(signed_params.encode("ascii", errors="ignore"))
+ params = unsign(signed_params)
organization, integration, idp = get_identity(
request.user, params["organization_id"], params["integration_id"]
diff --git a/src/sentry/integrations/slack/unlink_identity.py b/src/sentry/integrations/slack/unlink_identity.py
index 6ecdbf2695e03e..03719b9d56064b 100644
--- a/src/sentry/integrations/slack/unlink_identity.py
+++ b/src/sentry/integrations/slack/unlink_identity.py
@@ -37,7 +37,7 @@ class SlackUnlinkIdentityView(BaseView):
@transaction_start("SlackUnlinkIdentityView")
@never_cache
def handle(self, request, signed_params):
- params = unsign(signed_params.encode("ascii", errors="ignore"))
+ params = unsign(signed_params)
organization, integration, idp = get_identity(
request.user, params["organization_id"], params["integration_id"]
diff --git a/src/sentry/utils/signing.py b/src/sentry/utils/signing.py
index b56f9da38a0a67..5574049306d156 100644
--- a/src/sentry/utils/signing.py
+++ b/src/sentry/utils/signing.py
@@ -5,6 +5,7 @@
import base64
+from django.utils.encoding import force_bytes, force_text
from django.core.signing import TimestampSigner
from sentry.utils.json import dumps, loads
@@ -12,13 +13,27 @@
def sign(**kwargs):
- return base64.urlsafe_b64encode(TimestampSigner(salt=SALT).sign(dumps(kwargs))).rstrip("=")
+ """
+ Signs all passed kwargs and produces a base64 string which may be passed to
+ unsign which will verify the string has not been tampered with.
+ """
+ return force_text(
+ base64.urlsafe_b64encode(
+ TimestampSigner(salt=SALT).sign(dumps(kwargs)).encode("utf-8")
+ ).rstrip(b"=")
+ )
def unsign(data, max_age=60 * 60 * 24 * 2):
- return loads(TimestampSigner(salt=SALT).unsign(urlsafe_b64decode(data), max_age=max_age))
+ """
+ Unsign a signed base64 string. Accepts the base64 value as a string or bytes
+ """
+ return loads(
+ TimestampSigner(salt=SALT).unsign(urlsafe_b64decode(data).decode("utf-8"), max_age=max_age)
+ )
def urlsafe_b64decode(b64string):
+ b64string = force_bytes(b64string)
padded = b64string + b"=" * (4 - len(b64string) % 4)
return base64.urlsafe_b64decode(padded)
diff --git a/src/sentry/web/frontend/msteams_extension_configuration.py b/src/sentry/web/frontend/msteams_extension_configuration.py
index 3fab60dec0abb2..f2b51debf85fab 100644
--- a/src/sentry/web/frontend/msteams_extension_configuration.py
+++ b/src/sentry/web/frontend/msteams_extension_configuration.py
@@ -22,7 +22,5 @@ def map_params_to_state(self, params):
params = params.copy()
signed_params = params["signed_params"]
del params["signed_params"]
- params.update(
- unsign(signed_params.encode("ascii", errors="ignore"), max_age=INSTALL_EXPIRATION_TIME)
- )
+ params.update(unsign(signed_params, max_age=INSTALL_EXPIRATION_TIME,))
return params
diff --git a/tests/sentry/integrations/msteams/test_unlink_identity.py b/tests/sentry/integrations/msteams/test_unlink_identity.py
index 36facdd5218df3..5620c3ce39ede4 100644
--- a/tests/sentry/integrations/msteams/test_unlink_identity.py
+++ b/tests/sentry/integrations/msteams/test_unlink_identity.py
@@ -70,7 +70,7 @@ def test_basic_flow(self):
)
signed_params = unlink_url.split("/")[-2]
- params = unsign(signed_params.encode("ascii", errors="ignore"))
+ params = unsign(signed_params)
assert params == {
"conversation_id": self.conversation_id,
"service_url": "https://smba.trafficmanager.net/amer",
|
66e0b64024ede1b93d8143cf1869e19afe409530
|
2023-03-08 01:49:33
|
Cathy Teng
|
chore(scim): return error schema (#45484)
| false
|
return error schema (#45484)
|
chore
|
diff --git a/src/sentry/scim/endpoints/members.py b/src/sentry/scim/endpoints/members.py
index 6f33a5c0b762d1..c68195bf5b38d7 100644
--- a/src/sentry/scim/endpoints/members.py
+++ b/src/sentry/scim/endpoints/members.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from typing import Any, Dict, Union
import sentry_sdk
@@ -20,6 +22,7 @@
from sentry.api.base import region_silo_endpoint
from sentry.api.bases.organizationmember import OrganizationMemberEndpoint
from sentry.api.endpoints.organization_member.index import OrganizationMemberSerializer
+from sentry.api.exceptions import ResourceDoesNotExist
from sentry.api.paginator import GenericOffsetPaginator
from sentry.api.serializers import serialize
from sentry.api.serializers.models.organization_member import (
@@ -140,6 +143,25 @@ class OrganizationSCIMMemberDetails(SCIMEndpoint, OrganizationMemberEndpoint):
permission_classes = (OrganizationSCIMMemberPermission,)
public = {"GET", "DELETE", "PATCH"}
+ def convert_args(
+ self,
+ request: Request,
+ organization_slug: str,
+ member_id: str = "me",
+ *args: Any,
+ **kwargs: Any,
+ ) -> tuple[Any, Any]:
+ try:
+ args, kwargs = super().convert_args(
+ request, organization_slug, member_id, *args, **kwargs
+ )
+ return args, kwargs
+ except ResourceDoesNotExist:
+ raise SCIMApiError(
+ status_code=ResourceDoesNotExist.status_code,
+ detail=ResourceDoesNotExist.default_detail,
+ )
+
def _delete_member(self, request: Request, organization, member):
audit_data = member.get_audit_log_data()
if member.is_only_owner():
diff --git a/tests/apidocs/endpoints/scim/test_member_details.py b/tests/apidocs/endpoints/scim/test_member_details.py
index 12265026111e12..30488635bc5798 100644
--- a/tests/apidocs/endpoints/scim/test_member_details.py
+++ b/tests/apidocs/endpoints/scim/test_member_details.py
@@ -24,3 +24,12 @@ def test_delete(self):
response = self.client.delete(self.url)
request = RequestFactory().delete(self.url)
self.validate_schema(request, response)
+
+ def test_get_invalid(self):
+ url = reverse(
+ "sentry-api-0-organization-scim-member-details",
+ kwargs={"organization_slug": self.organization.slug, "member_id": 321},
+ )
+ response = self.client.get(url)
+ assert response.status_code == 404
+ assert response.data["schemas"] == ["urn:ietf:params:scim:api:messages:2.0:Error"]
|
66055f27ac221ba42b643df92eb752f3b6fec4f3
|
2023-09-11 23:54:12
|
Richard Ortenberg
|
fix(crons): Reduce check_missing timeouts (#56008)
| false
|
Reduce check_missing timeouts (#56008)
|
fix
|
diff --git a/src/sentry/monitors/tasks.py b/src/sentry/monitors/tasks.py
index 5f2982746e7db5..cf60c6d977759c 100644
--- a/src/sentry/monitors/tasks.py
+++ b/src/sentry/monitors/tasks.py
@@ -153,8 +153,8 @@ def clock_pulse(current_datetime=None):
@instrumented_task(
name="sentry.monitors.tasks.check_missing",
- time_limit=30,
- soft_time_limit=25,
+ time_limit=15,
+ soft_time_limit=10,
silo_mode=SiloMode.REGION,
)
def check_missing(current_datetime: datetime):
|
0150e18c692118f2d1dc925ca8f1431f76560708
|
2023-09-27 05:41:40
|
Josh Ferge
|
fix(bug-reports): add feedback to ignored modules (#56991)
| false
|
add feedback to ignored modules (#56991)
|
fix
|
diff --git a/src/sentry/testutils/pytest/sentry.py b/src/sentry/testutils/pytest/sentry.py
index 785725adcf1a78..3e04ff7f3e0e93 100644
--- a/src/sentry/testutils/pytest/sentry.py
+++ b/src/sentry/testutils/pytest/sentry.py
@@ -254,6 +254,7 @@ def pytest_configure(config: pytest.Config) -> None:
# This is a hack to force django to sync the database state from the models rather than use migrations.
settings.MIGRATION_MODULES["sentry"] = None # type: ignore[assignment]
settings.MIGRATION_MODULES["hybridcloud"] = None # type: ignore[assignment]
+ settings.MIGRATION_MODULES["feedback"] = None # type: ignore[assignment]
asset_version_patcher = mock.patch(
"sentry.runner.initializer.get_asset_version", return_value="{version}"
|
7f64faac4954d33f2c9dfe4ac6cc70396087459f
|
2024-09-19 21:20:11
|
Christinarlong
|
ref(sentry_apps): Move SentryAppInstallationToken to sentry_apps (#77734)
| false
|
Move SentryAppInstallationToken to sentry_apps (#77734)
|
ref
|
diff --git a/src/sentry/api/endpoints/integrations/sentry_apps/internal_app_token/details.py b/src/sentry/api/endpoints/integrations/sentry_apps/internal_app_token/details.py
index e82e75015a3c47..302ee27a4c140f 100644
--- a/src/sentry/api/endpoints/integrations/sentry_apps/internal_app_token/details.py
+++ b/src/sentry/api/endpoints/integrations/sentry_apps/internal_app_token/details.py
@@ -13,7 +13,7 @@
PARTNERSHIP_RESTRICTED_ERROR_MESSAGE,
)
from sentry.models.apitoken import ApiToken
-from sentry.models.integrations.sentry_app_installation_token import SentryAppInstallationToken
+from sentry.sentry_apps.models.sentry_app_installation_token import SentryAppInstallationToken
@control_silo_endpoint
diff --git a/src/sentry/deletions/__init__.py b/src/sentry/deletions/__init__.py
index 8096f3c9b213b1..f80ded434a15ed 100644
--- a/src/sentry/deletions/__init__.py
+++ b/src/sentry/deletions/__init__.py
@@ -101,6 +101,7 @@ def load_defaults() -> None:
from sentry.monitors import models as monitor_models
from sentry.sentry_apps.models.sentry_app import SentryApp
from sentry.sentry_apps.models.sentry_app_installation import SentryAppInstallation
+ from sentry.sentry_apps.models.sentry_app_installation_token import SentryAppInstallationToken
from sentry.snuba import models as snuba_models
from . import defaults
@@ -168,7 +169,7 @@ def load_defaults() -> None:
default_manager.register(SentryApp, defaults.SentryAppDeletionTask)
default_manager.register(SentryAppInstallation, defaults.SentryAppInstallationDeletionTask)
default_manager.register(
- models.SentryAppInstallationToken, defaults.SentryAppInstallationTokenDeletionTask
+ SentryAppInstallationToken, defaults.SentryAppInstallationTokenDeletionTask
)
default_manager.register(models.ServiceHook, defaults.ServiceHookDeletionTask)
default_manager.register(models.SavedSearch, BulkModelDeletionTask)
diff --git a/src/sentry/deletions/defaults/sentry_app_installation.py b/src/sentry/deletions/defaults/sentry_app_installation.py
index 78884463c695fe..cefeb358b76c6c 100644
--- a/src/sentry/deletions/defaults/sentry_app_installation.py
+++ b/src/sentry/deletions/defaults/sentry_app_installation.py
@@ -8,7 +8,7 @@ def get_child_relations(self, instance):
from sentry.models.integrations.sentry_app_installation_for_provider import (
SentryAppInstallationForProvider,
)
- from sentry.models.integrations.sentry_app_installation_token import (
+ from sentry.sentry_apps.models.sentry_app_installation_token import (
SentryAppInstallationToken,
)
diff --git a/src/sentry/integrations/vercel/integration.py b/src/sentry/integrations/vercel/integration.py
index 45068ff401d777..b0ef97aaabf0c1 100644
--- a/src/sentry/integrations/vercel/integration.py
+++ b/src/sentry/integrations/vercel/integration.py
@@ -22,12 +22,12 @@
from sentry.models.integrations.sentry_app_installation_for_provider import (
SentryAppInstallationForProvider,
)
-from sentry.models.integrations.sentry_app_installation_token import SentryAppInstallationToken
from sentry.organizations.services.organization import RpcOrganizationSummary
from sentry.pipeline import NestedPipelineView
from sentry.projects.services.project_key import project_key_service
from sentry.sentry_apps.logic import SentryAppCreator
from sentry.sentry_apps.models.sentry_app_installation import SentryAppInstallation
+from sentry.sentry_apps.models.sentry_app_installation_token import SentryAppInstallationToken
from sentry.shared_integrations.exceptions import ApiError, IntegrationError
from sentry.users.models.user import User
from sentry.utils.http import absolute_uri
diff --git a/src/sentry/integrations/vercel/webhook.py b/src/sentry/integrations/vercel/webhook.py
index e4eeff6f93bae7..7813b1ce9b2a23 100644
--- a/src/sentry/integrations/vercel/webhook.py
+++ b/src/sentry/integrations/vercel/webhook.py
@@ -22,9 +22,9 @@
from sentry.models.integrations.sentry_app_installation_for_provider import (
SentryAppInstallationForProvider,
)
-from sentry.models.integrations.sentry_app_installation_token import SentryAppInstallationToken
from sentry.models.project import Project
from sentry.projects.services.project import project_service
+from sentry.sentry_apps.models.sentry_app_installation_token import SentryAppInstallationToken
from sentry.shared_integrations.exceptions import IntegrationError
from sentry.utils.audit import create_audit_entry
from sentry.utils.http import absolute_uri
diff --git a/src/sentry/models/apitoken.py b/src/sentry/models/apitoken.py
index 743592f28a20fd..fffd9ee7eea67a 100644
--- a/src/sentry/models/apitoken.py
+++ b/src/sentry/models/apitoken.py
@@ -351,10 +351,10 @@ def sanitize_relocation_json(
@property
def organization_id(self) -> int | None:
- from sentry.models.integrations.sentry_app_installation_token import (
+ from sentry.sentry_apps.models.sentry_app_installation import SentryAppInstallation
+ from sentry.sentry_apps.models.sentry_app_installation_token import (
SentryAppInstallationToken,
)
- from sentry.sentry_apps.models.sentry_app_installation import SentryAppInstallation
try:
installation = SentryAppInstallation.objects.get_by_api_token(self.id).get()
diff --git a/src/sentry/models/integrations/__init__.py b/src/sentry/models/integrations/__init__.py
index 4e073fcc530d95..9ff5ab0268bb43 100644
--- a/src/sentry/models/integrations/__init__.py
+++ b/src/sentry/models/integrations/__init__.py
@@ -2,7 +2,6 @@
"SentryApp",
"SentryAppComponent",
"SentryAppInstallationForProvider",
- "SentryAppInstallationToken",
)
@@ -12,5 +11,4 @@
from sentry.models.integrations.sentry_app_installation_for_provider import (
SentryAppInstallationForProvider,
)
-from sentry.models.integrations.sentry_app_installation_token import SentryAppInstallationToken
from sentry.sentry_apps.models.sentry_app import SentryApp
diff --git a/src/sentry/sentry_apps/installations.py b/src/sentry/sentry_apps/installations.py
index f37a81444acadc..777f91b6bffe30 100644
--- a/src/sentry/sentry_apps/installations.py
+++ b/src/sentry/sentry_apps/installations.py
@@ -13,9 +13,9 @@
from sentry.models.apiapplication import ApiApplication
from sentry.models.apigrant import ApiGrant
from sentry.models.apitoken import ApiToken
-from sentry.models.integrations.sentry_app_installation_token import SentryAppInstallationToken
from sentry.sentry_apps.models.sentry_app import SentryApp
from sentry.sentry_apps.models.sentry_app_installation import SentryAppInstallation
+from sentry.sentry_apps.models.sentry_app_installation_token import SentryAppInstallationToken
from sentry.sentry_apps.services.hook import hook_service
from sentry.tasks.sentry_apps import installation_webhook
from sentry.users.models.user import User
diff --git a/src/sentry/sentry_apps/models/__init__.py b/src/sentry/sentry_apps/models/__init__.py
index c2665e429fdb8a..f9ae46e1f736c5 100644
--- a/src/sentry/sentry_apps/models/__init__.py
+++ b/src/sentry/sentry_apps/models/__init__.py
@@ -1,4 +1,5 @@
from .sentry_app import SentryApp
from .sentry_app_installation import SentryAppInstallation
+from .sentry_app_installation_token import SentryAppInstallationToken
-__all__ = ("SentryApp", "SentryAppInstallation")
+__all__ = ("SentryApp", "SentryAppInstallationToken", "SentryAppInstallation")
diff --git a/src/sentry/models/integrations/sentry_app_installation_token.py b/src/sentry/sentry_apps/models/sentry_app_installation_token.py
similarity index 100%
rename from src/sentry/models/integrations/sentry_app_installation_token.py
rename to src/sentry/sentry_apps/models/sentry_app_installation_token.py
diff --git a/src/sentry/sentry_apps/services/app/impl.py b/src/sentry/sentry_apps/services/app/impl.py
index c72db356434989..e9f55fda34f14d 100644
--- a/src/sentry/sentry_apps/services/app/impl.py
+++ b/src/sentry/sentry_apps/services/app/impl.py
@@ -12,13 +12,13 @@
from sentry.hybridcloud.rpc.filter_query import FilterQueryDatabaseImpl, OpaqueSerializedResponse
from sentry.mediators import alert_rule_actions
from sentry.models.integrations.sentry_app_component import SentryAppComponent
-from sentry.models.integrations.sentry_app_installation_token import SentryAppInstallationToken
from sentry.sentry_apps.logic import SentryAppCreator
from sentry.sentry_apps.models.sentry_app import SentryApp
from sentry.sentry_apps.models.sentry_app_installation import (
SentryAppInstallation,
prepare_sentry_app_components,
)
+from sentry.sentry_apps.models.sentry_app_installation_token import SentryAppInstallationToken
from sentry.sentry_apps.services.app import (
AppService,
RpcAlertRuleActionResult,
diff --git a/tests/sentry/api/endpoints/test_project_index.py b/tests/sentry/api/endpoints/test_project_index.py
index 03791ff9738773..095984e0192f1b 100644
--- a/tests/sentry/api/endpoints/test_project_index.py
+++ b/tests/sentry/api/endpoints/test_project_index.py
@@ -9,9 +9,9 @@
schedule_hybrid_cloud_foreign_key_jobs_control,
)
from sentry.models.apitoken import ApiToken
-from sentry.models.integrations.sentry_app_installation_token import SentryAppInstallationToken
from sentry.models.project import Project
from sentry.models.projectkey import ProjectKey
+from sentry.sentry_apps.models.sentry_app_installation_token import SentryAppInstallationToken
from sentry.silo.base import SiloMode
from sentry.silo.safety import unguarded_write
from sentry.testutils.cases import APITestCase
diff --git a/tests/sentry/api/endpoints/test_sentry_apps.py b/tests/sentry/api/endpoints/test_sentry_apps.py
index d8fbb1dc8e8612..ffe2760e16bca2 100644
--- a/tests/sentry/api/endpoints/test_sentry_apps.py
+++ b/tests/sentry/api/endpoints/test_sentry_apps.py
@@ -14,11 +14,11 @@
from sentry import deletions
from sentry.constants import SentryAppStatus
from sentry.models.apitoken import ApiToken
-from sentry.models.integrations.sentry_app_installation_token import SentryAppInstallationToken
from sentry.models.organization import Organization
from sentry.models.organizationmember import OrganizationMember
from sentry.sentry_apps.models.sentry_app import MASKED_VALUE, SentryApp
from sentry.sentry_apps.models.sentry_app_installation import SentryAppInstallation
+from sentry.sentry_apps.models.sentry_app_installation_token import SentryAppInstallationToken
from sentry.silo.base import SiloMode
from sentry.testutils.cases import APITestCase
from sentry.testutils.helpers import Feature, with_feature
diff --git a/tests/sentry/deletions/test_sentry_installation_tokens.py b/tests/sentry/deletions/test_sentry_installation_tokens.py
index 1b5e34c6aeb76e..90781c19ebce95 100644
--- a/tests/sentry/deletions/test_sentry_installation_tokens.py
+++ b/tests/sentry/deletions/test_sentry_installation_tokens.py
@@ -1,7 +1,7 @@
from sentry import deletions
from sentry.models.apitoken import ApiToken
-from sentry.models.integrations.sentry_app_installation_token import SentryAppInstallationToken
from sentry.sentry_apps.models.sentry_app_installation import SentryAppInstallation
+from sentry.sentry_apps.models.sentry_app_installation_token import SentryAppInstallationToken
from sentry.testutils.cases import TestCase
from sentry.testutils.silo import control_silo_test
diff --git a/tests/sentry/integrations/vercel/test_integration.py b/tests/sentry/integrations/vercel/test_integration.py
index fd0a349b16043d..133e6b7c769d81 100644
--- a/tests/sentry/integrations/vercel/test_integration.py
+++ b/tests/sentry/integrations/vercel/test_integration.py
@@ -13,11 +13,11 @@
from sentry.models.integrations.sentry_app_installation_for_provider import (
SentryAppInstallationForProvider,
)
-from sentry.models.integrations.sentry_app_installation_token import SentryAppInstallationToken
from sentry.models.project import Project
from sentry.models.projectkey import ProjectKey, ProjectKeyStatus
from sentry.models.scheduledeletion import ScheduledDeletion
from sentry.sentry_apps.models.sentry_app_installation import SentryAppInstallation
+from sentry.sentry_apps.models.sentry_app_installation_token import SentryAppInstallationToken
from sentry.silo.base import SiloMode
from sentry.testutils.cases import IntegrationTestCase
from sentry.testutils.silo import assume_test_silo_mode, control_silo_test
diff --git a/tests/sentry/integrations/vercel/test_webhook.py b/tests/sentry/integrations/vercel/test_webhook.py
index bd213911be1ee5..952ff8b9c2991a 100644
--- a/tests/sentry/integrations/vercel/test_webhook.py
+++ b/tests/sentry/integrations/vercel/test_webhook.py
@@ -13,7 +13,7 @@
SIGNATURE,
)
from sentry import VERSION
-from sentry.models.integrations.sentry_app_installation_token import SentryAppInstallationToken
+from sentry.sentry_apps.models.sentry_app_installation_token import SentryAppInstallationToken
from sentry.silo.base import SiloMode
from sentry.testutils.cases import APITestCase
from sentry.testutils.helpers import override_options
diff --git a/tests/sentry/models/test_apitoken.py b/tests/sentry/models/test_apitoken.py
index 12a06e77a4fb93..5cc25a6c6e0d30 100644
--- a/tests/sentry/models/test_apitoken.py
+++ b/tests/sentry/models/test_apitoken.py
@@ -7,8 +7,8 @@
from sentry.conf.server import SENTRY_SCOPE_HIERARCHY_MAPPING, SENTRY_SCOPES
from sentry.hybridcloud.models import ApiTokenReplica
from sentry.models.apitoken import ApiToken, NotSupported, PlaintextSecretAlreadyRead
-from sentry.models.integrations.sentry_app_installation_token import SentryAppInstallationToken
from sentry.sentry_apps.models.sentry_app_installation import SentryAppInstallation
+from sentry.sentry_apps.models.sentry_app_installation_token import SentryAppInstallationToken
from sentry.silo.base import SiloMode
from sentry.testutils.cases import TestCase
from sentry.testutils.outbox import outbox_runner
diff --git a/tests/sentry/ratelimits/utils/test_get_ratelimit_key.py b/tests/sentry/ratelimits/utils/test_get_ratelimit_key.py
index 498a52aabab53d..38f61e52a38a84 100644
--- a/tests/sentry/ratelimits/utils/test_get_ratelimit_key.py
+++ b/tests/sentry/ratelimits/utils/test_get_ratelimit_key.py
@@ -9,10 +9,10 @@
from sentry.auth.system import SystemToken
from sentry.hybridcloud.models.apitokenreplica import ApiTokenReplica
from sentry.models.apitoken import ApiToken
-from sentry.models.integrations.sentry_app_installation_token import SentryAppInstallationToken
from sentry.ratelimits import get_rate_limit_config, get_rate_limit_key
from sentry.ratelimits.config import RateLimitConfig
from sentry.sentry_apps.models.sentry_app_installation import SentryAppInstallation
+from sentry.sentry_apps.models.sentry_app_installation_token import SentryAppInstallationToken
from sentry.testutils.cases import TestCase
from sentry.testutils.silo import all_silo_test, assume_test_silo_mode_of
from sentry.types.ratelimit import RateLimit, RateLimitCategory
diff --git a/tests/sentry/models/test_sentryappinstallationtoken.py b/tests/sentry/sentry_apps/models/test_sentryappinstallationtoken.py
similarity index 95%
rename from tests/sentry/models/test_sentryappinstallationtoken.py
rename to tests/sentry/sentry_apps/models/test_sentryappinstallationtoken.py
index 600094306c6241..9c22242552be7b 100644
--- a/tests/sentry/models/test_sentryappinstallationtoken.py
+++ b/tests/sentry/sentry_apps/models/test_sentryappinstallationtoken.py
@@ -3,8 +3,8 @@
from sentry.models.integrations.sentry_app_installation_for_provider import (
SentryAppInstallationForProvider,
)
-from sentry.models.integrations.sentry_app_installation_token import SentryAppInstallationToken
from sentry.sentry_apps.models.sentry_app_installation import SentryAppInstallation
+from sentry.sentry_apps.models.sentry_app_installation_token import SentryAppInstallationToken
from sentry.testutils.cases import TestCase
from sentry.testutils.silo import control_silo_test
diff --git a/tests/sentry/sentry_apps/test_sentry_app_installation_token_creator.py b/tests/sentry/sentry_apps/test_sentry_app_installation_token_creator.py
index 50f1636fc2e90a..fb5639b478b256 100644
--- a/tests/sentry/sentry_apps/test_sentry_app_installation_token_creator.py
+++ b/tests/sentry/sentry_apps/test_sentry_app_installation_token_creator.py
@@ -1,12 +1,12 @@
from datetime import UTC, datetime
from unittest.mock import patch
-from sentry.models.integrations.sentry_app_installation_token import SentryAppInstallationToken
from sentry.sentry_apps.installations import (
SentryAppInstallationCreator,
SentryAppInstallationTokenCreator,
)
from sentry.sentry_apps.models.sentry_app_installation import SentryAppInstallation
+from sentry.sentry_apps.models.sentry_app_installation_token import SentryAppInstallationToken
from sentry.testutils.cases import TestCase
from sentry.testutils.silo import control_silo_test
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.